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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1314  ! raeburn     4: # $Id: lonnet.pm,v 1.1313 2016/07/01 19:59:46 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',
1.1314  ! raeburn  2205:                                   'coursecategories','autoenroll'],$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.1314  ! raeburn  2331:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
        !          2332:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
        !          2333:     }
1.1219    raeburn  2334:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2335:     return %domdefaults;
                   2336: }
                   2337: 
1.1311    raeburn  2338: sub course_portal_url {
                   2339:     my ($cnum,$cdom) = @_;
                   2340:     my $chome = &homeserver($cnum,$cdom);
                   2341:     my $hostname = &hostname($chome);
                   2342:     my $protocol = $protocol{$chome};
                   2343:     $protocol = 'http' if ($protocol ne 'https');
                   2344:     my %domdefaults = &get_domain_defaults($cdom);
                   2345:     my $firsturl;
                   2346:     if ($domdefaults{'portal_def'}) {
                   2347:         $firsturl = $domdefaults{'portal_def'};
                   2348:     } else {
                   2349:         $firsturl = $protocol.'://'.$hostname;
                   2350:     }
                   2351:     return $firsturl;
                   2352: }
                   2353: 
1.344     www      2354: # --------------------------------------------------- Assign a key to a student
                   2355: 
                   2356: sub assign_access_key {
1.364     www      2357: #
                   2358: # a valid key looks like uname:udom#comments
                   2359: # comments are being appended
                   2360: #
1.498     www      2361:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2362:     $kdom=
1.620     albertel 2363:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2364:     $knum=
1.620     albertel 2365:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2366:     $cdom=
1.620     albertel 2367:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2368:     $cnum=
1.620     albertel 2369:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2370:     $udom=$env{'user.name'} unless (defined($udom));
                   2371:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2372:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2373:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2374:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2375:                                                   # assigned to this person
                   2376:                                                   # - this should not happen,
1.345     www      2377:                                                   # unless something went wrong
                   2378:                                                   # the first time around
                   2379: # ready to assign
1.364     www      2380:         $logentry=$1.'; '.$logentry;
1.496     www      2381:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2382:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2383: # key now belongs to user
1.346     www      2384: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2385:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2386:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2387:                 return 'ok';
                   2388:             } else {
                   2389:                 return 
                   2390:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2391: 	    }
                   2392:         } else {
                   2393:             return 'error: Could not assign key, try again later.';
                   2394:         }
1.364     www      2395:     } elsif (!$existing{$ckey}) {
1.345     www      2396: # the key does not exist
                   2397: 	return 'error: The key does not exist';
                   2398:     } else {
                   2399: # the key is somebody else's
                   2400: 	return 'error: The key is already in use';
                   2401:     }
1.344     www      2402: }
                   2403: 
1.364     www      2404: # ------------------------------------------ put an additional comment on a key
                   2405: 
                   2406: sub comment_access_key {
                   2407: #
                   2408: # a valid key looks like uname:udom#comments
                   2409: # comments are being appended
                   2410: #
                   2411:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2412:     $cdom=
1.620     albertel 2413:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2414:     $cnum=
1.620     albertel 2415:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2416:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2417:     if ($existing{$ckey}) {
                   2418:         $existing{$ckey}.='; '.$logentry;
                   2419: # ready to assign
1.367     www      2420:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2421:                                                  $cdom,$cnum) eq 'ok') {
                   2422: 	    return 'ok';
                   2423:         } else {
                   2424: 	    return 'error: Count not store comment.';
                   2425:         }
                   2426:     } else {
                   2427: # the key does not exist
                   2428: 	return 'error: The key does not exist';
                   2429:     }
                   2430: }
                   2431: 
1.344     www      2432: # ------------------------------------------------------ Generate a set of keys
                   2433: 
                   2434: sub generate_access_keys {
1.364     www      2435:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2436:     $cdom=
1.620     albertel 2437:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2438:     $cnum=
1.620     albertel 2439:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2440:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2441:     unless (($cdom) && ($cnum)) { return 0; }
                   2442:     if ($number>10000) { return 0; }
                   2443:     sleep(2); # make sure don't get same seed twice
                   2444:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2445:     my $total=0;
                   2446:     for (my $i=1;$i<=$number;$i++) {
                   2447:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2448:                   sprintf("%lx",int(100000*rand)).'-'.
                   2449:                   sprintf("%lx",int(100000*rand));
                   2450:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2451:        $newkey=~s/0/h/g; # and also 0 and O
                   2452:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2453:        if ($existing{$newkey}) {
                   2454:            $i--;
                   2455:        } else {
1.364     www      2456: 	  if (&put('accesskeys',
                   2457:               { $newkey => '# generated '.localtime().
1.620     albertel 2458:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2459:                            '; '.$logentry },
                   2460: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2461:               $total++;
                   2462: 	  }
                   2463:        }
                   2464:     }
1.620     albertel 2465:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2466:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2467:     return $total;
                   2468: }
                   2469: 
                   2470: # ------------------------------------------------------- Validate an accesskey
                   2471: 
                   2472: sub validate_access_key {
                   2473:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2474:     $cdom=
1.620     albertel 2475:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2476:     $cnum=
1.620     albertel 2477:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2478:     $udom=$env{'user.domain'} unless (defined($udom));
                   2479:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2480:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2481:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2482: }
                   2483: 
                   2484: # ------------------------------------- Find the section of student in a course
1.652     albertel 2485: sub devalidate_getsection_cache {
                   2486:     my ($udom,$unam,$courseid)=@_;
                   2487:     my $hashid="$udom:$unam:$courseid";
                   2488:     &devalidate_cache_new('getsection',$hashid);
                   2489: }
1.298     matthew  2490: 
1.815     albertel 2491: sub courseid_to_courseurl {
                   2492:     my ($courseid) = @_;
                   2493:     #already url style courseid
                   2494:     return $courseid if ($courseid =~ m{^/});
                   2495: 
                   2496:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2497: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2498: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2499: 	return "/$cdom/$cnum";
                   2500:     }
                   2501: 
                   2502:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2503:     if (exists($courseinfo{'num'})) {
                   2504: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2505:     }
                   2506: 
                   2507:     return undef;
                   2508: }
                   2509: 
1.298     matthew  2510: sub getsection {
                   2511:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2512:     my $cachetime=1800;
1.551     albertel 2513: 
                   2514:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2515:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2516:     if (defined($cached)) { return $result; }
                   2517: 
1.298     matthew  2518:     my %Pending; 
                   2519:     my %Expired;
                   2520:     #
                   2521:     # Each role can either have not started yet (pending), be active, 
                   2522:     #    or have expired.
                   2523:     #
                   2524:     # If there is an active role, we are done.
                   2525:     #
                   2526:     # If there is more than one role which has not started yet, 
                   2527:     #     choose the one which will start sooner
                   2528:     # If there is one role which has not started yet, return it.
                   2529:     #
                   2530:     # If there is more than one expired role, choose the one which ended last.
                   2531:     # If there is a role which has expired, return it.
                   2532:     #
1.815     albertel 2533:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2534:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2535:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2536:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2537:         my $section=$1;
                   2538:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2539:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2540:         my $now=time;
1.548     albertel 2541:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2542:             $Expired{$end}=$section;
                   2543:             next;
                   2544:         }
1.548     albertel 2545:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2546:             $Pending{$start}=$section;
                   2547:             next;
                   2548:         }
1.599     albertel 2549:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2550:     }
                   2551:     #
                   2552:     # Presumedly there will be few matching roles from the above
                   2553:     # loop and the sorting time will be negligible.
                   2554:     if (scalar(keys(%Pending))) {
                   2555:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2556:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2557:     } 
                   2558:     if (scalar(keys(%Expired))) {
                   2559:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2560:         my $time = pop(@sorted);
1.599     albertel 2561:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2562:     }
1.599     albertel 2563:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2564: }
1.70      www      2565: 
1.599     albertel 2566: sub save_cache {
                   2567:     &purge_remembered();
1.722     albertel 2568:     #&Apache::loncommon::validate_page();
1.620     albertel 2569:     undef(%env);
1.780     albertel 2570:     undef($env_loaded);
1.599     albertel 2571: }
1.452     albertel 2572: 
1.599     albertel 2573: my $to_remember=-1;
                   2574: my %remembered;
                   2575: my %accessed;
                   2576: my $kicks=0;
                   2577: my $hits=0;
1.849     albertel 2578: sub make_key {
                   2579:     my ($name,$id) = @_;
1.872     albertel 2580:     if (length($id) > 65 
                   2581: 	&& length(&escape($id)) > 200) {
                   2582: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2583:     }
1.849     albertel 2584:     return &escape($name.':'.$id);
                   2585: }
                   2586: 
1.599     albertel 2587: sub devalidate_cache_new {
                   2588:     my ($name,$id,$debug) = @_;
                   2589:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2590:     $id=&make_key($name,$id);
1.599     albertel 2591:     $memcache->delete($id);
                   2592:     delete($remembered{$id});
                   2593:     delete($accessed{$id});
                   2594: }
                   2595: 
                   2596: sub is_cached_new {
                   2597:     my ($name,$id,$debug) = @_;
1.849     albertel 2598:     $id=&make_key($name,$id);
1.599     albertel 2599:     if (exists($remembered{$id})) {
1.1133    foxr     2600: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2601: 	$accessed{$id}=[&gettimeofday()];
                   2602: 	$hits++;
                   2603: 	return ($remembered{$id},1);
                   2604:     }
                   2605:     my $value = $memcache->get($id);
                   2606:     if (!(defined($value))) {
                   2607: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2608: 	return (undef,undef);
1.416     albertel 2609:     }
1.599     albertel 2610:     if ($value eq '__undef__') {
                   2611: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2612: 	$value=undef;
                   2613:     }
                   2614:     &make_room($id,$value,$debug);
                   2615:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2616:     return ($value,1);
                   2617: }
                   2618: 
                   2619: sub do_cache_new {
                   2620:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2621:     $id=&make_key($name,$id);
1.599     albertel 2622:     my $setvalue=$value;
                   2623:     if (!defined($setvalue)) {
                   2624: 	$setvalue='__undef__';
                   2625:     }
1.623     albertel 2626:     if (!defined($time) ) {
                   2627: 	$time=600;
                   2628:     }
1.599     albertel 2629:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2630:     my $result = $memcache->set($id,$setvalue,$time);
                   2631:     if (! $result) {
1.872     albertel 2632: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2633: 	$memcache->disconnect_all();
1.872     albertel 2634:     }
1.600     albertel 2635:     # need to make a copy of $value
1.919     albertel 2636:     &make_room($id,$value,$debug);
1.599     albertel 2637:     return $value;
                   2638: }
                   2639: 
                   2640: sub make_room {
                   2641:     my ($id,$value,$debug)=@_;
1.919     albertel 2642: 
                   2643:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2644:                                     : $value;
1.599     albertel 2645:     if ($to_remember<0) { return; }
                   2646:     $accessed{$id}=[&gettimeofday()];
                   2647:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2648:     my $to_kick;
                   2649:     my $max_time=0;
                   2650:     foreach my $other (keys(%accessed)) {
                   2651: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2652: 	    $to_kick=$other;
                   2653: 	    $max_time=&tv_interval($accessed{$other});
                   2654: 	}
                   2655:     }
                   2656:     delete($remembered{$to_kick});
                   2657:     delete($accessed{$to_kick});
                   2658:     $kicks++;
                   2659:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2660:     return;
                   2661: }
                   2662: 
1.599     albertel 2663: sub purge_remembered {
1.604     albertel 2664:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2665:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2666:     undef(%remembered);
                   2667:     undef(%accessed);
1.428     albertel 2668: }
1.70      www      2669: # ------------------------------------- Read an entry from a user's environment
                   2670: 
                   2671: sub userenvironment {
                   2672:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2673:     my $items;
                   2674:     foreach my $item (@what) {
                   2675:         $items.=&escape($item).'&';
                   2676:     }
                   2677:     $items=~s/\&$//;
1.70      www      2678:     my %returnhash=();
1.1009    raeburn  2679:     my $uhome = &homeserver($unam,$udom);
                   2680:     unless ($uhome eq 'no_host') {
                   2681:         my @answer=split(/\&/, 
                   2682:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2683:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2684:             return %returnhash;
                   2685:         }
1.1009    raeburn  2686:         my $i;
                   2687:         for ($i=0;$i<=$#what;$i++) {
                   2688: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2689:         }
1.70      www      2690:     }
                   2691:     return %returnhash;
1.1       albertel 2692: }
                   2693: 
1.617     albertel 2694: # ---------------------------------------------------------- Get a studentphoto
                   2695: sub studentphoto {
                   2696:     my ($udom,$unam,$ext) = @_;
                   2697:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2698:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2699:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2700:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2701:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2702:             } else {
                   2703:                 my ($result,$perm_reqd)=
1.707     albertel 2704: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2705:                 if ($result eq 'ok') {
                   2706:                     if (!($perm_reqd eq 'yes')) {
                   2707:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2708:                     }
                   2709:                 }
                   2710:             }
                   2711:         }
                   2712:     } else {
                   2713:         my ($result,$perm_reqd) = 
1.707     albertel 2714: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2715:         if ($result eq 'ok') {
                   2716:             if (!($perm_reqd eq 'yes')) {
                   2717:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2718:             }
                   2719:         }
                   2720:     }
                   2721:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2722: }
                   2723: 
                   2724: sub retrievestudentphoto {
                   2725:     my ($udom,$unam,$ext,$type) = @_;
                   2726:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2727:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2728:     if ($ret eq 'ok') {
                   2729:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2730:         if ($type eq 'thumbnail') {
                   2731:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2732:         }
                   2733:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2734:         return $tokenurl;
                   2735:     } else {
                   2736:         if ($type eq 'thumbnail') {
                   2737:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2738:         } else { 
                   2739:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2740:         }
1.617     albertel 2741:     }
                   2742: }
                   2743: 
1.263     www      2744: # -------------------------------------------------------------------- New chat
                   2745: 
                   2746: sub chatsend {
1.724     raeburn  2747:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2748:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2749:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2750:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2751:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2752: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2753: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2754: }
                   2755: 
                   2756: # ------------------------------------------ Find current version of a resource
                   2757: 
                   2758: sub getversion {
                   2759:     my $fname=&clutter(shift);
1.1189    raeburn  2760:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2761:     return &currentversion(&filelocation('',$fname));
                   2762: }
                   2763: 
                   2764: sub currentversion {
                   2765:     my $fname=shift;
                   2766:     my $author=$fname;
                   2767:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2768:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2769:     my $home=&homeserver($uname,$udom);
1.292     www      2770:     if ($home eq 'no_host') { 
                   2771:         return -1; 
                   2772:     }
1.1112    www      2773:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2774:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2775: 	return -1;
                   2776:     }
1.1112    www      2777:     return $answer;
1.263     www      2778: }
                   2779: 
1.1111    www      2780: #
                   2781: # Return special version number of resource if set by override, empty otherwise
                   2782: #
                   2783: sub usedversion {
                   2784:     my $fname=shift;
                   2785:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2786:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2787:     if ($urlversion) { return $urlversion; }
                   2788:     return '';
                   2789: }
                   2790: 
1.1       albertel 2791: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2792: 
1.1       albertel 2793: sub subscribe {
                   2794:     my $fname=shift;
1.761     raeburn  2795:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2796:     $fname=~s/[\n\r]//g;
1.1       albertel 2797:     my $author=$fname;
                   2798:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2799:     my ($udom,$uname)=split(/\//,$author);
                   2800:     my $home=homeserver($uname,$udom);
1.335     albertel 2801:     if ($home eq 'no_host') {
                   2802:         return 'not_found';
1.1       albertel 2803:     }
                   2804:     my $answer=reply("sub:$fname",$home);
1.64      www      2805:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2806: 	$answer.=' by '.$home;
                   2807:     }
1.1       albertel 2808:     return $answer;
                   2809: }
                   2810:     
1.8       www      2811: # -------------------------------------------------------------- Replicate file
                   2812: 
                   2813: sub repcopy {
                   2814:     my $filename=shift;
1.23      www      2815:     $filename=~s/\/+/\//g;
1.1142    raeburn  2816:     my $londocroot = $perlvar{'lonDocRoot'};
                   2817:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2818:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2819:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2820: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2821: 	return &repcopy_userfile($filename);
                   2822:     }
1.532     albertel 2823:     $filename=~s/[\n\r]//g;
1.8       www      2824:     my $transname="$filename.in.transfer";
1.828     www      2825: # FIXME: this should flock
1.607     raeburn  2826:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2827:     my $remoteurl=subscribe($filename);
1.64      www      2828:     if ($remoteurl =~ /^con_lost by/) {
                   2829: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2830:            return 'unavailable';
1.8       www      2831:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2832: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2833: 	   return 'not_found';
1.64      www      2834:     } elsif ($remoteurl =~ /^rejected by/) {
                   2835: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2836:            return 'forbidden';
1.20      www      2837:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2838:            return 'ok';
1.8       www      2839:     } else {
1.290     www      2840:         my $author=$filename;
                   2841:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2842:         my ($udom,$uname)=split(/\//,$author);
                   2843:         my $home=homeserver($uname,$udom);
                   2844:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2845:            my @parts=split(/\//,$filename);
                   2846:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2847:            if ($path ne "$londocroot/res") {
1.8       www      2848:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2849: 	       return 'bad_request';
1.8       www      2850:            }
                   2851:            my $count;
                   2852:            for ($count=5;$count<$#parts;$count++) {
                   2853:                $path.="/$parts[$count]";
                   2854:                if ((-e $path)!=1) {
                   2855: 		   mkdir($path,0777);
                   2856:                }
                   2857:            }
                   2858:            my $ua=new LWP::UserAgent;
                   2859:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2860:            my $response=$ua->request($request,$transname);
                   2861:            if ($response->is_error()) {
                   2862: 	       unlink($transname);
                   2863:                my $message=$response->status_line;
1.672     albertel 2864:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2865:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2866:                return 'unavailable';
1.8       www      2867:            } else {
1.16      www      2868: 	       if ($remoteurl!~/\.meta$/) {
                   2869:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2870:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2871:                   if ($mresponse->is_error()) {
                   2872: 		      unlink($filename.'.meta');
                   2873:                       &logthis(
1.672     albertel 2874:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2875:                   }
                   2876: 	       }
1.8       www      2877:                rename($transname,$filename);
1.607     raeburn  2878:                return 'ok';
1.8       www      2879:            }
1.290     www      2880:        }
1.8       www      2881:     }
1.330     www      2882: }
                   2883: 
                   2884: # ------------------------------------------------ Get server side include body
                   2885: sub ssi_body {
1.381     albertel 2886:     my ($filelink,%form)=@_;
1.606     matthew  2887:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2888:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2889:     }
1.953     www      2890:     my $output='';
                   2891:     my $response;
1.980     raeburn  2892:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2893:        ($output,$response)=&externalssi($filelink);
1.953     www      2894:     } else {
1.1004    droeschl 2895:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2896:        $filelink .= 'inhibitmenu=yes';
1.953     www      2897:        ($output,$response)=&ssi($filelink,%form);
                   2898:     }
1.778     albertel 2899:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2900:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2901:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2902:     if (wantarray) {
                   2903:         return ($output, $response);
                   2904:     } else {
                   2905:         return $output;
                   2906:     }
1.8       www      2907: }
                   2908: 
1.15      www      2909: # --------------------------------------------------------- Server Side Include
                   2910: 
1.782     albertel 2911: sub absolute_url {
                   2912:     my ($host_name) = @_;
                   2913:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2914:     if ($host_name eq '') {
                   2915: 	$host_name = $ENV{'SERVER_NAME'};
                   2916:     }
                   2917:     return $protocol.$host_name;
                   2918: }
                   2919: 
1.942     foxr     2920: #
                   2921: #   Server side include.
                   2922: # Parameters:
                   2923: #  fn     Possibly encrypted resource name/id.
                   2924: #  form   Hash that describes how the rendering should be done
                   2925: #         and other things.
1.944     foxr     2926: # Returns:
1.950     raeburn  2927: #   Scalar context: The content of the response.
                   2928: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2929: #     
1.15      www      2930: sub ssi {
                   2931: 
1.944     foxr     2932:     my ($fn,%form)=@_;
1.15      www      2933:     my $ua=new LWP::UserAgent;
1.23      www      2934:     my $request;
1.711     albertel 2935: 
                   2936:     $form{'no_update_last_known'}=1;
1.895     albertel 2937:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2938:     if (%form) {
1.782     albertel 2939:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 2940:       $request->content(join('&',map { 
                   2941:             my $name = escape($_);
                   2942:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   2943:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   2944:             : &escape($form{$_}) );    
                   2945:         } keys(%form)));
1.23      www      2946:     } else {
1.782     albertel 2947:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2948:     }
                   2949: 
1.15      www      2950:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2951:     my $response= $ua->request($request);
1.1182    foxr     2952:     my $content = $response->content;
                   2953: 
                   2954: 
1.944     foxr     2955:     if (wantarray) {
1.1173    foxr     2956: 	return ($content, $response);
1.944     foxr     2957:     } else {
1.1173    foxr     2958: 	return $content;
1.942     foxr     2959:     }
1.324     www      2960: }
                   2961: 
                   2962: sub externalssi {
                   2963:     my ($url)=@_;
                   2964:     my $ua=new LWP::UserAgent;
                   2965:     my $request=new HTTP::Request('GET',$url);
                   2966:     my $response=$ua->request($request);
1.954     raeburn  2967:     if (wantarray) {
                   2968:         return ($response->content, $response);
                   2969:     } else {
                   2970:         return $response->content;
                   2971:     }
1.15      www      2972: }
1.254     www      2973: 
1.492     albertel 2974: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2975: 
                   2976: sub allowuploaded {
                   2977:     my ($srcurl,$url)=@_;
                   2978:     $url=&clutter(&declutter($url));
                   2979:     my $dir=$url;
                   2980:     $dir=~s/\/[^\/]+$//;
                   2981:     my %httpref=();
                   2982:     my $httpurl=&hreflocation('',$url);
                   2983:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2984:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2985: }
1.477     raeburn  2986: 
1.1193    raeburn  2987: #
                   2988: # Determine if the current user should be able to edit a particular resource,
                   2989: # when viewing in course context.
                   2990: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2991: #     Functions.
                   2992: # (b) When displaying folder contents in course editor, used to determine if
                   2993: #     "Edit" link will be displayed alongside resource.
                   2994: #
1.1196    raeburn  2995: #  input: six args -- filename (decluttered), course number, course domain,
                   2996: #                   url, symb (if registered) and group (if this is a group
                   2997: #                   item -- e.g., bulletin board, group page etc.).
                   2998: #  output: array of five scalars -- 
1.1193    raeburn  2999: #          $cfile -- url for file editing if editable on current server
                   3000: #          $home -- homeserver of resource (i.e., for author if published,
                   3001: #                                           or course if uploaded.).
                   3002: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3003: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3004: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3005: #
                   3006: 
                   3007: sub can_edit_resource {
1.1194    raeburn  3008:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3009:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3010: #
                   3011: # For aboutme pages user can only edit his/her own.
                   3012: #
1.1199    raeburn  3013:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3014:         my ($sdom,$sname) = ($1,$2);
                   3015:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3016:             $home = $env{'user.home'};
                   3017:             $cfile = $resurl;
                   3018:             if ($env{'form.forceedit'}) {
                   3019:                 $forceview = 1;
                   3020:             } else {
                   3021:                 $forceedit = 1;
                   3022:             }
                   3023:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3024:         } else {
                   3025:             return;
                   3026:         }
                   3027:     }
                   3028: 
                   3029:     if ($env{'request.course.id'}) {
                   3030:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3031:         if ($group ne '') {
                   3032: # if this is a group homepage or group bulletin board, check group privs
                   3033:             my $allowed = 0;
1.1197    raeburn  3034:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3035:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3036:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3037:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3038:                     $allowed = 1;
                   3039:                 }
1.1197    raeburn  3040:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3041:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3042:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3043:                     $allowed = 1;
                   3044:                 }
                   3045:             }
                   3046:             if ($allowed) {
                   3047:                 $home=&homeserver($cnum,$cdom);
                   3048:                 if ($env{'form.forceedit'}) {
                   3049:                     $forceview = 1;
                   3050:                 } else {
                   3051:                     $forceedit = 1;
                   3052:                 }
                   3053:                 $cfile = $resurl;
                   3054:             } else {
                   3055:                 return;
                   3056:             }
                   3057:         } else {
1.1208    raeburn  3058:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3059:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3060:                     return;
                   3061:                 }
                   3062:             } elsif (!$crsedit) {
1.1194    raeburn  3063: #
                   3064: # No edit allowed where CC has switched to student role.
                   3065: #
                   3066:                 return;
                   3067:             }
                   3068:         }
                   3069:     }
                   3070: 
1.1193    raeburn  3071:     if ($file ne '') {
                   3072:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3073:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3074:                 $uploaded = 1;
                   3075:                 $incourse = 1;
1.1193    raeburn  3076:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3077:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3078:                     if ($env{'form.forceedit'}) {
                   3079:                         $forceview = 1;
                   3080:                     } else {
                   3081:                         $forceedit = 1;
                   3082:                     }
1.1194    raeburn  3083:                 }
                   3084:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3085:                 $incourse = 1;
                   3086:                 if ($env{'form.forceedit'}) {
                   3087:                     $forceview = 1;
                   3088:                 } else {
                   3089:                     $forceedit = 1;
                   3090:                 }
                   3091:                 $cfile = $resurl;
                   3092:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3093:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3094:                     $incourse = 1;
                   3095:                     if ($env{'form.forceedit'}) {
                   3096:                         $forceview = 1;
                   3097:                     } else {
                   3098:                         $forceedit = 1;
                   3099:                     }
                   3100:                     $cfile = $resurl;
1.1199    raeburn  3101:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3102:                     $incourse = 1;
                   3103:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3104:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3105:                     $incourse = 1;
1.1199    raeburn  3106:                     if ($env{'form.forceedit'}) {
                   3107:                         $forceview = 1;
                   3108:                     } else {
                   3109:                         $forceedit = 1;
                   3110:                     }
                   3111:                     $cfile = $resurl;
1.1298    raeburn  3112:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3113:                     $incourse = 1;
                   3114:                     if ($env{'form.forceedit'}) {
                   3115:                         $forceview = 1;
                   3116:                     } else {
                   3117:                         $forceedit = 1;
                   3118:                     }
                   3119:                     $cfile = $resurl;
1.1208    raeburn  3120:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3121:                     $incourse = 1;
                   3122:                     if ($env{'form.forceedit'}) {
                   3123:                         $forceview = 1;
                   3124:                     } else {
                   3125:                         $forceedit = 1;
                   3126:                     }
                   3127:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3128:                 }
                   3129:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3130:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3131:                 if (&is_on_map($template)) { 
                   3132:                     $incourse = 1;
                   3133:                     $forceview = 1;
                   3134:                     $cfile = $template;
1.1193    raeburn  3135:                 }
1.1199    raeburn  3136:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3137:                     $incourse = 1;
                   3138:                     if ($env{'form.forceedit'}) {
                   3139:                         $forceview = 1;
                   3140:                     } else {
                   3141:                         $forceedit = 1;
                   3142:                     }
                   3143:                     $cfile = $resurl;
1.1298    raeburn  3144:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3145:                 $incourse = 1;
                   3146:                 if ($env{'form.forceedit'}) {
                   3147:                     $forceview = 1;
                   3148:                 } else {
                   3149:                     $forceedit = 1;
                   3150:                 }
                   3151:                 $cfile = $resurl;
1.1199    raeburn  3152:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3153:                 $incourse = 1;
                   3154:                 $forceview = 1;
                   3155:                 if ($symb) {
                   3156:                     my ($map,$id,$res)=&decode_symb($symb);
                   3157:                     $env{'request.symb'} = $symb;
                   3158:                     $cfile = &clutter($res);
                   3159:                 } else {
                   3160:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3161:                     my $escfile = &unescape($cfile);
                   3162:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3163:                         $cfile = '/adm/wrapper'.$escfile;
                   3164:                     } else {
                   3165:                         $escfile =~ s{^http://}{};
                   3166:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3167:                     }
1.1199    raeburn  3168:                 }
1.1234    raeburn  3169:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3170:                 if ($env{'form.forceedit'}) {
                   3171:                     $forceview = 1;
                   3172:                 } else {
                   3173:                     $forceedit = 1;
                   3174:                 }
                   3175:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3176:             }
                   3177:         }
1.1194    raeburn  3178:         if ($uploaded || $incourse) {
                   3179:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3180:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3181:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3182:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3183:             # Check that the user has permission to edit this resource
                   3184:             my $setpriv = 1;
                   3185:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3186:             if (defined($cfudom)) {
                   3187:                 $home=&homeserver($cfuname,$cfudom);
                   3188:                 $cfile=$file;
                   3189:             }
                   3190:         }
1.1194    raeburn  3191:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3192:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3193:             my @ids=&current_machine_ids();
                   3194:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3195:                 $switchserver=1;
                   3196:             }
                   3197:         }
                   3198:     }
1.1194    raeburn  3199:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3200: }
                   3201: 
                   3202: sub is_course_upload {
                   3203:     my ($file,$cnum,$cdom) = @_;
                   3204:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3205:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3206:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3207:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3208:         return 1;
                   3209:     }
                   3210:     return;
                   3211: }
                   3212: 
1.1194    raeburn  3213: sub in_course {
1.1195    raeburn  3214:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3215:     if ($hideprivileged) {
                   3216:         my $skipuser;
1.1219    raeburn  3217:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3218:         my @possdoms = ($cdom);  
                   3219:         if ($coursehash{'checkforpriv'}) { 
                   3220:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3221:         }
                   3222:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3223:             $skipuser = 1;
                   3224:             if ($coursehash{'nothideprivileged'}) {
                   3225:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3226:                     my $user;
                   3227:                     if ($item =~ /:/) {
                   3228:                         $user = $item;
                   3229:                     } else {
                   3230:                         $user = join(':',split(/[\@]/,$item));
                   3231:                     }
                   3232:                     if ($user eq $uname.':'.$udom) {
                   3233:                         undef($skipuser);
                   3234:                         last;
                   3235:                     }
                   3236:                 }
                   3237:             }
                   3238:             if ($skipuser) {
                   3239:                 return 0;
                   3240:             }
                   3241:         }
                   3242:     }
1.1194    raeburn  3243:     $type ||= 'any';
                   3244:     if (!defined($cdom) || !defined($cnum)) {
                   3245:         my $cid  = $env{'request.course.id'};
                   3246:         $cdom = $env{'course.'.$cid.'.domain'};
                   3247:         $cnum = $env{'course.'.$cid.'.num'};
                   3248:     }
                   3249:     my $typesref;
1.1195    raeburn  3250:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3251:         $typesref = ['active','previous','future'];
                   3252:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3253:         $typesref = [$type];
                   3254:     }
                   3255:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3256:                               $typesref,undef,[$cdom]);
                   3257:     my ($tmp) = keys(%roles);
                   3258:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3259:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3260:     if (@course_roles > 0) {
                   3261:         return 1;
                   3262:     }
                   3263:     return 0;
                   3264: }
                   3265: 
1.478     albertel 3266: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3267: # input: action, courseID, current domain, intended
1.637     raeburn  3268: #        path to file, source of file, instruction to parse file for objects,
                   3269: #        ref to hash for embedded objects,
                   3270: #        ref to hash for codebase of java objects.
1.1095    raeburn  3271: #        reference to scalar to accommodate mime type determined
                   3272: #          from File::MMagic if $parser = parse.
1.637     raeburn  3273: #
1.485     raeburn  3274: # output: url to file (if action was uploaddoc), 
                   3275: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3276: #
1.478     albertel 3277: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3278: # course.
1.477     raeburn  3279: #
1.478     albertel 3280: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3281: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3282: #          course's home server.
1.477     raeburn  3283: #
1.478     albertel 3284: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3285: #          be copied from $source (current location) to 
                   3286: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3287: #         and will then be copied to
                   3288: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3289: #         course's home server.
1.485     raeburn  3290: #
1.481     raeburn  3291: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3292: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3293: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3294: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3295: #         in course's home server.
1.637     raeburn  3296: #
1.477     raeburn  3297: 
                   3298: sub process_coursefile {
1.1095    raeburn  3299:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3300:         $mimetype)=@_;
1.477     raeburn  3301:     my $fetchresult;
1.638     albertel 3302:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3303:     if ($action eq 'propagate') {
1.638     albertel 3304:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3305: 			     $home);
1.481     raeburn  3306:     } else {
1.477     raeburn  3307:         my $fpath = '';
                   3308:         my $fname = $file;
1.478     albertel 3309:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3310:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3311:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3312:         if ($action eq 'copy') {
                   3313:             if ($source eq '') {
                   3314:                 $fetchresult = 'no source file';
                   3315:                 return $fetchresult;
                   3316:             } else {
                   3317:                 my $destination = $filepath.'/'.$fname;
                   3318:                 rename($source,$destination);
                   3319:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3320:                                  $home);
1.481     raeburn  3321:             }
                   3322:         } elsif ($action eq 'uploaddoc') {
                   3323:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3324:             print $fh $env{'form.'.$source};
1.481     raeburn  3325:             close($fh);
1.637     raeburn  3326:             if ($parser eq 'parse') {
1.1024    raeburn  3327:                 my $mm = new File::MMagic;
1.1095    raeburn  3328:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3329:                 if ($type eq 'text/html') {
1.1024    raeburn  3330:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3331:                     unless ($parse_result eq 'ok') {
                   3332:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3333:                     }
1.637     raeburn  3334:                 }
1.1095    raeburn  3335:                 if (ref($mimetype)) {
                   3336:                     $$mimetype = $type;
                   3337:                 } 
1.637     raeburn  3338:             }
1.477     raeburn  3339:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3340:                                  $home);
1.481     raeburn  3341:             if ($fetchresult eq 'ok') {
                   3342:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3343:             } else {
                   3344:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3345:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3346:                 return '/adm/notfound.html';
                   3347:             }
1.477     raeburn  3348:         }
                   3349:     }
1.485     raeburn  3350:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3351:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3352:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3353:     }
                   3354:     return $fetchresult;
                   3355: }
                   3356: 
1.637     raeburn  3357: sub build_filepath {
                   3358:     my ($fpath) = @_;
                   3359:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3360:     unless ($fpath eq '') {
                   3361:         my @parts=split('/',$fpath);
                   3362:         foreach my $part (@parts) {
                   3363:             $filepath.= '/'.$part;
                   3364:             if ((-e $filepath)!=1) {
                   3365:                 mkdir($filepath,0777);
                   3366:             }
                   3367:         }
                   3368:     }
                   3369:     return $filepath;
                   3370: }
                   3371: 
                   3372: sub store_edited_file {
1.638     albertel 3373:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3374:     my $file = $primary_url;
                   3375:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3376:     my $fpath = '';
                   3377:     my $fname = $file;
                   3378:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3379:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3380:     my $filepath = &build_filepath($fpath);
                   3381:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3382:     print $fh $content;
                   3383:     close($fh);
1.638     albertel 3384:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3385:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3386: 			  $home);
1.637     raeburn  3387:     if ($$fetchresult eq 'ok') {
                   3388:         return '/uploaded/'.$fpath.'/'.$fname;
                   3389:     } else {
1.638     albertel 3390:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3391: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3392:         return '/adm/notfound.html';
                   3393:     }
                   3394: }
                   3395: 
1.531     albertel 3396: sub clean_filename {
1.831     albertel 3397:     my ($fname,$args)=@_;
1.315     www      3398: # Replace Windows backslashes by forward slashes
1.257     www      3399:     $fname=~s/\\/\//g;
1.831     albertel 3400:     if (!$args->{'keep_path'}) {
                   3401:         # Get rid of everything but the actual filename
                   3402: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3403:     }
1.315     www      3404: # Replace spaces by underscores
                   3405:     $fname=~s/\s+/\_/g;
                   3406: # Replace all other weird characters by nothing
1.831     albertel 3407:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3408: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3409: # numbers
                   3410:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3411:     return $fname;
                   3412: }
1.1051    raeburn  3413: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3414: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3415: # image with the same aspect ratio as the original, but with dimensions which do 
                   3416: # not exceed $resizewidth and $resizeheight.
                   3417:  
1.984     neumanie 3418: sub resizeImage {
1.1051    raeburn  3419:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3420:     my $ima = Image::Magick->new;
                   3421:     my $resized;
                   3422:     if (-e $img_path) {
                   3423:         $ima->Read($img_path);
                   3424:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3425:             my $width = $ima->Get('width');
                   3426:             my $height = $ima->Get('height');
                   3427:             if ($width > $resizewidth) {
                   3428: 	        my $factor = $width/$resizewidth;
                   3429:                 my $newheight = $height/$factor;
                   3430:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3431:                 $resized = 1;
                   3432:             }
                   3433:         }
                   3434:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3435:             my $width = $ima->Get('width');
                   3436:             my $height = $ima->Get('height');
                   3437:             if ($height > $resizeheight) {
                   3438:                 my $factor = $height/$resizeheight;
                   3439:                 my $newwidth = $width/$factor;
                   3440:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3441:                 $resized = 1;
                   3442:             }
                   3443:         }
                   3444:         if ($resized) {
                   3445:             $ima->Write($img_path);
                   3446:         }
                   3447:     }
                   3448:     return;
1.977     amueller 3449: }
                   3450: 
1.608     albertel 3451: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3452: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3453: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3454: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3455: #                                    canceloverwrite, or ''. 
                   3456: #                   if 'coursedoc': upload to the current course
                   3457: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3458: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3459: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3460: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3461: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3462: #        $allfiles - reference to hash for embedded objects
                   3463: #        $codebase - reference to hash for codebase of java objects
                   3464: #        $desuname - username for permanent storage of uploaded file
                   3465: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3466: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3467: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3468: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3469: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3470: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3471: #                    from File::MMagic.
1.858     raeburn  3472: # 
1.686     albertel 3473: # output: url of file in userspace, or error: <message> 
                   3474: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3475: 
1.531     albertel 3476: sub userfileupload {
1.1090    raeburn  3477:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3478:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3479:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3480:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3481:     $fname=&clean_filename($fname);
1.1090    raeburn  3482:     # See if there is anything left
1.257     www      3483:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3484:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3485:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3486:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3487:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3488:         my $now = time;
1.1090    raeburn  3489:         my $filepath;
1.1095    raeburn  3490:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3491:              $filepath = 'tmp/helprequests/'.$now;
                   3492:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3493:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3494:                          '_'.$env{'user.domain'}.'/pending';
                   3495:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3496:             my ($docuname,$docudom);
                   3497:             if ($destudom) {
                   3498:                 $docudom = $destudom;
                   3499:             } else {
                   3500:                 $docudom = $env{'user.domain'};
                   3501:             }
                   3502:             if ($destuname) {
                   3503:                 $docuname = $destuname;
                   3504:             } else {
                   3505:                 $docuname = $env{'user.name'};
                   3506:             }
                   3507:             if (exists($env{'form.group'})) {
                   3508:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3509:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3510:             }
                   3511:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3512:             if ($context eq 'canceloverwrite') {
                   3513:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3514:                 if (-e  $tempfile) {
                   3515:                     my @info = stat($tempfile);
                   3516:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3517:                         unlink($tempfile);
                   3518:                     }
                   3519:                 }
                   3520:                 return;
1.523     raeburn  3521:             }
                   3522:         }
1.1090    raeburn  3523:         # Create the directory if not present
1.741     raeburn  3524:         my @parts=split(/\//,$filepath);
                   3525:         my $fullpath = $perlvar{'lonDaemons'};
                   3526:         for (my $i=0;$i<@parts;$i++) {
                   3527:             $fullpath .= '/'.$parts[$i];
                   3528:             if ((-e $fullpath)!=1) {
                   3529:                 mkdir($fullpath,0777);
                   3530:             }
                   3531:         }
                   3532:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3533:         print $fh $env{'form.'.$formname};
                   3534:         close($fh);
1.1090    raeburn  3535:         if ($context eq 'existingfile') {
                   3536:             my @info = stat($fullpath.'/'.$fname);
                   3537:             return ($fullpath.'/'.$fname,$info[9]);
                   3538:         } else {
                   3539:             return $fullpath.'/'.$fname;
                   3540:         }
1.523     raeburn  3541:     }
1.995     raeburn  3542:     if ($subdir eq 'scantron') {
                   3543:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3544:     } else {
1.995     raeburn  3545:         $fname="$subdir/$fname";
                   3546:     }
1.1090    raeburn  3547:     if ($context eq 'coursedoc') {
1.638     albertel 3548: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3549: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3550:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3551:             return &finishuserfileupload($docuname,$docudom,
                   3552: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3553: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3554:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3555:         } else {
1.1218    raeburn  3556:             if ($env{'form.folder'}) {
                   3557:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3558:             }
1.638     albertel 3559:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3560: 				       $fname,$formname,$parser,
1.1095    raeburn  3561: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3562:         }
1.719     banghart 3563:     } elsif (defined($destuname)) {
                   3564:         my $docuname=$destuname;
                   3565:         my $docudom=$destudom;
1.860     raeburn  3566: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3567: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3568:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3569:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3570:     } else {
1.638     albertel 3571:         my $docuname=$env{'user.name'};
                   3572:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3573:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3574:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3575:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3576:         }
1.860     raeburn  3577: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3578: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3579:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3580:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3581:     }
1.271     www      3582: }
                   3583: 
                   3584: sub finishuserfileupload {
1.860     raeburn  3585:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3586:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3587:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3588:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3589:   
1.860     raeburn  3590:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3591:     $file=$fname;
                   3592:     if ($fname=~m|/|) {
                   3593:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3594: 	$path.=$fnamepath.'/';
                   3595:     }
1.259     www      3596:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3597:     my $count;
                   3598:     for ($count=4;$count<=$#parts;$count++) {
                   3599:         $filepath.="/$parts[$count]";
                   3600:         if ((-e $filepath)!=1) {
                   3601: 	    mkdir($filepath,0777);
                   3602:         }
                   3603:     }
1.984     neumanie 3604: 
1.258     www      3605: # Save the file
                   3606:     {
1.701     albertel 3607: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3608: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3609: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3610: 	    return '/adm/notfound.html';
                   3611: 	}
1.1090    raeburn  3612:         if ($context eq 'overwrite') {
1.1117    foxr     3613:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3614:             my $target = $filepath.'/'.$file;
                   3615:             if (-e $source) {
                   3616:                 my @info = stat($source);
                   3617:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3618:                     unless (&File::Copy::move($source,$target)) {
                   3619:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3620:                         return "Moving from $source failed";
                   3621:                     }
                   3622:                 } else {
                   3623:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3624:                 }
                   3625:             } else {
                   3626:                 return "Temporary file: $source missing";
                   3627:             }
                   3628:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3629: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3630: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3631: 	    return '/adm/notfound.html';
                   3632: 	}
1.570     albertel 3633: 	close(FH);
1.1051    raeburn  3634:         if ($resizewidth && $resizeheight) {
                   3635:             my $mm = new File::MMagic;
                   3636:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3637:             if ($mime_type =~ m{^image/}) {
                   3638: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3639:             }  
1.977     amueller 3640: 	}
1.258     www      3641:     }
1.1152    raeburn  3642:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3643:         if (ref($mimetype)) {
                   3644:             if ($$mimetype eq '') {
                   3645:                 my $mm = new File::MMagic;
                   3646:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3647:                 $$mimetype = $type;
                   3648:             }
                   3649:         }
                   3650:     }
1.637     raeburn  3651:     if ($parser eq 'parse') {
1.1152    raeburn  3652:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3653:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3654:                                                        $allfiles,$codebase);
                   3655:             unless ($parse_result eq 'ok') {
                   3656:                 &logthis('Failed to parse '.$filepath.$file.
                   3657: 	   	         ' for embedded media: '.$parse_result); 
                   3658:             }
1.637     raeburn  3659:         }
                   3660:     }
1.860     raeburn  3661:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3662:         my $input = $filepath.'/'.$file;
                   3663:         my $output = $filepath.'/'.'tn-'.$file;
                   3664:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3665:         system("convert -sample $thumbsize $input $output");
                   3666:         if (-e $filepath.'/'.'tn-'.$file) {
                   3667:             $fetchthumb  = 1; 
                   3668:         }
                   3669:     }
1.858     raeburn  3670:  
1.259     www      3671: # Notify homeserver to grep it
                   3672: #
1.984     neumanie 3673:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3674:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3675:     if ($fetchresult eq 'ok') {
1.860     raeburn  3676:         if ($fetchthumb) {
                   3677:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3678:             if ($thumbresult ne 'ok') {
                   3679:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3680:                          $docuhome.': '.$thumbresult);
                   3681:             }
                   3682:         }
1.259     www      3683: #
1.258     www      3684: # Return the URL to it
1.494     albertel 3685:         return '/uploaded/'.$path.$file;
1.263     www      3686:     } else {
1.494     albertel 3687:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3688: 		 ': '.$fetchresult);
1.263     www      3689:         return '/adm/notfound.html';
1.858     raeburn  3690:     }
1.493     albertel 3691: }
                   3692: 
1.637     raeburn  3693: sub extract_embedded_items {
1.961     raeburn  3694:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3695:     my @state = ();
1.1164    raeburn  3696:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3697:     my %javafiles = (
                   3698:                       codebase => '',
                   3699:                       code => '',
                   3700:                       archive => ''
                   3701:                     );
                   3702:     my %mediafiles = (
                   3703:                       src => '',
                   3704:                       movie => '',
                   3705:                      );
1.648     raeburn  3706:     my $p;
                   3707:     if ($content) {
                   3708:         $p = HTML::LCParser->new($content);
                   3709:     } else {
1.961     raeburn  3710:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3711:     }
1.641     albertel 3712:     while (my $t=$p->get_token()) {
1.640     albertel 3713: 	if ($t->[0] eq 'S') {
                   3714: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3715: 	    push(@state, $tagname);
1.648     raeburn  3716:             if (lc($tagname) eq 'allow') {
                   3717:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3718:             }
1.640     albertel 3719: 	    if (lc($tagname) eq 'img') {
                   3720: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3721: 	    }
1.886     albertel 3722: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3723:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3724:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3725:                 }
1.886     albertel 3726: 	    }
1.645     raeburn  3727:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3728:                 my $src;
1.645     raeburn  3729:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3730:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3731:                 } else {
1.1164    raeburn  3732:                     if ($attr->{'src'} ne '') {
                   3733:                         $src = $attr->{'src'};
                   3734:                         &add_filetype($allfiles,$src,'src');
                   3735:                     }
                   3736:                 }
                   3737:                 my $text = $p->get_trimmed_text();
                   3738:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3739:                     my @swfargs = split(/,/,$1);
                   3740:                     foreach my $item (@swfargs) {
                   3741:                         $item =~ s/["']//g;
                   3742:                         $item =~ s/^\s+//;
                   3743:                         $item =~ s/\s+$//;
                   3744:                     }
                   3745:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3746:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3747:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3748:                         } else {
                   3749:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3750:                         }
                   3751:                     }
1.645     raeburn  3752:                 }
                   3753:             }
                   3754:             if (lc($tagname) eq 'link') {
                   3755:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3756:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3757:                 }
                   3758:             }
1.640     albertel 3759: 	    if (lc($tagname) eq 'object' ||
                   3760: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3761: 		foreach my $item (keys(%javafiles)) {
                   3762: 		    $javafiles{$item} = '';
                   3763: 		}
1.1164    raeburn  3764:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3765:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3766:                 }
1.640     albertel 3767: 	    }
                   3768: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3769: 		my $name = lc($attr->{'name'});
                   3770: 		foreach my $item (keys(%javafiles)) {
                   3771: 		    if ($name eq $item) {
                   3772: 			$javafiles{$item} = $attr->{'value'};
                   3773: 			last;
                   3774: 		    }
                   3775: 		}
1.1164    raeburn  3776:                 my $pathfrom;
1.640     albertel 3777: 		foreach my $item (keys(%mediafiles)) {
                   3778: 		    if ($name eq $item) {
1.1164    raeburn  3779:                         $pathfrom = $attr->{'value'};
                   3780:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3781: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3782: 			last;
                   3783: 		    }
                   3784: 		}
1.1164    raeburn  3785:                 if ($name eq 'flashvars') {
                   3786:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3787:                 }
                   3788:                 if ($pathfrom ne '') {
                   3789:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3790:                                          $pathfrom);
                   3791:                 }
1.640     albertel 3792: 	    }
                   3793: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3794: 		foreach my $item (keys(%javafiles)) {
                   3795: 		    if ($attr->{$item}) {
                   3796: 			$javafiles{$item} = $attr->{$item};
                   3797: 			last;
                   3798: 		    }
                   3799: 		}
                   3800: 		foreach my $item (keys(%mediafiles)) {
                   3801: 		    if ($attr->{$item}) {
                   3802: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3803: 			last;
                   3804: 		    }
                   3805: 		}
1.1164    raeburn  3806:                 if (lc($tagname) eq 'embed') {
                   3807:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3808:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3809:                                              $attr->{'src'});
                   3810:                     }
                   3811:                 }
1.640     albertel 3812: 	    }
1.1243    raeburn  3813:             if (lc($tagname) eq 'iframe') {
                   3814:                 my $src = $attr->{'src'} ;
                   3815:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3816:                     &add_filetype($allfiles,$src,'src');
                   3817:                 } elsif ($src =~ m{^/}) {
                   3818:                     if ($env{'request.course.id'}) {
                   3819:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3820:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3821:                         my $url = &hreflocation('',$fullpath);
                   3822:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3823:                             my $relpath = $1;
                   3824:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3825:                                 &add_filetype($allfiles,$1,'src');
                   3826:                             }
                   3827:                         }
                   3828:                     }
                   3829:                 }
                   3830:             }
1.1164    raeburn  3831:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3832:                 pop(@state);
1.1164    raeburn  3833:             }
1.640     albertel 3834: 	} elsif ($t->[0] eq 'E') {
                   3835: 	    my ($tagname) = ($t->[1]);
                   3836: 	    if ($javafiles{'codebase'} ne '') {
                   3837: 		$javafiles{'codebase'} .= '/';
                   3838: 	    }  
                   3839: 	    if (lc($tagname) eq 'applet' ||
                   3840: 		lc($tagname) eq 'object' ||
                   3841: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3842: 		) {
                   3843: 		foreach my $item (keys(%javafiles)) {
                   3844: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3845: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3846: 			&add_filetype($allfiles,$file,$item);
                   3847: 		    }
                   3848: 		}
                   3849: 	    } 
                   3850: 	    pop @state;
                   3851: 	}
                   3852:     }
1.1164    raeburn  3853:     foreach my $id (sort(keys(%flashvars))) {
                   3854:         if ($shockwave{$id} ne '') {
                   3855:             my @pairs = split(/\&/,$flashvars{$id});
                   3856:             foreach my $pair (@pairs) {
                   3857:                 my ($key,$value) = split(/\=/,$pair);
                   3858:                 if ($key eq 'thumb') {
                   3859:                     &add_filetype($allfiles,$value,$key);
                   3860:                 } elsif ($key eq 'content') {
                   3861:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3862:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3863:                     if ($ext ne '') {
                   3864:                         &add_filetype($allfiles,$path.$value,$ext);
                   3865:                     }
                   3866:                 }
                   3867:             }
                   3868:         }
                   3869:     }
1.637     raeburn  3870:     return 'ok';
                   3871: }
                   3872: 
1.639     albertel 3873: sub add_filetype {
                   3874:     my ($allfiles,$file,$type)=@_;
                   3875:     if (exists($allfiles->{$file})) {
                   3876: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3877: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3878: 	}
                   3879:     } else {
                   3880: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3881:     }
                   3882: }
                   3883: 
1.1164    raeburn  3884: sub embedded_dependency {
                   3885:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3886:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3887:         if (($identifier ne '') &&
                   3888:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3889:             ($pathfrom ne '')) {
                   3890:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3891:             foreach my $dep (@{$related->{$identifier}}) {
                   3892:                 &add_filetype($allfiles,$path.$dep,'object');
                   3893:             }
                   3894:         }
                   3895:     }
                   3896:     return;
                   3897: }
                   3898: 
1.493     albertel 3899: sub removeuploadedurl {
1.984     neumanie 3900:     my ($url)=@_;	
                   3901:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3902:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3903: }
                   3904: 
                   3905: sub removeuserfile {
                   3906:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3907:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3908:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3909:     if ($result eq 'ok') {	
1.798     raeburn  3910:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3911:             my $metafile = $fname.'.meta';
                   3912:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3913: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3914:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3915:             my $sqlresult = 
1.823     albertel 3916:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3917:                                         'portfolio_metadata',$group,
                   3918:                                         'delete');
1.798     raeburn  3919:         }
                   3920:     }
                   3921:     return $result;
1.257     www      3922: }
1.15      www      3923: 
1.530     albertel 3924: sub mkdiruserfile {
                   3925:     my ($docuname,$docudom,$dir)=@_;
                   3926:     my $home=&homeserver($docuname,$docudom);
                   3927:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3928: }
                   3929: 
1.531     albertel 3930: sub renameuserfile {
                   3931:     my ($docuname,$docudom,$old,$new)=@_;
                   3932:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3933:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3934:                         &escape("$old").':'.&escape("$new"),$home);
                   3935:     if ($result eq 'ok') {
                   3936:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3937:             my $oldmeta = $old.'.meta';
                   3938:             my $newmeta = $new.'.meta';
                   3939:             my $metaresult = 
                   3940:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3941: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3942:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3943:             my $sqlresult = 
1.823     albertel 3944:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3945:                                         'portfolio_metadata',$group,
                   3946:                                         'delete');
1.798     raeburn  3947:         }
                   3948:     }
                   3949:     return $result;
1.531     albertel 3950: }
                   3951: 
1.14      www      3952: # ------------------------------------------------------------------------- Log
                   3953: 
                   3954: sub log {
                   3955:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3956:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3957: }
                   3958: 
                   3959: # ------------------------------------------------------------------ Course Log
1.352     www      3960: #
                   3961: # This routine flushes several buffers of non-mission-critical nature
                   3962: #
1.157     www      3963: 
                   3964: sub flushcourselogs {
1.352     www      3965:     &logthis('Flushing log buffers');
                   3966: #
                   3967: # course logs
                   3968: # This is a log of all transactions in a course, which can be used
                   3969: # for data mining purposes
                   3970: #
                   3971: # It also collects the courseid database, which lists last transaction
                   3972: # times and course titles for all courseids
                   3973: #
                   3974:     my %courseidbuffer=();
1.921     raeburn  3975:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3976:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3977: 		          &escape($courselogs{$crsid}),
                   3978: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3979: 	    delete $courselogs{$crsid};
                   3980:         } else {
                   3981:             &logthis('Failed to flush log buffer for '.$crsid);
                   3982:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3983:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3984:                         " exceeded maximum size, deleting.</font>");
                   3985:                delete $courselogs{$crsid};
                   3986:             }
1.352     www      3987:         }
1.920     raeburn  3988:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3989:             'description' => $coursedescrbuf{$crsid},
                   3990:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3991:             'type'        => $coursetypebuf{$crsid},
                   3992:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3993:         };
1.191     harris41 3994:     }
1.352     www      3995: #
                   3996: # Write course id database (reverse lookup) to homeserver of courses 
                   3997: # Is used in pickcourse
                   3998: #
1.840     albertel 3999:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4000:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4001:                                     $courseidbuffer{$crs_home},
                   4002:                                     $crs_home,'timeonly');
1.352     www      4003:     }
                   4004: #
                   4005: # File accesses
                   4006: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4007: #
1.449     matthew  4008:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4009:         if ($entry =~ /___count$/) {
                   4010:             my ($dom,$name);
1.807     albertel 4011:             ($dom,$name,undef)=
1.811     albertel 4012: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4013:             if (! defined($dom) || $dom eq '' || 
                   4014:                 ! defined($name) || $name eq '') {
1.620     albertel 4015:                 my $cid = $env{'request.course.id'};
                   4016:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4017:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4018:             }
1.450     matthew  4019:             my $value = $accesshash{$entry};
                   4020:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4021:             my %temphash=($url => $value);
1.449     matthew  4022:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4023:             if ($result eq 'ok') {
                   4024:                 delete $accesshash{$entry};
                   4025:             }
                   4026:         } else {
1.811     albertel 4027:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4028:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4029:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4030:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4031:                 delete $accesshash{$entry};
                   4032:             }
1.185     www      4033:         }
1.191     harris41 4034:     }
1.352     www      4035: #
                   4036: # Roles
                   4037: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4038: #
1.800     albertel 4039:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4040:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4041: 	    split(/\:/,$entry);
                   4042:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4043:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4044:                 $rudom,$runame) eq 'ok') {
                   4045: 	    delete $userrolehash{$entry};
                   4046:         }
                   4047:     }
1.662     raeburn  4048: #
                   4049: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   4050: #
                   4051:     my %domrolebuffer = ();
1.1000    raeburn  4052:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4053:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4054:         if ($domrolebuffer{$rudom}) {
                   4055:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4056:                       '='.&escape($domainrolehash{$entry});
                   4057:         } else {
                   4058:             $domrolebuffer{$rudom}.=&escape($entry).
                   4059:                       '='.&escape($domainrolehash{$entry});
                   4060:         }
                   4061:         delete $domainrolehash{$entry};
                   4062:     }
                   4063:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 4064: 	my %servers = &get_servers($dom,'library');
                   4065: 	foreach my $tryserver (keys(%servers)) {
                   4066: 	    unless (&reply('domroleput:'.$dom.':'.
                   4067: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4068: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4069: 	    }
1.662     raeburn  4070:         }
                   4071:     }
1.186     www      4072:     $dumpcount++;
1.157     www      4073: }
                   4074: 
                   4075: sub courselog {
                   4076:     my $what=shift;
1.158     www      4077:     $what=time.':'.$what;
1.620     albertel 4078:     unless ($env{'request.course.id'}) { return ''; }
                   4079:     $coursedombuf{$env{'request.course.id'}}=
                   4080:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4081:     $coursenumbuf{$env{'request.course.id'}}=
                   4082:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4083:     $coursehombuf{$env{'request.course.id'}}=
                   4084:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4085:     $coursedescrbuf{$env{'request.course.id'}}=
                   4086:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4087:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4088:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4089:     $courseownerbuf{$env{'request.course.id'}}=
                   4090:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4091:     $coursetypebuf{$env{'request.course.id'}}=
                   4092:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4093:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4094: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4095:     } else {
1.620     albertel 4096: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4097:     }
1.620     albertel 4098:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4099: 	&flushcourselogs();
                   4100:     }
1.158     www      4101: }
                   4102: 
                   4103: sub courseacclog {
                   4104:     my $fnsymb=shift;
1.620     albertel 4105:     unless ($env{'request.course.id'}) { return ''; }
                   4106:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4107:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4108:         $what.=':POST';
1.583     matthew  4109:         # FIXME: Probably ought to escape things....
1.800     albertel 4110: 	foreach my $key (keys(%env)) {
                   4111:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4112:                 my $formitem = $1;
                   4113:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4114:                     $what.=':'.$formitem.'='.$env{$key};
                   4115:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4116:                     $what.=':'.$formitem.'='.$env{$key};
                   4117:                 }
1.158     www      4118:             }
1.191     harris41 4119:         }
1.583     matthew  4120:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4121:         # FIXME: We should not be depending on a form parameter that someone
                   4122:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4123:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4124:             $what.= ':POST';
                   4125:             # FIXME: Probably ought to escape things....
                   4126:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4127:                                  'crsdiscuss') {
1.620     albertel 4128:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4129:             }
                   4130:         }
1.158     www      4131:     }
                   4132:     &courselog($what);
1.149     www      4133: }
                   4134: 
1.185     www      4135: sub countacc {
                   4136:     my $url=&declutter(shift);
1.458     matthew  4137:     return if (! defined($url) || $url eq '');
1.620     albertel 4138:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4139: #
                   4140: # Mark that this url was used in this course
                   4141: #
1.620     albertel 4142:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4143: #
                   4144: # Increase the access count for this resource in this child process
                   4145: #
1.281     www      4146:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4147:     $accesshash{$key}++;
1.185     www      4148: }
1.349     www      4149: 
1.361     www      4150: sub linklog {
                   4151:     my ($from,$to)=@_;
                   4152:     $from=&declutter($from);
                   4153:     $to=&declutter($to);
                   4154:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4155:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4156: }
1.1160    www      4157: 
                   4158: sub statslog {
                   4159:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4160:     if ($users<2) { return; }
                   4161:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4162:             'course'       => $env{'request.course.id'},
                   4163:             'sections'     => '"all"',
                   4164:             'num_students' => $users,
                   4165:             'part'         => $part,
                   4166:             'symb'         => $symb,
                   4167:             'mean_tries'   => $av_attempts,
                   4168:             'deg_of_diff'  => $degdiff});
                   4169:     foreach my $key (keys(%dynstore)) {
                   4170:         $accesshash{$key}=$dynstore{$key};
                   4171:     }
                   4172: }
1.361     www      4173:   
1.349     www      4174: sub userrolelog {
                   4175:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4176:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4177:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4178:        $userrolehash
                   4179:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4180:                     =$tend.':'.$tstart;
1.662     raeburn  4181:     }
1.1169    droeschl 4182:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4183:        $userrolehash
                   4184:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4185:                     =$tend.':'.$tstart;
                   4186:     }
1.1169    droeschl 4187:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  4188:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4189:        $domainrolehash
                   4190:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4191:                     = $tend.':'.$tstart;
                   4192:     }
1.351     www      4193: }
                   4194: 
1.957     raeburn  4195: sub courserolelog {
                   4196:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4197:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4198:         my $cdom = $1;
                   4199:         my $cnum = $2;
                   4200:         my $sec = $3;
                   4201:         my $namespace = 'rolelog';
                   4202:         my %storehash = (
                   4203:                            role    => $trole,
                   4204:                            start   => $tstart,
                   4205:                            end     => $tend,
                   4206:                            selfenroll => $selfenroll,
                   4207:                            context    => $context,
                   4208:                         );
                   4209:         if ($trole eq 'gr') {
                   4210:             $namespace = 'groupslog';
                   4211:             $storehash{'group'} = $sec;
                   4212:         } else {
                   4213:             $storehash{'section'} = $sec;
                   4214:         }
1.1188    raeburn  4215:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4216:                    $domain,$cnum,$cdom);
1.1184    raeburn  4217:         if (($trole ne 'st') || ($sec ne '')) {
                   4218:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4219:         }
                   4220:     }
                   4221:     return;
                   4222: }
                   4223: 
1.1184    raeburn  4224: sub domainrolelog {
                   4225:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4226:     if ($area =~ m{^/($match_domain)/$}) {
                   4227:         my $cdom = $1;
                   4228:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   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('domain',$namespace,\%storehash,$delflag,$username,
                   4237:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4238:     }
                   4239:     return;
                   4240: 
                   4241: }
                   4242: 
                   4243: sub coauthorrolelog {
                   4244:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4245:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4246:         my $audom = $1;
                   4247:         my $auname = $2;
                   4248:         my $namespace = 'rolelog';
                   4249:         my %storehash = (
                   4250:                            role    => $trole,
                   4251:                            start   => $tstart,
                   4252:                            end     => $tend,
                   4253:                            context => $context,
                   4254:                         );
1.1188    raeburn  4255:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4256:                    $domain,$auname,$audom);
1.1184    raeburn  4257:     }
                   4258:     return;
                   4259: }
                   4260: 
1.351     www      4261: sub get_course_adv_roles {
1.948     raeburn  4262:     my ($cid,$codes) = @_;
1.620     albertel 4263:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4264:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4265:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4266:     my %nothide=();
1.800     albertel 4267:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4268:         if ($user !~ /:/) {
                   4269: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4270:         } else {
                   4271:             $nothide{$user}=1;
                   4272:         }
1.470     www      4273:     }
1.1219    raeburn  4274:     my @possdoms = ($coursehash{'domain'});
                   4275:     if ($coursehash{'checkforpriv'}) {
                   4276:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4277:     }
1.351     www      4278:     my %returnhash=();
                   4279:     my %dumphash=
                   4280:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4281:     my $now=time;
1.997     raeburn  4282:     my %privileged;
1.1000    raeburn  4283:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4284: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4285:         if (($tstart) && ($tstart<0)) { next; }
                   4286:         if (($tend) && ($tend<$now)) { next; }
                   4287:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4288:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4289: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4290:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4291:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4292: 	if ($role eq 'cr') { next; }
1.948     raeburn  4293:         if ($codes) {
                   4294:             if ($section) { $role .= ':'.$section; }
                   4295:             if ($returnhash{$role}) {
                   4296:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4297:             } else {
                   4298:                 $returnhash{$role}=$username.':'.$domain;
                   4299:             }
1.351     www      4300:         } else {
1.988     raeburn  4301:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4302:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4303:             if ($returnhash{$key}) {
                   4304: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4305:             } else {
                   4306:                 $returnhash{$key}=$username.':'.$domain;
                   4307:             }
1.351     www      4308:         }
1.948     raeburn  4309:     }
1.400     www      4310:     return %returnhash;
                   4311: }
                   4312: 
                   4313: sub get_my_roles {
1.937     raeburn  4314:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4315:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4316:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4317:     my (%dumphash,%nothide);
1.1086    raeburn  4318:     if ($context eq 'userroles') {
1.1166    raeburn  4319:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4320:     } else {
1.1219    raeburn  4321:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4322:         if ($hidepriv) {
                   4323:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4324:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4325:                 if ($user !~ /:/) {
                   4326:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4327:                 } else {
                   4328:                     $nothide{$user} = 1;
                   4329:                 }
                   4330:             }
                   4331:         }
1.858     raeburn  4332:     }
1.400     www      4333:     my %returnhash=();
                   4334:     my $now=time;
1.999     raeburn  4335:     my %privileged;
1.800     albertel 4336:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4337:         my ($role,$tend,$tstart);
                   4338:         if ($context eq 'userroles') {
1.1149    raeburn  4339:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4340: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4341:         } else {
                   4342:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4343:         }
1.400     www      4344:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4345:         my $status = 'active';
1.939     raeburn  4346:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4347:             $status = 'previous';
                   4348:         } 
                   4349:         if (($tstart) && ($now<$tstart)) {
                   4350:             $status = 'future';
                   4351:         }
                   4352:         if (ref($types) eq 'ARRAY') {
                   4353:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4354:                 next;
                   4355:             } 
                   4356:         } else {
                   4357:             if ($status ne 'active') {
                   4358:                 next;
                   4359:             }
                   4360:         }
1.867     raeburn  4361:         my ($rolecode,$username,$domain,$section,$area);
                   4362:         if ($context eq 'userroles') {
1.1186    raeburn  4363:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4364:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4365:         } else {
                   4366:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4367:         }
1.832     raeburn  4368:         if (ref($roledoms) eq 'ARRAY') {
                   4369:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4370:                 next;
                   4371:             }
                   4372:         }
                   4373:         if (ref($roles) eq 'ARRAY') {
                   4374:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4375:                 if ($role =~ /^cr\//) {
                   4376:                     if (!grep(/^cr$/,@{$roles})) {
                   4377:                         next;
                   4378:                     }
1.1104    raeburn  4379:                 } elsif ($role =~ /^gr\//) {
                   4380:                     if (!grep(/^gr$/,@{$roles})) {
                   4381:                         next;
                   4382:                     }
1.922     raeburn  4383:                 } else {
                   4384:                     next;
                   4385:                 }
1.832     raeburn  4386:             }
1.867     raeburn  4387:         }
1.937     raeburn  4388:         if ($hidepriv) {
1.1219    raeburn  4389:             my @privroles = ('dc','su');
1.999     raeburn  4390:             if ($context eq 'userroles') {
1.1219    raeburn  4391:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4392:             } else {
1.1219    raeburn  4393:                 my $possdoms = [$domain];
                   4394:                 if (ref($roledoms) eq 'ARRAY') {
                   4395:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4396:                 }
1.1219    raeburn  4397:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4398:                     if (!$nothide{$username.':'.$domain}) {
                   4399:                         next;
                   4400:                     }
                   4401:                 }
1.937     raeburn  4402:             }
                   4403:         }
1.933     raeburn  4404:         if ($withsec) {
                   4405:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4406:                 $tstart.':'.$tend;
                   4407:         } else {
                   4408:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4409:         }
1.832     raeburn  4410:     }
1.373     www      4411:     return %returnhash;
1.399     www      4412: }
                   4413: 
                   4414: # ----------------------------------------------------- Frontpage Announcements
                   4415: #
                   4416: #
                   4417: 
                   4418: sub postannounce {
                   4419:     my ($server,$text)=@_;
1.844     albertel 4420:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4421:     unless ($text=~/\w/) { $text=''; }
                   4422:     return &reply('setannounce:'.&escape($text),$server);
                   4423: }
                   4424: 
                   4425: sub getannounce {
1.448     albertel 4426: 
                   4427:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4428: 	my $announcement='';
1.800     albertel 4429: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4430: 	close($fh);
1.399     www      4431: 	if ($announcement=~/\w/) { 
                   4432: 	    return 
                   4433:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4434:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4435: 	} else {
                   4436: 	    return '';
                   4437: 	}
                   4438:     } else {
                   4439: 	return '';
                   4440:     }
1.351     www      4441: }
1.353     www      4442: 
                   4443: # ---------------------------------------------------------- Course ID routines
                   4444: # Deal with domain's nohist_courseid.db files
                   4445: #
                   4446: 
                   4447: sub courseidput {
1.921     raeburn  4448:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4449:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4450:     my $outcome;
                   4451:     if ($caller eq 'timeonly') {
                   4452:         my $cids = '';
                   4453:         foreach my $item (keys(%$storehash)) {
                   4454:             $cids.=&escape($item).'&';
                   4455:         }
                   4456:         $cids=~s/\&$//;
                   4457:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4458:                           $coursehome);       
                   4459:     } else {
                   4460:         my $items = '';
                   4461:         foreach my $item (keys(%$storehash)) {
                   4462:             $items.= &escape($item).'='.
                   4463:                      &freeze_escape($$storehash{$item}).'&';
                   4464:         }
                   4465:         $items=~s/\&$//;
                   4466:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4467:                           $coursehome);
1.918     raeburn  4468:     }
                   4469:     if ($outcome eq 'unknown_cmd') {
                   4470:         my $what;
                   4471:         foreach my $cid (keys(%$storehash)) {
                   4472:             $what .= &escape($cid).'=';
1.921     raeburn  4473:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4474:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4475:             }
                   4476:             $what =~ s/\:$/&/;
                   4477:         }
                   4478:         $what =~ s/\&$//;  
                   4479:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4480:     } else {
                   4481:         return $outcome;
                   4482:     }
1.353     www      4483: }
                   4484: 
                   4485: sub courseiddump {
1.921     raeburn  4486:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4487:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4488:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4489:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4490:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4491:     my $as_hash = 1;
                   4492:     my %returnhash;
                   4493:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4494:     my %libserv = &all_library();
                   4495:     foreach my $tryserver (keys(%libserv)) {
                   4496:         if ( (  $hostidflag == 1 
                   4497: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4498: 	     || (!defined($hostidflag)) ) {
                   4499: 
1.918     raeburn  4500: 	    if (($domfilter eq '') ||
                   4501: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4502:                 my $rep;
                   4503:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4504:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4505:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4506:                                 &escape($descfilter), &escape($instcodefilter), 
                   4507:                                 &escape($ownerfilter), &escape($coursefilter),
                   4508:                                 &escape($typefilter), &escape($regexp_ok), 
                   4509:                                 $as_hash, &escape($selfenrollonly), 
                   4510:                                 &escape($catfilter), $showhidden, $caller, 
                   4511:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4512:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  4513:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4514:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 4515:                 } else {
                   4516:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4517:                              $sincefilter.':'.&escape($descfilter).':'.
                   4518:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4519:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4520:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4521:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4522:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4523:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4524:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  4525:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4526:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 4527:                 }
                   4528:                      
1.918     raeburn  4529:                 my @pairs=split(/\&/,$rep);
                   4530:                 foreach my $item (@pairs) {
                   4531:                     my ($key,$value)=split(/\=/,$item,2);
                   4532:                     $key = &unescape($key);
                   4533:                     next if ($key =~ /^error: 2 /);
                   4534:                     my $result = &thaw_unescape($value);
                   4535:                     if (ref($result) eq 'HASH') {
                   4536:                         $returnhash{$key}=$result;
                   4537:                     } else {
1.921     raeburn  4538:                         my @responses = split(/:/,$value);
                   4539:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4540:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4541:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4542:                         }
1.1008    raeburn  4543:                     }
1.353     www      4544:                 }
                   4545:             }
                   4546:         }
                   4547:     }
                   4548:     return %returnhash;
                   4549: }
                   4550: 
1.1055    raeburn  4551: sub courselastaccess {
                   4552:     my ($cdom,$cnum,$hostidref) = @_;
                   4553:     my %returnhash;
                   4554:     if ($cdom && $cnum) {
                   4555:         my $chome = &homeserver($cnum,$cdom);
                   4556:         if ($chome ne 'no_host') {
                   4557:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4558:             &extract_lastaccess(\%returnhash,$rep);
                   4559:         }
                   4560:     } else {
                   4561:         if (!$cdom) { $cdom=''; }
                   4562:         my %libserv = &all_library();
                   4563:         foreach my $tryserver (keys(%libserv)) {
                   4564:             if (ref($hostidref) eq 'ARRAY') {
                   4565:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4566:             } 
                   4567:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4568:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4569:                 &extract_lastaccess(\%returnhash,$rep);
                   4570:             }
                   4571:         }
                   4572:     }
                   4573:     return %returnhash;
                   4574: }
                   4575: 
                   4576: sub extract_lastaccess {
                   4577:     my ($returnhash,$rep) = @_;
                   4578:     if (ref($returnhash) eq 'HASH') {
                   4579:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4580:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4581:                  $rep eq '') {
                   4582:             my @pairs=split(/\&/,$rep);
                   4583:             foreach my $item (@pairs) {
                   4584:                 my ($key,$value)=split(/\=/,$item,2);
                   4585:                 $key = &unescape($key);
                   4586:                 next if ($key =~ /^error: 2 /);
                   4587:                 $returnhash->{$key} = &thaw_unescape($value);
                   4588:             }
                   4589:         }
                   4590:     }
                   4591:     return;
                   4592: }
                   4593: 
1.658     raeburn  4594: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4595: 
                   4596: sub dcmailput {
1.685     raeburn  4597:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4598:     my $status = &Apache::lonnet::critical(
1.740     www      4599:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4600:        &escape($message),$server);
1.662     raeburn  4601:     return $status;
                   4602: }
                   4603: 
1.658     raeburn  4604: sub dcmaildump {
                   4605:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4606:     my %returnhash=();
1.846     albertel 4607: 
                   4608:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4609:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4610:                                                          &escape($enddate).':';
                   4611: 	my @esc_senders=map { &escape($_)} @$senders;
                   4612: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4613: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4614:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4615:             if (($key) && ($value)) {
                   4616:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4617:             }
                   4618:         }
                   4619:     }
                   4620:     return %returnhash;
                   4621: }
1.662     raeburn  4622: # ---------------------------------------------------------- Domain roles
                   4623: 
                   4624: sub get_domain_roles {
                   4625:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4626:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4627:         $startdate = '.';
                   4628:     }
1.1018    raeburn  4629:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4630:         $enddate = '.';
                   4631:     }
1.922     raeburn  4632:     my $rolelist;
                   4633:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4634:         $rolelist = join('&',@{$roles});
1.922     raeburn  4635:     }
1.662     raeburn  4636:     my %personnel = ();
1.841     albertel 4637: 
                   4638:     my %servers = &get_servers($dom,'library');
                   4639:     foreach my $tryserver (keys(%servers)) {
                   4640: 	%{$personnel{$tryserver}}=();
                   4641: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4642: 					    &escape($startdate).':'.
                   4643: 					    &escape($enddate).':'.
                   4644: 					    &escape($rolelist), $tryserver))) {
                   4645: 	    my ($key,$value) = split(/\=/,$line,2);
                   4646: 	    if (($key) && ($value)) {
                   4647: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4648: 	    }
                   4649: 	}
1.662     raeburn  4650:     }
                   4651:     return %personnel;
                   4652: }
1.658     raeburn  4653: 
1.1057    www      4654: # ----------------------------------------------------------- Interval timing 
1.149     www      4655: 
1.1153    www      4656: {
                   4657: # Caches needed for speedup of navmaps
                   4658: # We don't want to cache this for very long at all (5 seconds at most)
                   4659: # 
                   4660: # The user for whom we cache
                   4661: my $cachedkey='';
                   4662: # The cached times for this user
                   4663: my %cachedtimes=();
                   4664: # When this was last done
1.1282    raeburn  4665: my $cachedtime='';
1.1153    www      4666: 
                   4667: sub load_all_first_access {
1.1308    raeburn  4668:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      4669:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  4670:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   4671:         (!$ignorecache)) {
1.1154    raeburn  4672:         return;
                   4673:     }
                   4674:     $cachedtime=time;
                   4675:     $cachedkey=$uname.':'.$udom;
                   4676:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4677: }
                   4678: 
1.504     albertel 4679: sub get_first_access {
1.1308    raeburn  4680:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 4681:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4682:     if ($argsymb) { $symb=$argsymb; }
                   4683:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4684:     if ($argmap) { $map = $argmap; }
1.926     albertel 4685:     if ($type eq 'course') {
                   4686: 	$res='course';
                   4687:     } elsif ($type eq 'map') {
1.588     albertel 4688: 	$res=&symbread($map);
                   4689:     } else {
                   4690: 	$res=$symb;
                   4691:     }
1.1308    raeburn  4692:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      4693:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4694: }
                   4695: 
                   4696: sub set_first_access {
1.1162    raeburn  4697:     my ($type,$interval)=@_;
1.790     albertel 4698:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4699:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4700:     if ($type eq 'course') {
                   4701: 	$res='course';
                   4702:     } elsif ($type eq 'map') {
1.588     albertel 4703: 	$res=&symbread($map);
                   4704:     } else {
                   4705: 	$res=$symb;
                   4706:     }
1.1153    www      4707:     $cachedkey='';
1.1162    raeburn  4708:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4709:     if (!$firstaccess) {
1.1162    raeburn  4710:         my $start = time;
                   4711: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4712:                           $udom,$uname);
                   4713:         if ($putres eq 'ok') {
                   4714:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4715:                  $udom,$uname); 
                   4716:             &appenv(
                   4717:                      {
                   4718:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4719:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4720:                      }
                   4721:                   );
                   4722:         }
                   4723:         return $putres;
1.505     albertel 4724:     }
                   4725:     return 'already_set';
1.504     albertel 4726: }
1.1153    www      4727: }
1.1282    raeburn  4728: 
1.110     www      4729: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4730: 
                   4731: sub expirespread {
                   4732:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4733:     my $cid=$env{'request.course.id'}; 
1.110     www      4734:     if ($cid) {
                   4735:        my $now=time;
                   4736:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4737:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4738:                             $env{'course.'.$cid.'.num'}.
1.110     www      4739: 	        	    ':nohist_expirationdates:'.
                   4740:                             &escape($key).'='.$now,
1.620     albertel 4741:                             $env{'course.'.$cid.'.home'})
1.110     www      4742:     }
                   4743:     return 'ok';
1.14      www      4744: }
                   4745: 
1.109     www      4746: # ----------------------------------------------------- Devalidate Spreadsheets
                   4747: 
                   4748: sub devalidate {
1.325     www      4749:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4750:     my $cid=$env{'request.course.id'}; 
1.109     www      4751:     if ($cid) {
1.391     matthew  4752:         # delete the stored spreadsheets for
                   4753:         # - the student level sheet of this user in course's homespace
                   4754:         # - the assessment level sheet for this resource 
                   4755:         #   for this user in user's homespace
1.553     albertel 4756: 	# - current conditional state info
1.325     www      4757: 	my $key=$uname.':'.$udom.':';
1.109     www      4758:         my $status=
1.299     matthew  4759: 	    &del('nohist_calculatedsheets',
1.391     matthew  4760: 		 [$key.'studentcalc:'],
1.620     albertel 4761: 		 $env{'course.'.$cid.'.domain'},
                   4762: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4763: 		.' '.
                   4764: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4765: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4766:         unless ($status eq 'ok ok') {
                   4767:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4768:                     $uname.' at '.$udom.' for '.
1.109     www      4769: 		    $symb.': '.$status);
1.133     albertel 4770:         }
1.553     albertel 4771: 	&delenv('user.state.'.$cid);
1.109     www      4772:     }
                   4773: }
                   4774: 
1.265     albertel 4775: sub get_scalar {
                   4776:     my ($string,$end) = @_;
                   4777:     my $value;
                   4778:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4779: 	$value = $1;
                   4780:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4781: 	$value = $1;
                   4782:     }
                   4783:     return &unescape($value);
                   4784: }
                   4785: 
                   4786: sub array2str {
                   4787:   my (@array) = @_;
                   4788:   my $result=&arrayref2str(\@array);
                   4789:   $result=~s/^__ARRAY_REF__//;
                   4790:   $result=~s/__END_ARRAY_REF__$//;
                   4791:   return $result;
                   4792: }
                   4793: 
1.204     albertel 4794: sub arrayref2str {
                   4795:   my ($arrayref) = @_;
1.265     albertel 4796:   my $result='__ARRAY_REF__';
1.204     albertel 4797:   foreach my $elem (@$arrayref) {
1.265     albertel 4798:     if(ref($elem) eq 'ARRAY') {
                   4799:       $result.=&arrayref2str($elem).'&';
                   4800:     } elsif(ref($elem) eq 'HASH') {
                   4801:       $result.=&hashref2str($elem).'&';
                   4802:     } elsif(ref($elem)) {
                   4803:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4804:     } else {
                   4805:       $result.=&escape($elem).'&';
                   4806:     }
                   4807:   }
                   4808:   $result=~s/\&$//;
1.265     albertel 4809:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4810:   return $result;
                   4811: }
                   4812: 
1.168     albertel 4813: sub hash2str {
1.204     albertel 4814:   my (%hash) = @_;
                   4815:   my $result=&hashref2str(\%hash);
1.265     albertel 4816:   $result=~s/^__HASH_REF__//;
                   4817:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4818:   return $result;
                   4819: }
                   4820: 
                   4821: sub hashref2str {
                   4822:   my ($hashref)=@_;
1.265     albertel 4823:   my $result='__HASH_REF__';
1.800     albertel 4824:   foreach my $key (sort(keys(%$hashref))) {
                   4825:     if (ref($key) eq 'ARRAY') {
                   4826:       $result.=&arrayref2str($key).'=';
                   4827:     } elsif (ref($key) eq 'HASH') {
                   4828:       $result.=&hashref2str($key).'=';
                   4829:     } elsif (ref($key)) {
1.265     albertel 4830:       $result.='=';
1.800     albertel 4831:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4832:     } else {
1.1132    raeburn  4833: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4834:     }
                   4835: 
1.800     albertel 4836:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4837:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4838:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4839:       $result.=&hashref2str($hashref->{$key}).'&';
                   4840:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4841:        $result.='&';
1.800     albertel 4842:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4843:     } else {
1.800     albertel 4844:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4845:     }
                   4846:   }
1.168     albertel 4847:   $result=~s/\&$//;
1.265     albertel 4848:   $result .= '__END_HASH_REF__';
1.168     albertel 4849:   return $result;
                   4850: }
                   4851: 
                   4852: sub str2hash {
1.265     albertel 4853:     my ($string)=@_;
                   4854:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4855:     return %$hash;
                   4856: }
                   4857: 
                   4858: sub str2hashref {
1.168     albertel 4859:   my ($string) = @_;
1.265     albertel 4860: 
                   4861:   my %hash;
                   4862: 
                   4863:   if($string !~ /^__HASH_REF__/) {
                   4864:       if (! ($string eq '' || !defined($string))) {
                   4865: 	  $hash{'error'}='Not hash reference';
                   4866:       }
                   4867:       return (\%hash, $string);
                   4868:   }
                   4869: 
                   4870:   $string =~ s/^__HASH_REF__//;
                   4871: 
                   4872:   while($string !~ /^__END_HASH_REF__/) {
                   4873:       #key
                   4874:       my $key='';
                   4875:       if($string =~ /^__HASH_REF__/) {
                   4876:           ($key, $string)=&str2hashref($string);
                   4877:           if(defined($key->{'error'})) {
                   4878:               $hash{'error'}='Bad data';
                   4879:               return (\%hash, $string);
                   4880:           }
                   4881:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4882:           ($key, $string)=&str2arrayref($string);
                   4883:           if($key->[0] eq 'Array reference error') {
                   4884:               $hash{'error'}='Bad data';
                   4885:               return (\%hash, $string);
                   4886:           }
                   4887:       } else {
                   4888:           $string =~ s/^(.*?)=//;
1.267     albertel 4889: 	  $key=&unescape($1);
1.265     albertel 4890:       }
                   4891:       $string =~ s/^=//;
                   4892: 
                   4893:       #value
                   4894:       my $value='';
                   4895:       if($string =~ /^__HASH_REF__/) {
                   4896:           ($value, $string)=&str2hashref($string);
                   4897:           if(defined($value->{'error'})) {
                   4898:               $hash{'error'}='Bad data';
                   4899:               return (\%hash, $string);
                   4900:           }
                   4901:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4902:           ($value, $string)=&str2arrayref($string);
                   4903:           if($value->[0] eq 'Array reference error') {
                   4904:               $hash{'error'}='Bad data';
                   4905:               return (\%hash, $string);
                   4906:           }
                   4907:       } else {
                   4908: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4909:       }
                   4910:       $string =~ s/^&//;
                   4911: 
                   4912:       $hash{$key}=$value;
1.204     albertel 4913:   }
1.265     albertel 4914: 
                   4915:   $string =~ s/^__END_HASH_REF__//;
                   4916: 
                   4917:   return (\%hash, $string);
1.204     albertel 4918: }
                   4919: 
                   4920: sub str2array {
1.265     albertel 4921:     my ($string)=@_;
                   4922:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4923:     return @$array;
                   4924: }
                   4925: 
                   4926: sub str2arrayref {
1.204     albertel 4927:   my ($string) = @_;
1.265     albertel 4928:   my @array;
                   4929: 
                   4930:   if($string !~ /^__ARRAY_REF__/) {
                   4931:       if (! ($string eq '' || !defined($string))) {
                   4932: 	  $array[0]='Array reference error';
                   4933:       }
                   4934:       return (\@array, $string);
                   4935:   }
                   4936: 
                   4937:   $string =~ s/^__ARRAY_REF__//;
                   4938: 
                   4939:   while($string !~ /^__END_ARRAY_REF__/) {
                   4940:       my $value='';
                   4941:       if($string =~ /^__HASH_REF__/) {
                   4942:           ($value, $string)=&str2hashref($string);
                   4943:           if(defined($value->{'error'})) {
                   4944:               $array[0] ='Array reference error';
                   4945:               return (\@array, $string);
                   4946:           }
                   4947:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4948:           ($value, $string)=&str2arrayref($string);
                   4949:           if($value->[0] eq 'Array reference error') {
                   4950:               $array[0] ='Array reference error';
                   4951:               return (\@array, $string);
                   4952:           }
                   4953:       } else {
                   4954: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4955:       }
                   4956:       $string =~ s/^&//;
                   4957: 
                   4958:       push(@array, $value);
1.191     harris41 4959:   }
1.265     albertel 4960: 
                   4961:   $string =~ s/^__END_ARRAY_REF__//;
                   4962: 
                   4963:   return (\@array, $string);
1.168     albertel 4964: }
                   4965: 
1.167     albertel 4966: # -------------------------------------------------------------------Temp Store
                   4967: 
1.168     albertel 4968: sub tmpreset {
                   4969:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4970:   if (!$symb) {
                   4971:     $symb=&symbread();
1.620     albertel 4972:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4973:   }
                   4974:   $symb=escape($symb);
                   4975: 
1.620     albertel 4976:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4977:   $namespace=~s/\//\_/g;
                   4978:   $namespace=~s/\W//g;
                   4979: 
1.620     albertel 4980:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4981:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4982:   if ($domain eq 'public' && $stuname eq 'public') {
                   4983:       $stuname=$ENV{'REMOTE_ADDR'};
                   4984:   }
1.1117    foxr     4985:   my $path=LONCAPA::tempdir();
1.168     albertel 4986:   my %hash;
                   4987:   if (tie(%hash,'GDBM_File',
                   4988: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4989: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4990:     foreach my $key (keys(%hash)) {
1.180     albertel 4991:       if ($key=~ /:$symb/) {
1.168     albertel 4992: 	delete($hash{$key});
                   4993:       }
                   4994:     }
                   4995:   }
                   4996: }
                   4997: 
1.167     albertel 4998: sub tmpstore {
1.168     albertel 4999:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5000: 
                   5001:   if (!$symb) {
                   5002:     $symb=&symbread();
1.620     albertel 5003:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5004:   }
                   5005:   $symb=escape($symb);
                   5006: 
                   5007:   if (!$namespace) {
                   5008:     # I don't think we would ever want to store this for a course.
                   5009:     # it seems this will only be used if we don't have a course.
1.620     albertel 5010:     #$namespace=$env{'request.course.id'};
1.168     albertel 5011:     #if (!$namespace) {
1.620     albertel 5012:       $namespace=$env{'request.state'};
1.168     albertel 5013:     #}
                   5014:   }
                   5015:   $namespace=~s/\//\_/g;
                   5016:   $namespace=~s/\W//g;
1.620     albertel 5017:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5018:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5019:   if ($domain eq 'public' && $stuname eq 'public') {
                   5020:       $stuname=$ENV{'REMOTE_ADDR'};
                   5021:   }
1.168     albertel 5022:   my $now=time;
                   5023:   my %hash;
1.1117    foxr     5024:   my $path=LONCAPA::tempdir();
1.168     albertel 5025:   if (tie(%hash,'GDBM_File',
                   5026: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5027: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5028:     $hash{"version:$symb"}++;
                   5029:     my $version=$hash{"version:$symb"};
                   5030:     my $allkeys=''; 
                   5031:     foreach my $key (keys(%$storehash)) {
                   5032:       $allkeys.=$key.':';
1.591     albertel 5033:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5034:     }
                   5035:     $hash{"$version:$symb:timestamp"}=$now;
                   5036:     $allkeys.='timestamp';
                   5037:     $hash{"$version:keys:$symb"}=$allkeys;
                   5038:     if (untie(%hash)) {
                   5039:       return 'ok';
                   5040:     } else {
                   5041:       return "error:$!";
                   5042:     }
                   5043:   } else {
                   5044:     return "error:$!";
                   5045:   }
                   5046: }
1.167     albertel 5047: 
1.168     albertel 5048: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5049: 
1.168     albertel 5050: sub tmprestore {
                   5051:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5052: 
1.168     albertel 5053:   if (!$symb) {
                   5054:     $symb=&symbread();
1.620     albertel 5055:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5056:   }
                   5057:   $symb=escape($symb);
                   5058: 
1.620     albertel 5059:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5060: 
1.620     albertel 5061:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5062:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5063:   if ($domain eq 'public' && $stuname eq 'public') {
                   5064:       $stuname=$ENV{'REMOTE_ADDR'};
                   5065:   }
1.168     albertel 5066:   my %returnhash;
                   5067:   $namespace=~s/\//\_/g;
                   5068:   $namespace=~s/\W//g;
                   5069:   my %hash;
1.1117    foxr     5070:   my $path=LONCAPA::tempdir();
1.168     albertel 5071:   if (tie(%hash,'GDBM_File',
                   5072: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5073: 	  &GDBM_READER(),0640)) {
1.168     albertel 5074:     my $version=$hash{"version:$symb"};
                   5075:     $returnhash{'version'}=$version;
                   5076:     my $scope;
                   5077:     for ($scope=1;$scope<=$version;$scope++) {
                   5078:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5079:       my @keys=split(/:/,$vkeys);
                   5080:       my $key;
                   5081:       $returnhash{"$scope:keys"}=$vkeys;
                   5082:       foreach $key (@keys) {
1.591     albertel 5083: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5084: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5085:       }
                   5086:     }
1.168     albertel 5087:     if (!(untie(%hash))) {
                   5088:       return "error:$!";
                   5089:     }
                   5090:   } else {
                   5091:     return "error:$!";
                   5092:   }
                   5093:   return %returnhash;
1.167     albertel 5094: }
                   5095: 
1.9       www      5096: # ----------------------------------------------------------------------- Store
                   5097: 
                   5098: sub store {
1.1269    raeburn  5099:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5100:     my $home='';
                   5101: 
1.168     albertel 5102:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5103: 
1.213     www      5104:     $symb=&symbclean($symb);
1.122     albertel 5105:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5106: 
1.620     albertel 5107:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5108:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5109: 
                   5110:     &devalidate($symb,$stuname,$domain);
1.109     www      5111: 
                   5112:     $symb=escape($symb);
1.187     www      5113:     if (!$namespace) { 
1.620     albertel 5114:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5115:           return ''; 
                   5116:        } 
                   5117:     }
1.620     albertel 5118:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5119: 
                   5120:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5121:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5122: 
1.12      www      5123:     my $namevalue='';
1.800     albertel 5124:     foreach my $key (keys(%$storehash)) {
                   5125:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5126:     }
1.12      www      5127:     $namevalue=~s/\&$//;
1.187     www      5128:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5129:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5130: }
                   5131: 
1.47      www      5132: # -------------------------------------------------------------- Critical Store
                   5133: 
                   5134: sub cstore {
1.1269    raeburn  5135:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5136:     my $home='';
                   5137: 
1.168     albertel 5138:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5139: 
1.213     www      5140:     $symb=&symbclean($symb);
1.122     albertel 5141:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5142: 
1.620     albertel 5143:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5144:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5145: 
                   5146:     &devalidate($symb,$stuname,$domain);
1.109     www      5147: 
                   5148:     $symb=escape($symb);
1.187     www      5149:     if (!$namespace) { 
1.620     albertel 5150:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5151:           return ''; 
                   5152:        } 
                   5153:     }
1.620     albertel 5154:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5155: 
                   5156:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5157:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5158: 
1.47      www      5159:     my $namevalue='';
1.800     albertel 5160:     foreach my $key (keys(%$storehash)) {
                   5161:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5162:     }
1.47      www      5163:     $namevalue=~s/\&$//;
1.187     www      5164:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5165:     return critical
1.1269    raeburn  5166:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5167: }
                   5168: 
1.9       www      5169: # --------------------------------------------------------------------- Restore
                   5170: 
                   5171: sub restore {
1.124     www      5172:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5173:     my $home='';
                   5174: 
1.168     albertel 5175:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5176: 
1.122     albertel 5177:     if (!$symb) {
1.1224    raeburn  5178:         return if ($namespace eq 'courserequests');
                   5179:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5180:     } else {
1.1224    raeburn  5181:         unless ($namespace eq 'courserequests') {
                   5182:             $symb=&escape(&symbclean($symb));
                   5183:         }
1.122     albertel 5184:     }
1.188     www      5185:     if (!$namespace) { 
1.620     albertel 5186:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5187:           return ''; 
                   5188:        } 
                   5189:     }
1.620     albertel 5190:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5191:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5192:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5193:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5194: 
1.12      www      5195:     my %returnhash=();
1.800     albertel 5196:     foreach my $line (split(/\&/,$answer)) {
                   5197: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5198:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5199:     }
1.75      www      5200:     my $version;
                   5201:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5202:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5203:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5204:        }
1.75      www      5205:     }
1.13      www      5206:     return %returnhash;
1.34      www      5207: }
                   5208: 
                   5209: # ---------------------------------------------------------- Course Description
1.1118    foxr     5210: #
                   5211: #  
1.34      www      5212: 
                   5213: sub coursedescription {
1.731     albertel 5214:     my ($courseid,$args)=@_;
1.34      www      5215:     $courseid=~s/^\///;
1.49      www      5216:     $courseid=~s/\_/\//g;
1.34      www      5217:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5218:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5219:     my $normalid=$cdomain.'_'.$cnum;
                   5220:     # need to always cache even if we get errors otherwise we keep 
                   5221:     # trying and trying and trying to get the course description.
                   5222:     my %envhash=();
                   5223:     my %returnhash=();
1.731     albertel 5224:     
                   5225:     my $expiretime=600;
                   5226:     if ($env{'request.course.id'} eq $normalid) {
                   5227: 	$expiretime=120;
                   5228:     }
                   5229: 
                   5230:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5231:     if (!$args->{'freshen_cache'}
                   5232: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5233: 	foreach my $key (keys(%env)) {
                   5234: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5235: 	    my ($setting) = $1;
                   5236: 	    $returnhash{$setting} = $env{$key};
                   5237: 	}
                   5238: 	return %returnhash;
                   5239:     }
                   5240: 
1.1118    foxr     5241:     # get the data again
                   5242: 
1.731     albertel 5243:     if (!$args->{'one_time'}) {
                   5244: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5245:     }
1.811     albertel 5246: 
1.34      www      5247:     if ($chome ne 'no_host') {
1.302     albertel 5248:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5249:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5250: 	   my $username = $env{'user.name'}; # Defult username
                   5251: 	   if(defined $args->{'user'}) {
                   5252: 	       $username = $args->{'user'};
                   5253: 	   }
1.129     albertel 5254:            $returnhash{'home'}= $chome;
                   5255: 	   $returnhash{'domain'} = $cdomain;
                   5256: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5257:            if (!defined($returnhash{'type'})) {
                   5258:                $returnhash{'type'} = 'Course';
                   5259:            }
1.130     albertel 5260:            while (my ($name,$value) = each %returnhash) {
1.53      www      5261:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5262:            }
1.270     www      5263:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5264:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5265: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5266:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5267:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5268:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5269:        }
                   5270:     }
1.731     albertel 5271:     if (!$args->{'one_time'}) {
1.949     raeburn  5272: 	&appenv(\%envhash);
1.731     albertel 5273:     }
1.302     albertel 5274:     return %returnhash;
1.461     www      5275: }
                   5276: 
1.1080    raeburn  5277: sub update_released_required {
                   5278:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5279:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5280:         $cid = $env{'request.course.id'};
                   5281:         $cdom = $env{'course.'.$cid.'.domain'};
                   5282:         $cnum = $env{'course.'.$cid.'.num'};
                   5283:         $chome = $env{'course.'.$cid.'.home'};
                   5284:     }
                   5285:     if ($needsrelease) {
                   5286:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5287:         my $needsupdate;
                   5288:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5289:             $needsupdate = 1;
                   5290:         } else {
                   5291:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5292:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5293:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5294:                 $needsupdate = 1;
                   5295:             }
                   5296:         }
                   5297:         if ($needsupdate) {
                   5298:             my %needshash = (
                   5299:                              'internal.releaserequired' => $needsrelease,
                   5300:                             );
                   5301:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5302:             if ($putresult eq 'ok') {
                   5303:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5304:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5305:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5306:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5307:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5308:                 }
                   5309:             }
                   5310:         }
                   5311:     }
                   5312:     return;
                   5313: }
                   5314: 
1.461     www      5315: # -------------------------------------------------See if a user is privileged
                   5316: 
                   5317: sub privileged {
1.1219    raeburn  5318:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5319:     my $now = time;
1.1219    raeburn  5320:     my $roles;
                   5321:     if (ref($possroles) eq 'ARRAY') {
                   5322:         $roles = $possroles; 
                   5323:     } else {
                   5324:         $roles = ['dc','su'];
                   5325:     }
                   5326:     if (ref($possdomains) eq 'ARRAY') {
                   5327:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5328:         foreach my $dom (@{$possdomains}) {
                   5329:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5330:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5331:                 foreach my $role (@{$roles}) {
                   5332:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5333:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5334:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5335:                             return 1 unless (($end && $end < $now) ||
                   5336:                                              ($start && $start > $now));
                   5337:                         }
                   5338:                     }
                   5339:                 }
                   5340:             }
                   5341:         }
                   5342:     } else {
                   5343:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5344:         my $now = time;
1.1170    droeschl 5345: 
1.1275    musolffc 5346:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5347:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5348:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5349:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5350:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5351:             }
1.1219    raeburn  5352:         }
                   5353:     }
                   5354:     return 0;
                   5355: }
1.1170    droeschl 5356: 
1.1219    raeburn  5357: sub privileged_by_domain {
                   5358:     my ($domains,$roles) = @_;
                   5359:     my %privileged = ();
                   5360:     my $cachetime = 60*60*24;
                   5361:     my $now = time;
                   5362:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5363:         return %privileged;
                   5364:     }
                   5365:     foreach my $dom (@{$domains}) {
                   5366:         next if (ref($privileged{$dom}) eq 'HASH');
                   5367:         my $needroles;
                   5368:         foreach my $role (@{$roles}) {
                   5369:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5370:             if (defined($cached)) {
                   5371:                 if (ref($result) eq 'HASH') {
                   5372:                     $privileged{$dom}{$role} = $result;
                   5373:                 }
                   5374:             } else {
                   5375:                 $needroles = 1;
                   5376:             }
                   5377:         }
                   5378:         if ($needroles) {
                   5379:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5380:             $privileged{$dom} = {};
                   5381:             foreach my $server (keys(%dompersonnel)) {
                   5382:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5383:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5384:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5385:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5386:                         next if ($end && $end < $now);
                   5387:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5388:                             $dompersonnel{$server}{$item};
                   5389:                     }
                   5390:                 }
                   5391:             }
                   5392:             if (ref($privileged{$dom}) eq 'HASH') {
                   5393:                 foreach my $role (@{$roles}) {
                   5394:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5395:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5396:                     } else {
                   5397:                         my %hash = ();
                   5398:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5399:                     }
                   5400:                 }
                   5401:             }
                   5402:         }
                   5403:     }
                   5404:     return %privileged;
1.9       www      5405: }
1.1       albertel 5406: 
1.103     harris41 5407: # -------------------------------------------------------- Get user privileges
1.11      www      5408: 
                   5409: sub rolesinit {
1.1169    droeschl 5410:     my ($domain, $username) = @_;
                   5411:     my %userroles = ('user.login.time' => time);
                   5412:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5413: 
                   5414:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5415:     # also, blocking can be triggered by an activating timer
                   5416:     # it's saved in the user's %env.
                   5417:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5418:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5419:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5420:         %timerintchk, %timerintenv);
                   5421: 
1.1162    raeburn  5422:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5423:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5424:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5425:     }
1.1169    droeschl 5426: 
1.1162    raeburn  5427:     foreach my $key (keys(%timerinterval)) {
                   5428:         my ($cid,$rest) = split(/\0/,$key);
                   5429:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5430:     }
1.1169    droeschl 5431: 
1.11      www      5432:     my %allroles=();
1.1162    raeburn  5433:     my %allgroups=();
1.11      www      5434: 
1.1274    raeburn  5435:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5436:         my $role = $rolesdump{$area};
                   5437:         $area =~ s/\_\w\w$//;
                   5438: 
                   5439:         my ($trole, $tend, $tstart, $group_privs);
                   5440: 
                   5441:         if ($role =~ /^cr/) {
                   5442:         # Custom role, defined by a user 
                   5443:         # e.g., user.role.cr/msu/smith/mynewrole
                   5444:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5445:                 $trole = $1;
                   5446:                 ($tend, $tstart) = split('_', $2);
                   5447:             } else {
                   5448:                 $trole = $role;
                   5449:             }
                   5450:         } elsif ($role =~ m|^gr/|) {
                   5451:         # Role of member in a group, defined within a course/community
                   5452:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5453:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5454:             next if $tstart eq '-1';
                   5455:             ($trole, $group_privs) = split(/\//, $trole);
                   5456:             $group_privs = &unescape($group_privs);
                   5457:         } else {
                   5458:         # Just a normal role, defined in roles.tab
                   5459:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5460:         }
                   5461: 
                   5462:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5463:                  $username);
                   5464:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5465: 
                   5466:         # role expired or not available yet?
                   5467:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5468:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5469: 
                   5470:         next if $area eq '' or $trole eq '';
                   5471: 
                   5472:         my $spec = "$trole.$area";
                   5473:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5474: 
                   5475:         if ($trole =~ /^cr\//) {
                   5476:         # Custom role, defined by a user
                   5477:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5478:         } elsif ($trole eq 'gr') {
                   5479:         # Role of a member in a group, defined within a course/community
                   5480:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5481:             next;
                   5482:         } else {
                   5483:         # Normal role, defined in roles.tab
                   5484:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5485:         }
                   5486: 
                   5487:         my $cid = $tdomain.'_'.$trest;
                   5488:         unless ($firstaccchk{$cid}) {
                   5489:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5490:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5491:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5492:                         $coursetimerstarts{$cid}{$item}; 
                   5493:                 }
                   5494:             }
                   5495:             $firstaccchk{$cid} = 1;
                   5496:         }
                   5497:         unless ($timerintchk{$cid}) {
                   5498:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5499:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5500:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5501:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5502:                 }
1.12      www      5503:             }
1.1169    droeschl 5504:             $timerintchk{$cid} = 1;
1.191     harris41 5505:         }
1.11      www      5506:     }
1.1169    droeschl 5507: 
                   5508:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5509:         \%allroles, \%allgroups);
                   5510:     $env{'user.adv'} = $userroles{'user.adv'};
                   5511: 
1.1162    raeburn  5512:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5513: }
                   5514: 
1.567     raeburn  5515: sub set_arearole {
1.1215    raeburn  5516:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5517:     unless ($nolog) {
1.567     raeburn  5518: # log the associated role with the area
1.1215    raeburn  5519:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5520:     }
1.743     albertel 5521:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5522: }
                   5523: 
                   5524: sub custom_roleprivs {
                   5525:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5526:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5527:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5528:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5529:         my ($rdummy,$roledef)=
                   5530:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5531:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5532:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5533:             if (defined($syspriv)) {
1.1043    raeburn  5534:                 if ($trest =~ /^$match_community$/) {
                   5535:                     $syspriv =~ s/bre\&S//; 
                   5536:                 }
1.567     raeburn  5537:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5538:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5539:             }
                   5540:             if ($tdomain ne '') {
                   5541:                 if (defined($dompriv)) {
                   5542:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5543:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5544:                 }
                   5545:                 if (($trest ne '') && (defined($coursepriv))) {
                   5546:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5547:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5548:                 }
                   5549:             }
                   5550:         }
                   5551:     }
                   5552: }
                   5553: 
1.678     raeburn  5554: sub group_roleprivs {
                   5555:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5556:     my $access = 1;
                   5557:     my $now = time;
                   5558:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5559:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5560:     if ($access) {
1.811     albertel 5561:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5562:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5563:     }
                   5564: }
1.567     raeburn  5565: 
                   5566: sub standard_roleprivs {
                   5567:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5568:     if (defined($pr{$trole.':s'})) {
                   5569:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5570:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5571:     }
                   5572:     if ($tdomain ne '') {
                   5573:         if (defined($pr{$trole.':d'})) {
                   5574:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5575:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5576:         }
                   5577:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5578:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5579:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5580:         }
                   5581:     }
                   5582: }
                   5583: 
                   5584: sub set_userprivs {
1.1064    raeburn  5585:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5586:     my $author=0;
                   5587:     my $adv=0;
1.678     raeburn  5588:     my %grouproles = ();
                   5589:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5590:         my @groupkeys; 
1.1000    raeburn  5591:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5592:             push(@groupkeys,$role);
                   5593:         }
                   5594:         if (ref($groups_roles) eq 'HASH') {
                   5595:             foreach my $key (keys(%{$groups_roles})) {
                   5596:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5597:                     push(@groupkeys,$key);
                   5598:                 }
                   5599:             }
                   5600:         }
                   5601:         if (@groupkeys > 0) {
                   5602:             foreach my $role (@groupkeys) {
                   5603:                 my ($trole,$area,$sec,$extendedarea);
                   5604:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5605:                     $trole = $1;
                   5606:                     $area = $2;
                   5607:                     $sec = $3;
                   5608:                     $extendedarea = $area.$sec;
                   5609:                     if (exists($$allgroups{$area})) {
                   5610:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5611:                             my $spec = $trole.'.'.$extendedarea;
                   5612:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5613:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5614:                         }
1.678     raeburn  5615:                     }
                   5616:                 }
                   5617:             }
                   5618:         }
                   5619:     }
1.800     albertel 5620:     foreach my $group (keys(%grouproles)) {
                   5621:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5622:     }
1.800     albertel 5623:     foreach my $role (keys(%{$allroles})) {
                   5624:         my %thesepriv;
1.941     raeburn  5625:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5626:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5627:             if ($item ne '') {
                   5628:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5629:                 if ($restrictions eq '') {
                   5630:                     $thesepriv{$privilege}='F';
                   5631:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5632:                     $thesepriv{$privilege}.=$restrictions;
                   5633:                 }
                   5634:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5635:             }
                   5636:         }
                   5637:         my $thesestr='';
1.1104    raeburn  5638:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5639: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5640: 	}
                   5641:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5642:     }
                   5643:     return ($author,$adv);
                   5644: }
                   5645: 
1.994     raeburn  5646: sub role_status {
1.1104    raeburn  5647:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5648:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5649:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5650:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5651:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5652:             $$where = '/'.$two;
1.994     raeburn  5653:             $$trolecode=$$role.'.'.$$where;
                   5654:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5655:             $$tstatus='is';
1.1104    raeburn  5656:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5657:                 $$tstatus='future';
1.1034    raeburn  5658:                 if ($$tstart<$now) {
                   5659:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5660:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5661:                             my (%allroles,%allgroups,$group_privs,
                   5662:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5663:                             my %userroles = (
                   5664:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5665:                             );
1.1064    raeburn  5666:                             @rolecodes = ('cm'); 
1.1002    raeburn  5667:                             my $spec=$$role.'.'.$$where;
                   5668:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5669:                             if ($$role =~ /^cr\//) {
                   5670:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5671:                                 push(@rolecodes,'cr');
1.1002    raeburn  5672:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5673:                                 push(@rolecodes,$$role);
1.1002    raeburn  5674:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5675:                                                     $env{'user.name'});
1.1064    raeburn  5676:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5677:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5678:                                 $group_privs = &unescape($group_privs);
                   5679:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5680:                                 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  5681:                                 &get_groups_roles($tdomain,$trest,
                   5682:                                                   \%course_roles,\@rolecodes,
                   5683:                                                   \%groups_roles);
1.1002    raeburn  5684:                             } else {
1.1064    raeburn  5685:                                 push(@rolecodes,$$role);
1.1002    raeburn  5686:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5687:                             }
1.1064    raeburn  5688:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5689:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5690:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5691:                         }
                   5692:                     }
1.1034    raeburn  5693:                     $$tstatus = 'is';
1.1002    raeburn  5694:                 }
1.994     raeburn  5695:             }
                   5696:             if ($$tend) {
1.1104    raeburn  5697:                 if ($$tend<$update) {
1.994     raeburn  5698:                     $$tstatus='expired';
                   5699:                 } elsif ($$tend<$now) {
                   5700:                     $$tstatus='will_not';
                   5701:                 }
                   5702:             }
                   5703:         }
                   5704:     }
                   5705: }
                   5706: 
1.1104    raeburn  5707: sub get_groups_roles {
                   5708:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5709:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5710:                   (ref($rolecodes) eq 'ARRAY') && 
                   5711:                   (ref($groups_roles) eq 'HASH')); 
                   5712:     if (keys(%{$cdom_courseroles}) > 0) {
                   5713:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5714:         if ($cdom ne '' && $cnum ne '') {
                   5715:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5716:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5717:                     my $crsrole = $1;
                   5718:                     my $crssec = $2;
                   5719:                     if ($crsrole =~ /^cr/) {
                   5720:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5721:                             push(@{$rolecodes},'cr');
                   5722:                         }
                   5723:                     } else {
                   5724:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5725:                             push(@{$rolecodes},$crsrole);
                   5726:                         }
                   5727:                     }
                   5728:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5729:                     if ($crssec ne '') {
                   5730:                         $rolekey .= "/$crssec";
                   5731:                     }
                   5732:                     $rolekey .= './';
                   5733:                     $groups_roles->{$rolekey} = $rolecodes;
                   5734:                 }
                   5735:             }
                   5736:         }
                   5737:     }
                   5738:     return;
                   5739: }
                   5740: 
                   5741: sub delete_env_groupprivs {
                   5742:     my ($where,$courseroles,$possroles) = @_;
                   5743:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5744:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5745:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5746:         %{$courseroles->{$udom}} =
                   5747:             &get_my_roles('','','userroles',['active'],
                   5748:                           $possroles,[$udom],1);
                   5749:     }
                   5750:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5751:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5752:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5753:             my $area = '/'.$cdom.'/'.$cnum;
                   5754:             my $privkey = "user.priv.$crsrole.$area";
                   5755:             if ($crssec ne '') {
                   5756:                 $privkey .= '/'.$crssec;
                   5757:             }
                   5758:             $privkey .= ".$area/$group";
                   5759:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5760:         }
                   5761:     }
                   5762:     return;
                   5763: }
                   5764: 
1.994     raeburn  5765: sub check_adhoc_privs {
1.1104    raeburn  5766:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5767:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5768:     my $setprivs;
1.994     raeburn  5769:     if ($env{$cckey}) {
                   5770:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5771:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5772:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5773:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5774:             $setprivs = 1;
1.994     raeburn  5775:         }
                   5776:     } else {
1.1088    raeburn  5777:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5778:         $setprivs = 1;
1.994     raeburn  5779:     }
1.1185    raeburn  5780:     return $setprivs;
1.994     raeburn  5781: }
                   5782: 
                   5783: sub set_adhoc_privileges {
                   5784: # role can be cc or ca
1.1088    raeburn  5785:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5786:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5787:     my $spec = $role.'.'.$area;
                   5788:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5789:                                   $env{'user.name'},1);
1.994     raeburn  5790:     my %ccrole = ();
                   5791:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5792:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5793:     &appenv(\%userroles,[$role,'cm']);
                   5794:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5795:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5796:         &appenv( {'request.role'        => $spec,
                   5797:                   'request.role.domain' => $dcdom,
                   5798:                   'request.course.sec'  => ''
                   5799:                  }
                   5800:                );
                   5801:         my $tadv=0;
                   5802:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5803:         &appenv({'request.role.adv'    => $tadv});
                   5804:     }
1.994     raeburn  5805: }
                   5806: 
1.12      www      5807: # --------------------------------------------------------------- get interface
                   5808: 
                   5809: sub get {
1.131     albertel 5810:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5811:    my $items='';
1.800     albertel 5812:    foreach my $item (@$storearr) {
                   5813:        $items.=&escape($item).'&';
1.191     harris41 5814:    }
1.12      www      5815:    $items=~s/\&$//;
1.620     albertel 5816:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5817:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5818:    my $uhome=&homeserver($uname,$udomain);
                   5819: 
1.133     albertel 5820:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5821:    my @pairs=split(/\&/,$rep);
1.273     albertel 5822:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5823:      return @pairs;
                   5824:    }
1.15      www      5825:    my %returnhash=();
1.42      www      5826:    my $i=0;
1.800     albertel 5827:    foreach my $item (@$storearr) {
                   5828:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5829:       $i++;
1.191     harris41 5830:    }
1.15      www      5831:    return %returnhash;
1.27      www      5832: }
                   5833: 
                   5834: # --------------------------------------------------------------- del interface
                   5835: 
                   5836: sub del {
1.133     albertel 5837:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5838:    my $items='';
1.800     albertel 5839:    foreach my $item (@$storearr) {
                   5840:        $items.=&escape($item).'&';
1.191     harris41 5841:    }
1.984     neumanie 5842: 
1.27      www      5843:    $items=~s/\&$//;
1.620     albertel 5844:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5845:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5846:    my $uhome=&homeserver($uname,$udomain);
                   5847:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5848: }
                   5849: 
                   5850: # -------------------------------------------------------------- dump interface
                   5851: 
1.1180    droeschl 5852: sub unserialize {
                   5853:     my ($rep, $escapedkeys) = @_;
                   5854: 
                   5855:     return {} if $rep =~ /^error/;
                   5856: 
                   5857:     my %returnhash=();
1.1252    raeburn  5858: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 5859: 	    my ($key, $value) = split(/=/, $item, 2);
                   5860: 	    $key = unescape($key) unless $escapedkeys;
                   5861: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  5862: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 5863: 	}
                   5864:     #return %returnhash;
                   5865:     return \%returnhash;
                   5866: }        
                   5867: 
                   5868: # see Lond::dump_with_regexp
                   5869: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5870: sub dump {
1.1180    droeschl 5871:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5872:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5873:     if (!$uname) { $uname=$env{'user.name'}; }
                   5874:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5875: 
1.1266    raeburn  5876:     if ($regexp) {
                   5877:         $regexp=&escape($regexp);
                   5878:     } else {
                   5879:         $regexp='.';
                   5880:     }
1.1180    droeschl 5881:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5882:         # user is hosted on this machine
1.1266    raeburn  5883:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5884:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5885:         return %{unserialize($reply, $escapedkeys)};
                   5886:     }
1.1166    raeburn  5887:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5888:     my @pairs=split(/\&/,$rep);
                   5889:     my %returnhash=();
1.1098    foxr     5890:     if (!($rep =~ /^error/ )) {
                   5891: 	foreach my $item (@pairs) {
                   5892: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5893:         $key = unescape($key) unless $escapedkeys;
                   5894:         #$key = &unescape($key);
1.1098    foxr     5895: 	    next if ($key =~ /^error: 2 /);
                   5896: 	    $returnhash{$key}=&thaw_unescape($value);
                   5897: 	}
1.755     albertel 5898:     }
                   5899:     return %returnhash;
1.407     www      5900: }
                   5901: 
1.1098    foxr     5902: 
1.717     albertel 5903: # --------------------------------------------------------- dumpstore interface
                   5904: 
                   5905: sub dumpstore {
                   5906:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5907:    # same as dump but keys must be escaped. They may contain colon separated
                   5908:    # lists of values that may themself contain colons (e.g. symbs).
                   5909:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5910: }
                   5911: 
1.407     www      5912: # -------------------------------------------------------------- keys interface
                   5913: 
                   5914: sub getkeys {
                   5915:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5916:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5917:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5918:    my $uhome=&homeserver($uname,$udomain);
                   5919:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5920:    my @keyarray=();
1.800     albertel 5921:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5922:       next if ($key =~ /^error: 2 /);
1.800     albertel 5923:       push(@keyarray,&unescape($key));
1.407     www      5924:    }
                   5925:    return @keyarray;
1.318     matthew  5926: }
                   5927: 
1.319     matthew  5928: # --------------------------------------------------------------- currentdump
                   5929: sub currentdump {
1.328     matthew  5930:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5931:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5932:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5933:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5934:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5935:    my $rep;
                   5936: 
                   5937:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5938:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5939:                    $courseid)));
                   5940:    } else {
                   5941:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5942:    }
                   5943: 
1.318     matthew  5944:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5945:    #
1.318     matthew  5946:    my %returnhash=();
1.319     matthew  5947:    #
                   5948:    if ($rep eq "unknown_cmd") { 
                   5949:        # an old lond will not know currentdump
                   5950:        # Do a dump and make it look like a currentdump
1.822     albertel 5951:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5952:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5953:        my %hash = @tmp;
                   5954:        @tmp=();
1.424     matthew  5955:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5956:    } else {
                   5957:        my @pairs=split(/\&/,$rep);
1.800     albertel 5958:        foreach my $pair (@pairs) {
                   5959:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5960:            my ($symb,$param) = split(/:/,$key);
                   5961:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5962:                                                         &thaw_unescape($value);
1.319     matthew  5963:        }
1.191     harris41 5964:    }
1.12      www      5965:    return %returnhash;
1.424     matthew  5966: }
                   5967: 
                   5968: sub convert_dump_to_currentdump{
                   5969:     my %hash = %{shift()};
                   5970:     my %returnhash;
                   5971:     # Code ripped from lond, essentially.  The only difference
                   5972:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5973:     # we might run in to problems with parameter names =~ /^v\./
                   5974:     while (my ($key,$value) = each(%hash)) {
                   5975:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5976: 	$symb  = &unescape($symb);
                   5977: 	$param = &unescape($param);
1.424     matthew  5978:         next if ($v eq 'version' || $symb eq 'keys');
                   5979:         next if (exists($returnhash{$symb}) &&
                   5980:                  exists($returnhash{$symb}->{$param}) &&
                   5981:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5982:         $returnhash{$symb}->{$param}=$value;
                   5983:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5984:     }
                   5985:     #
                   5986:     # Remove all of the keys in the hashes which keep track of
                   5987:     # the version of the parameter.
                   5988:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5989:         # use a foreach because we are going to delete from the hash.
                   5990:         foreach my $key (keys(%$param_hash)) {
                   5991:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5992:         }
                   5993:     }
                   5994:     return \%returnhash;
1.12      www      5995: }
                   5996: 
1.627     albertel 5997: # ------------------------------------------------------ critical inc interface
                   5998: 
                   5999: sub cinc {
                   6000:     return &inc(@_,'critical');
                   6001: }
                   6002: 
1.449     matthew  6003: # --------------------------------------------------------------- inc interface
                   6004: 
                   6005: sub inc {
1.627     albertel 6006:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6007:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6008:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6009:     my $uhome=&homeserver($uname,$udomain);
                   6010:     my $items='';
                   6011:     if (! ref($store)) {
                   6012:         # got a single value, so use that instead
                   6013:         $items = &escape($store).'=&';
                   6014:     } elsif (ref($store) eq 'SCALAR') {
                   6015:         $items = &escape($$store).'=&';        
                   6016:     } elsif (ref($store) eq 'ARRAY') {
                   6017:         $items = join('=&',map {&escape($_);} @{$store});
                   6018:     } elsif (ref($store) eq 'HASH') {
                   6019:         while (my($key,$value) = each(%{$store})) {
                   6020:             $items.= &escape($key).'='.&escape($value).'&';
                   6021:         }
                   6022:     }
                   6023:     $items=~s/\&$//;
1.627     albertel 6024:     if ($critical) {
                   6025: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6026:     } else {
                   6027: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6028:     }
1.449     matthew  6029: }
                   6030: 
1.12      www      6031: # --------------------------------------------------------------- put interface
                   6032: 
                   6033: sub put {
1.134     albertel 6034:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6035:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6036:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6037:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6038:    my $items='';
1.800     albertel 6039:    foreach my $item (keys(%$storehash)) {
                   6040:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6041:    }
1.12      www      6042:    $items=~s/\&$//;
1.134     albertel 6043:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6044: }
                   6045: 
1.631     albertel 6046: # ------------------------------------------------------------ newput interface
                   6047: 
                   6048: sub newput {
                   6049:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6050:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6051:    if (!$uname) { $uname=$env{'user.name'}; }
                   6052:    my $uhome=&homeserver($uname,$udomain);
                   6053:    my $items='';
                   6054:    foreach my $key (keys(%$storehash)) {
                   6055:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6056:    }
                   6057:    $items=~s/\&$//;
                   6058:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6059: }
                   6060: 
                   6061: # ---------------------------------------------------------  putstore interface
                   6062: 
1.524     raeburn  6063: sub putstore {
1.1269    raeburn  6064:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6065:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6066:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6067:    my $uhome=&homeserver($uname,$udomain);
                   6068:    my $items='';
1.715     albertel 6069:    foreach my $key (keys(%$storehash)) {
                   6070:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6071:    }
1.715     albertel 6072:    $items=~s/\&$//;
1.716     albertel 6073:    my $esc_symb=&escape($symb);
                   6074:    my $esc_v=&escape($version);
1.715     albertel 6075:    my $reply =
1.716     albertel 6076:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6077: 	      $uhome);
1.1269    raeburn  6078:    if (($tolog) && ($reply eq 'ok')) {
                   6079:        my $namevalue='';
                   6080:        foreach my $key (keys(%{$storehash})) {
                   6081:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6082:        }
                   6083:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6084:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6085:                      '&version='.$esc_v.
                   6086:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6087:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6088:    }
1.715     albertel 6089:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6090:        # gfall back to way things use to be done
1.715     albertel 6091:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6092: 			    $uname);
1.524     raeburn  6093:    }
1.715     albertel 6094:    return $reply;
                   6095: }
                   6096: 
                   6097: sub old_putstore {
1.716     albertel 6098:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6099:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6100:     if (!$uname) { $uname=$env{'user.name'}; }
                   6101:     my $uhome=&homeserver($uname,$udomain);
                   6102:     my %newstorehash;
1.800     albertel 6103:     foreach my $item (keys(%$storehash)) {
                   6104: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6105: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6106:     }
                   6107:     my $items='';
                   6108:     my %allitems = ();
1.800     albertel 6109:     foreach my $item (keys(%newstorehash)) {
                   6110: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6111: 	    my $key = $1.':keys:'.$2;
                   6112: 	    $allitems{$key} .= $3.':';
                   6113: 	}
1.800     albertel 6114: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6115:     }
1.800     albertel 6116:     foreach my $item (keys(%allitems)) {
                   6117: 	$allitems{$item} =~ s/\:$//;
                   6118: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6119:     }
                   6120:     $items=~s/\&$//;
                   6121:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6122: }
                   6123: 
1.47      www      6124: # ------------------------------------------------------ critical put interface
                   6125: 
                   6126: sub cput {
1.134     albertel 6127:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6128:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6129:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6130:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6131:    my $items='';
1.800     albertel 6132:    foreach my $item (keys(%$storehash)) {
                   6133:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6134:    }
1.47      www      6135:    $items=~s/\&$//;
1.134     albertel 6136:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6137: }
                   6138: 
                   6139: # -------------------------------------------------------------- eget interface
                   6140: 
                   6141: sub eget {
1.133     albertel 6142:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6143:    my $items='';
1.800     albertel 6144:    foreach my $item (@$storearr) {
                   6145:        $items.=&escape($item).'&';
1.191     harris41 6146:    }
1.12      www      6147:    $items=~s/\&$//;
1.620     albertel 6148:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6149:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6150:    my $uhome=&homeserver($uname,$udomain);
                   6151:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6152:    my @pairs=split(/\&/,$rep);
                   6153:    my %returnhash=();
1.42      www      6154:    my $i=0;
1.800     albertel 6155:    foreach my $item (@$storearr) {
                   6156:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6157:       $i++;
1.191     harris41 6158:    }
1.12      www      6159:    return %returnhash;
                   6160: }
                   6161: 
1.667     albertel 6162: # ------------------------------------------------------------ tmpput interface
                   6163: sub tmpput {
1.802     raeburn  6164:     my ($storehash,$server,$context)=@_;
1.667     albertel 6165:     my $items='';
1.800     albertel 6166:     foreach my $item (keys(%$storehash)) {
                   6167: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6168:     }
                   6169:     $items=~s/\&$//;
1.802     raeburn  6170:     if (defined($context)) {
                   6171:         $items .= ':'.&escape($context);
                   6172:     }
1.667     albertel 6173:     return &reply("tmpput:$items",$server);
                   6174: }
                   6175: 
                   6176: # ------------------------------------------------------------ tmpget interface
                   6177: sub tmpget {
1.688     albertel 6178:     my ($token,$server)=@_;
                   6179:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6180:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6181:     my %returnhash;
                   6182:     foreach my $item (split(/\&/,$rep)) {
                   6183: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6184:         next if ($key =~ /^error: 2 /);
1.667     albertel 6185: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6186:     }
                   6187:     return %returnhash;
                   6188: }
                   6189: 
1.1113    raeburn  6190: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6191: sub tmpdel {
                   6192:     my ($token,$server)=@_;
                   6193:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6194:     return &reply("tmpdel:$token",$server);
                   6195: }
                   6196: 
1.1198    raeburn  6197: # ------------------------------------------------------------ get_timebased_id 
                   6198: 
                   6199: sub get_timebased_id {
                   6200:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6201:         $maxtries) = @_;
                   6202:     my ($newid,$error,$dellock);
                   6203:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6204:         return ('','ok','invalid call to get suffix');
                   6205:     }
                   6206: 
                   6207: # set defaults for any optional args for which values were not supplied
                   6208:     if ($who eq '') {
                   6209:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6210:     }
                   6211:     if (!$locktries) {
                   6212:         $locktries = 3;
                   6213:     }
                   6214:     if (!$maxtries) {
                   6215:         $maxtries = 10;
                   6216:     }
                   6217:     
                   6218:     if (($cdom eq '') || ($cnum eq '')) {
                   6219:         if ($env{'request.course.id'}) {
                   6220:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6221:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6222:         }
                   6223:         if (($cdom eq '') || ($cnum eq '')) {
                   6224:             return ('','ok','call to get suffix not in course context');
                   6225:         }
                   6226:     }
                   6227: 
                   6228: # construct locking item
                   6229:     my $lockhash = {
                   6230:                       $prefix."\0".'locked_'.$keyid => $who,
                   6231:                    };
                   6232:     my $tries = 0;
                   6233: 
                   6234: # attempt to get lock on nohist_$namespace file
                   6235:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6236:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6237:         $tries ++;
                   6238:         sleep 1;
                   6239:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6240:     }
                   6241: 
                   6242: # attempt to get unique identifier, based on current timestamp
                   6243:     if ($gotlock eq 'ok') {
                   6244:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6245:         my $id = time;
                   6246:         $newid = $id;
1.1268    raeburn  6247:         if ($idtype eq 'addcode') {
                   6248:             $newid .= &sixnum_code();
                   6249:         }
1.1198    raeburn  6250:         my $idtries = 0;
                   6251:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6252:             if ($idtype eq 'concat') {
                   6253:                 $newid = $id.$idtries;
1.1268    raeburn  6254:             } elsif ($idtype eq 'addcode') {
                   6255:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6256:             } else {
                   6257:                 $newid ++;
                   6258:             }
                   6259:             $idtries ++;
                   6260:         }
                   6261:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6262:             my %new_item =  (
                   6263:                               $prefix."\0".$newid => $who,
                   6264:                             );
                   6265:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6266:                                                  $cdom,$cnum);
                   6267:             if ($putresult ne 'ok') {
                   6268:                 undef($newid);
                   6269:                 $error = 'error saving new item: '.$putresult;
                   6270:             }
                   6271:         } else {
1.1268    raeburn  6272:              undef($newid);
1.1198    raeburn  6273:              $error = ('error: no unique suffix available for the new item ');
                   6274:         }
                   6275: #  remove lock
                   6276:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6277:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6278:     } else {
                   6279:         $error = "error: could not obtain lockfile\n";
                   6280:         $dellock = 'ok';
1.1276    raeburn  6281:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6282:             $dellock = 'nolock';
                   6283:         }
1.1198    raeburn  6284:     }
                   6285:     return ($newid,$dellock,$error);
                   6286: }
                   6287: 
1.1268    raeburn  6288: sub sixnum_code {
                   6289:     my $code;
                   6290:     for (0..6) {
                   6291:         $code .= int( rand(9) );
                   6292:     }
                   6293:     return $code;
                   6294: }
                   6295: 
1.765     albertel 6296: # -------------------------------------------------- portfolio access checking
                   6297: 
                   6298: sub portfolio_access {
1.1270    raeburn  6299:     my ($requrl,$clientip) = @_;
1.765     albertel 6300:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6301:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6302:     if ($result) {
                   6303:         my %setters;
                   6304:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6305:             my ($startblock,$endblock) =
                   6306:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6307:             if ($startblock && $endblock) {
                   6308:                 return 'B';
                   6309:             }
                   6310:         } else {
                   6311:             my ($startblock,$endblock) =
                   6312:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6313:             if ($startblock && $endblock) {
                   6314:                 return 'B';
                   6315:             }
                   6316:         }
                   6317:     }
1.765     albertel 6318:     if ($result eq 'ok') {
1.766     albertel 6319:        return 'F';
1.765     albertel 6320:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6321:        return 'A';
1.765     albertel 6322:     }
1.766     albertel 6323:     return '';
1.765     albertel 6324: }
                   6325: 
                   6326: sub get_portfolio_access {
1.1270    raeburn  6327:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6328: 
                   6329:     if (!ref($access_hash)) {
                   6330: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6331: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6332: 						   $file_name);
                   6333: 	$access_hash = $access_controls{$file_name};
                   6334:     }
                   6335: 
1.1270    raeburn  6336:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6337:     my $now = time;
                   6338:     if (ref($access_hash) eq 'HASH') {
                   6339:         foreach my $key (keys(%{$access_hash})) {
                   6340:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6341:             if ($start > $now) {
                   6342:                 next;
                   6343:             }
                   6344:             if ($end && $end<$now) {
                   6345:                 next;
                   6346:             }
                   6347:             if ($scope eq 'public') {
                   6348:                 $public = $key;
                   6349:                 last;
                   6350:             } elsif ($scope eq 'guest') {
                   6351:                 $guest = $key;
                   6352:             } elsif ($scope eq 'domains') {
                   6353:                 push(@domains,$key);
                   6354:             } elsif ($scope eq 'users') {
                   6355:                 push(@users,$key);
                   6356:             } elsif ($scope eq 'course') {
                   6357:                 push(@courses,$key);
                   6358:             } elsif ($scope eq 'group') {
                   6359:                 push(@groups,$key);
1.1270    raeburn  6360:             } elsif ($scope eq 'ip') {
                   6361:                 push(@ips,$key);
1.765     albertel 6362:             }
                   6363:         }
                   6364:         if ($public) {
                   6365:             return 'ok';
1.1270    raeburn  6366:         } elsif (@ips > 0) {
                   6367:             my $allowed;
                   6368:             foreach my $ipkey (@ips) {
                   6369:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6370:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6371:                         $allowed = 1;
                   6372:                         last; 
                   6373:                     }
                   6374:                 }
                   6375:             }
                   6376:             if ($allowed) {
                   6377:                 return 'ok';
                   6378:             }
1.765     albertel 6379:         }
                   6380:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6381:             if ($guest) {
                   6382:                 return $guest;
                   6383:             }
                   6384:         } else {
                   6385:             if (@domains > 0) {
                   6386:                 foreach my $domkey (@domains) {
                   6387:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6388:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6389:                             return 'ok';
                   6390:                         }
                   6391:                     }
                   6392:                 }
                   6393:             }
                   6394:             if (@users > 0) {
                   6395:                 foreach my $userkey (@users) {
1.865     raeburn  6396:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6397:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6398:                             if (ref($item) eq 'HASH') {
                   6399:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6400:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6401:                                     return 'ok';
                   6402:                                 }
                   6403:                             }
                   6404:                         }
                   6405:                     } 
1.765     albertel 6406:                 }
                   6407:             }
                   6408:             my %roleshash;
                   6409:             my @courses_and_groups = @courses;
                   6410:             push(@courses_and_groups,@groups); 
                   6411:             if (@courses_and_groups > 0) {
                   6412:                 my (%allgroups,%allroles); 
                   6413:                 my ($start,$end,$role,$sec,$group);
                   6414:                 foreach my $envkey (%env) {
1.1060    raeburn  6415:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6416:                         my $cid = $2.'_'.$3; 
                   6417:                         if ($1 eq 'gr') {
                   6418:                             $group = $4;
                   6419:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6420:                         } else {
                   6421:                             if ($4 eq '') {
                   6422:                                 $sec = 'none';
                   6423:                             } else {
                   6424:                                 $sec = $4;
                   6425:                             }
                   6426:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6427:                         }
1.811     albertel 6428:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6429:                         my $cid = $2.'_'.$3;
                   6430:                         if ($4 eq '') {
                   6431:                             $sec = 'none';
                   6432:                         } else {
                   6433:                             $sec = $4;
                   6434:                         }
                   6435:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6436:                     }
                   6437:                 }
                   6438:                 if (keys(%allroles) == 0) {
                   6439:                     return;
                   6440:                 }
                   6441:                 foreach my $key (@courses_and_groups) {
                   6442:                     my %content = %{$$access_hash{$key}};
                   6443:                     my $cnum = $content{'number'};
                   6444:                     my $cdom = $content{'domain'};
                   6445:                     my $cid = $cdom.'_'.$cnum;
                   6446:                     if (!exists($allroles{$cid})) {
                   6447:                         next;
                   6448:                     }    
                   6449:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6450:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6451:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6452:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6453:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6454:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6455:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6456:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6457:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6458:                                         if (grep/^all$/,@sections) {
                   6459:                                             return 'ok';
                   6460:                                         } else {
                   6461:                                             if (grep/^$sec$/,@sections) {
                   6462:                                                 return 'ok';
                   6463:                                             }
                   6464:                                         }
                   6465:                                     }
                   6466:                                 }
                   6467:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6468:                                     if (grep/^none$/,@groups) {
                   6469:                                         return 'ok';
                   6470:                                     }
                   6471:                                 } else {
                   6472:                                     if (grep/^all$/,@groups) {
                   6473:                                         return 'ok';
                   6474:                                     } 
                   6475:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6476:                                         if (grep/^$group$/,@groups) {
                   6477:                                             return 'ok';
                   6478:                                         }
                   6479:                                     }
                   6480:                                 } 
                   6481:                             }
                   6482:                         }
                   6483:                     }
                   6484:                 }
                   6485:             }
                   6486:             if ($guest) {
                   6487:                 return $guest;
                   6488:             }
                   6489:         }
                   6490:     }
                   6491:     return;
                   6492: }
                   6493: 
                   6494: sub course_group_datechecker {
                   6495:     my ($dates,$now,$status) = @_;
                   6496:     my ($start,$end) = split(/\./,$dates);
                   6497:     if (!$start && !$end) {
                   6498:         return 'ok';
                   6499:     }
                   6500:     if (grep/^active$/,@{$status}) {
                   6501:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6502:             return 'ok';
                   6503:         }
                   6504:     }
                   6505:     if (grep/^previous$/,@{$status}) {
                   6506:         if ($end > $now ) {
                   6507:             return 'ok';
                   6508:         }
                   6509:     }
                   6510:     if (grep/^future$/,@{$status}) {
                   6511:         if ($start > $now) {
                   6512:             return 'ok';
                   6513:         }
                   6514:     }
                   6515:     return; 
                   6516: }
                   6517: 
                   6518: sub parse_portfolio_url {
                   6519:     my ($url) = @_;
                   6520: 
                   6521:     my ($type,$udom,$unum,$group,$file_name);
                   6522:     
1.823     albertel 6523:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6524: 	$type = 1;
                   6525:         $udom = $1;
                   6526:         $unum = $2;
                   6527:         $file_name = $3;
1.823     albertel 6528:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6529: 	$type = 2;
                   6530:         $udom = $1;
                   6531:         $unum = $2;
                   6532:         $group = $3;
                   6533:         $file_name = $3.'/'.$4;
                   6534:     }
                   6535:     if (wantarray) {
                   6536: 	return ($type,$udom,$unum,$file_name,$group);
                   6537:     }
                   6538:     return $type;
                   6539: }
                   6540: 
                   6541: sub is_portfolio_url {
                   6542:     my ($url) = @_;
                   6543:     return scalar(&parse_portfolio_url($url));
                   6544: }
                   6545: 
1.798     raeburn  6546: sub is_portfolio_file {
                   6547:     my ($file) = @_;
1.820     raeburn  6548:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6549:         return 1;
                   6550:     }
                   6551:     return;
                   6552: }
                   6553: 
1.976     raeburn  6554: sub usertools_access {
1.1084    raeburn  6555:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6556:     my ($access,%tools);
                   6557:     if ($context eq '') {
                   6558:         $context = 'tools';
                   6559:     }
                   6560:     if ($context eq 'requestcourses') {
                   6561:         %tools = (
                   6562:                       official   => 1,
                   6563:                       unofficial => 1,
1.1006    raeburn  6564:                       community  => 1,
1.1246    raeburn  6565:                       textbook   => 1,
1.1305    raeburn  6566:                       placement  => 1,
1.985     raeburn  6567:                  );
1.1183    raeburn  6568:     } elsif ($context eq 'requestauthor') {
                   6569:         %tools = (
                   6570:                       requestauthor => 1,
                   6571:                  );
1.985     raeburn  6572:     } else {
                   6573:         %tools = (
                   6574:                       aboutme   => 1,
                   6575:                       blog      => 1,
1.1177    raeburn  6576:                       webdav    => 1,
1.985     raeburn  6577:                       portfolio => 1,
                   6578:                  );
                   6579:     }
1.976     raeburn  6580:     return if (!defined($tools{$tool}));
                   6581: 
1.1242    raeburn  6582:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6583:         $udom = $env{'user.domain'};
                   6584:         $uname = $env{'user.name'};
                   6585:     }
                   6586: 
1.978     raeburn  6587:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6588:         if ($action ne 'reload') {
1.985     raeburn  6589:             if ($context eq 'requestcourses') {
                   6590:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6591:             } elsif ($context eq 'requestauthor') {
                   6592:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6593:             } else {
                   6594:                 return $env{'environment.availabletools.'.$tool};
                   6595:             }
                   6596:         }
1.976     raeburn  6597:     }
                   6598: 
1.1183    raeburn  6599:     my ($toolstatus,$inststatus,$envkey);
                   6600:     if ($context eq 'requestauthor') {
                   6601:         $envkey = $context; 
                   6602:     } else {
                   6603:         $envkey = $context.'.'.$tool;
                   6604:     }
1.976     raeburn  6605: 
1.985     raeburn  6606:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6607:          ($action ne 'reload')) {
1.1183    raeburn  6608:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6609:         $inststatus = $env{'environment.inststatus'};
                   6610:     } else {
1.1084    raeburn  6611:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6612:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6613:             $inststatus = $userenvref->{'inststatus'};
                   6614:         } else {
1.1183    raeburn  6615:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6616:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6617:             $inststatus = $userenv{'inststatus'};
                   6618:         }
1.976     raeburn  6619:     }
                   6620: 
                   6621:     if ($toolstatus ne '') {
                   6622:         if ($toolstatus) {
                   6623:             $access = 1;
                   6624:         } else {
                   6625:             $access = 0;
                   6626:         }
                   6627:         return $access;
                   6628:     }
                   6629: 
1.1084    raeburn  6630:     my ($is_adv,%domdef);
                   6631:     if (ref($is_advref) eq 'HASH') {
                   6632:         $is_adv = $is_advref->{'is_adv'};
                   6633:     } else {
                   6634:         $is_adv = &is_advanced_user($udom,$uname);
                   6635:     }
                   6636:     if (ref($domdefref) eq 'HASH') {
                   6637:         %domdef = %{$domdefref};
                   6638:     } else {
                   6639:         %domdef = &get_domain_defaults($udom);
                   6640:     }
1.976     raeburn  6641:     if (ref($domdef{$tool}) eq 'HASH') {
                   6642:         if ($is_adv) {
                   6643:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6644:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6645:                     $access = 1;
                   6646:                 } else {
                   6647:                     $access = 0;
                   6648:                 }
                   6649:                 return $access;
                   6650:             }
                   6651:         }
                   6652:         if ($inststatus ne '') {
                   6653:             my ($hasaccess,$hasnoaccess);
                   6654:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6655:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6656:                     if ($domdef{$tool}{$affiliation}) {
                   6657:                         $hasaccess = 1;
                   6658:                     } else {
                   6659:                         $hasnoaccess = 1;
                   6660:                     }
                   6661:                 }
                   6662:             }
                   6663:             if ($hasaccess || $hasnoaccess) {
                   6664:                 if ($hasaccess) {
                   6665:                     $access = 1;
                   6666:                 } elsif ($hasnoaccess) {
                   6667:                     $access = 0; 
                   6668:                 }
                   6669:                 return $access;
                   6670:             }
                   6671:         } else {
                   6672:             if ($domdef{$tool}{'default'} ne '') {
                   6673:                 if ($domdef{$tool}{'default'}) {
                   6674:                     $access = 1;
                   6675:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6676:                     $access = 0;
                   6677:                 }
                   6678:                 return $access;
                   6679:             }
                   6680:         }
                   6681:     } else {
1.1177    raeburn  6682:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6683:             $access = 1;
                   6684:         } else {
                   6685:             $access = 0;
                   6686:         }
1.976     raeburn  6687:         return $access;
                   6688:     }
                   6689: }
                   6690: 
1.1050    raeburn  6691: sub is_course_owner {
                   6692:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6693:     if (($udom eq '') || ($uname eq '')) {
                   6694:         $udom = $env{'user.domain'};
                   6695:         $uname = $env{'user.name'};
                   6696:     }
                   6697:     unless (($udom eq '') || ($uname eq '')) {
                   6698:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6699:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6700:                 return 1;
                   6701:             } else {
                   6702:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6703:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6704:                     return 1;
                   6705:                 }
                   6706:             }
                   6707:         }
                   6708:     }
                   6709:     return;
                   6710: }
                   6711: 
1.976     raeburn  6712: sub is_advanced_user {
                   6713:     my ($udom,$uname) = @_;
1.1085    raeburn  6714:     if ($udom ne '' && $uname ne '') {
                   6715:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6716:             if (wantarray) {
                   6717:                 return ($env{'user.adv'},$env{'user.author'});
                   6718:             } else {
                   6719:                 return $env{'user.adv'};
                   6720:             }
1.1085    raeburn  6721:         }
                   6722:     }
1.976     raeburn  6723:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6724:     my %allroles;
1.1128    raeburn  6725:     my ($is_adv,$is_author);
1.976     raeburn  6726:     foreach my $role (keys(%roleshash)) {
                   6727:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6728:         my $area = '/'.$tdomain.'/'.$trest;
                   6729:         if ($sec ne '') {
                   6730:             $area .= '/'.$sec;
                   6731:         }
                   6732:         if (($area ne '') && ($trole ne '')) {
                   6733:             my $spec=$trole.'.'.$area;
                   6734:             if ($trole =~ /^cr\//) {
                   6735:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6736:             } elsif ($trole ne 'gr') {
                   6737:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6738:             }
1.1128    raeburn  6739:             if ($trole eq 'au') {
                   6740:                 $is_author = 1;
                   6741:             }
1.976     raeburn  6742:         }
                   6743:     }
                   6744:     foreach my $role (keys(%allroles)) {
                   6745:         last if ($is_adv);
                   6746:         foreach my $item (split(/:/,$allroles{$role})) {
                   6747:             if ($item ne '') {
                   6748:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6749:                 if ($privilege eq 'adv') {
                   6750:                     $is_adv = 1;
                   6751:                     last;
                   6752:                 }
                   6753:             }
                   6754:         }
                   6755:     }
1.1128    raeburn  6756:     if (wantarray) {
                   6757:         return ($is_adv,$is_author);
                   6758:     }
1.976     raeburn  6759:     return $is_adv;
                   6760: }
1.798     raeburn  6761: 
1.1035    raeburn  6762: sub check_can_request {
1.1036    raeburn  6763:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6764:     my $canreq = 0;
                   6765:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6766:     my @options = ('approval','validate','autolimit');
                   6767:     my $optregex = join('|',@options);
                   6768:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6769:         foreach my $type (@{$types}) {
                   6770:             if (&usertools_access($env{'user.name'},
                   6771:                                   $env{'user.domain'},
                   6772:                                   $type,undef,'requestcourses')) {
                   6773:                 $canreq ++;
1.1036    raeburn  6774:                 if (ref($request_domains) eq 'HASH') {
                   6775:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6776:                 }
1.1035    raeburn  6777:                 if ($dom eq $env{'user.domain'}) {
                   6778:                     $can_request->{$type} = 1;
                   6779:                 }
                   6780:             }
                   6781:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6782:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6783:                 if (@curr > 0) {
1.1036    raeburn  6784:                     foreach my $item (@curr) {
                   6785:                         if (ref($request_domains) eq 'HASH') {
                   6786:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6787:                             if ($otherdom ne '') {
                   6788:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6789:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6790:                                         push(@{$request_domains->{$type}},$otherdom);
                   6791:                                     }
                   6792:                                 } else {
                   6793:                                     push(@{$request_domains->{$type}},$otherdom);
                   6794:                                 }
                   6795:                             }
                   6796:                         }
                   6797:                     }
                   6798:                     unless($dom eq $env{'user.domain'}) {
                   6799:                         $canreq ++;
1.1035    raeburn  6800:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6801:                             $can_request->{$type} = 1;
                   6802:                         }
                   6803:                     }
                   6804:                 }
                   6805:             }
                   6806:         }
                   6807:     }
                   6808:     return $canreq;
                   6809: }
                   6810: 
1.341     www      6811: # ---------------------------------------------- Custom access rule evaluation
                   6812: 
                   6813: sub customaccess {
                   6814:     my ($priv,$uri)=@_;
1.807     albertel 6815:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6816:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6817:     $udom = &LONCAPA::clean_domain($udom);
                   6818:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6819:     my $access=0;
1.800     albertel 6820:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6821: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6822: 	if ($type eq 'user') {
                   6823: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6824: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6825: 		if ($tdom) {
                   6826: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6827: 		}
1.896     albertel 6828: 		if ($tuname) {
                   6829: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6830: 		}
                   6831: 		$access=($effect eq 'allow');
                   6832: 		last;
                   6833: 	    }
                   6834: 	} else {
                   6835: 	    if ($role) {
                   6836: 		if ($role ne $urole) { next; }
                   6837: 	    }
                   6838: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6839: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6840: 		if ($tdom) {
                   6841: 		    if ($tdom ne $udom) { next; }
                   6842: 		}
                   6843: 		if ($tcrs) {
                   6844: 		    if ($tcrs ne $ucrs) { next; }
                   6845: 		}
                   6846: 		if ($tsec) {
                   6847: 		    if ($tsec ne $usec) { next; }
                   6848: 		}
                   6849: 		$access=($effect eq 'allow');
                   6850: 		last;
                   6851: 	    }
                   6852: 	    if ($realm eq '' && $role eq '') {
                   6853: 		$access=($effect eq 'allow');
                   6854: 	    }
1.402     bowersj2 6855: 	}
1.341     www      6856:     }
                   6857:     return $access;
                   6858: }
                   6859: 
1.103     harris41 6860: # ------------------------------------------------- Check for a user privilege
1.12      www      6861: 
                   6862: sub allowed {
1.1281    raeburn  6863:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 6864:     my $ver_orguri=$uri;
1.439     www      6865:     $uri=&deversion($uri);
1.152     www      6866:     my $orguri=$uri;
1.52      www      6867:     $uri=&declutter($uri);
1.809     raeburn  6868: 
1.810     raeburn  6869:     if ($priv eq 'evb') {
                   6870: # Evade communication block restrictions for specified role in a course
                   6871:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6872:             return $1;
                   6873:         } else {
                   6874:             return;
                   6875:         }
                   6876:     }
                   6877: 
1.620     albertel 6878:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6879: # Free bre access to adm and meta resources
1.775     albertel 6880:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6881: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6882: 	&& ($priv eq 'bre')) {
1.14      www      6883: 	return 'F';
1.159     www      6884:     }
                   6885: 
1.545     banghart 6886: # Free bre access to user's own portfolio contents
1.714     raeburn  6887:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6888:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6889: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6890:         my %setters;
                   6891:         my ($startblock,$endblock) = 
                   6892:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6893:         if ($startblock && $endblock) {
                   6894:             return 'B';
                   6895:         } else {
                   6896:             return 'F';
                   6897:         }
1.545     banghart 6898:     }
                   6899: 
1.762     raeburn  6900: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6901:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6902:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6903:         if (exists($env{'request.course.id'})) {
                   6904:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6905:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6906:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6907:                 my $courseprivid=$env{'request.course.id'};
                   6908:                 $courseprivid=~s/\_/\//;
                   6909:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6910:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6911:                     return $1; 
1.762     raeburn  6912:                 } else {
                   6913:                     if ($env{'request.course.sec'}) {
                   6914:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6915:                     }
                   6916:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6917:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6918:                         return $2;
                   6919:                     }
1.714     raeburn  6920:                 }
                   6921:             }
                   6922:         }
                   6923:     }
                   6924: 
1.159     www      6925: # Free bre to public access
                   6926: 
                   6927:     if ($priv eq 'bre') {
1.238     www      6928:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6929: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6930:            return 'F'; 
                   6931:         }
1.238     www      6932:         if ($copyright eq 'priv') {
                   6933:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6934: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6935: 		return '';
                   6936:             }
                   6937:         }
                   6938:         if ($copyright eq 'domain') {
                   6939:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6940: 	    unless (($env{'user.domain'} eq $1) ||
                   6941:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6942: 		return '';
                   6943:             }
1.262     matthew  6944:         }
1.620     albertel 6945:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6946:             # Library role, so allow browsing of resources in this domain.
                   6947:             return 'F';
1.238     www      6948:         }
1.341     www      6949:         if ($copyright eq 'custom') {
                   6950: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6951:         }
1.14      www      6952:     }
1.264     matthew  6953:     # Domain coordinator is trying to create a course
1.620     albertel 6954:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6955:         # uri is the requested domain in this case.
                   6956:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6957:         # a role of dc for the domain in question.
1.620     albertel 6958:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6959:     }
1.29      www      6960: 
1.52      www      6961:     my $thisallowed='';
                   6962:     my $statecond=0;
                   6963:     my $courseprivid='';
                   6964: 
1.1039    raeburn  6965:     my $ownaccess;
1.1043    raeburn  6966:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6967:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6968:         if ($uri eq '') {
                   6969:             $ownaccess = 1;
                   6970:         } else {
                   6971:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6972:                 my $udom = $env{'user.domain'};
                   6973:                 my $uname = $env{'user.name'};
                   6974:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6975:                     $ownaccess = 1;
1.1040    raeburn  6976:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6977:                     unless ($uri =~ m{\.\./}) {
                   6978:                         $ownaccess = 1;
                   6979:                     }
                   6980:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6981:                     my $now = time;
                   6982:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6983:                         my $adom = $1;
                   6984:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6985:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6986:                                 my ($start,$end) = split('.',$env{$key});
                   6987:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6988:                                     $ownaccess = 1;
                   6989:                                     last;
                   6990:                                 }
                   6991:                             }
                   6992:                         }
                   6993:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6994:                         my $adom = $1;
                   6995:                         my $aname = $2;
1.1042    raeburn  6996:                         foreach my $role ('ca','aa') { 
                   6997:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6998:                                 my ($start,$end) =
                   6999:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7000:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7001:                                     $ownaccess = 1;
                   7002:                                     last;
                   7003:                                 }
1.1039    raeburn  7004:                             }
                   7005:                         }
                   7006:                     }
                   7007:                 }
                   7008:             }
                   7009:         }
                   7010:     }
                   7011: 
1.52      www      7012: # Course
                   7013: 
1.620     albertel 7014:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7015:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7016:             $thisallowed.=$1;
                   7017:         }
1.52      www      7018:     }
1.29      www      7019: 
1.52      www      7020: # Domain
                   7021: 
1.620     albertel 7022:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7023:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7024:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7025:             $thisallowed.=$1;
                   7026:         }
1.12      www      7027:     }
1.52      www      7028: 
1.1141    raeburn  7029: # User who is not author or co-author might still be able to edit
                   7030: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7031:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7032:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7033:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7034:             $thisallowed.=$1;
                   7035:         }
                   7036:     }
                   7037: 
1.52      www      7038: # Course: uri itself is a course
1.66      www      7039:     my $courseuri=$uri;
                   7040:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7041:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7042: 
1.620     albertel 7043:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7044:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7045:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7046:             $thisallowed.=$1;
                   7047:         }
1.12      www      7048:     }
1.29      www      7049: 
1.665     albertel 7050: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7051: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7052:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7053: 	$thisallowed='';
1.671     raeburn  7054:         my ($match)=&is_on_map($uri);
                   7055:         if ($match) {
                   7056:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7057:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7058:                 my $value = $1;
                   7059:                 if ($noblockcheck) {
                   7060:                     $thisallowed.=$value;
1.1162    raeburn  7061:                 } else {
1.1281    raeburn  7062:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7063:                     if (@blockers > 0) {
                   7064:                         $thisallowed = 'B';
                   7065:                     } else {
                   7066:                         $thisallowed.=$value;
                   7067:                     }
1.1162    raeburn  7068:                 }
1.671     raeburn  7069:             }
                   7070:         } else {
1.705     albertel 7071:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7072:             if ($refuri) {
                   7073:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7074:                     $thisallowed='F';
1.671     raeburn  7075:                 } else {
                   7076:                     $refuri=&declutter($refuri);
                   7077:                     my ($match) = &is_on_map($refuri);
                   7078:                     if ($match) {
1.1281    raeburn  7079:                         if ($noblockcheck) {
                   7080:                             $thisallowed='F';
1.1162    raeburn  7081:                         } else {
1.1281    raeburn  7082:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7083:                             if (@blockers > 0) {
                   7084:                                 $thisallowed = 'B';
                   7085:                             } else {
                   7086:                                 $thisallowed='F';
                   7087:                             }
1.1162    raeburn  7088:                         }
1.671     raeburn  7089:                     }
1.669     raeburn  7090:                 }
1.671     raeburn  7091:             }
                   7092:         }
1.314     www      7093:     }
1.492     albertel 7094: 
1.766     albertel 7095:     if ($priv eq 'bre'
                   7096: 	&& $thisallowed ne 'F' 
                   7097: 	&& $thisallowed ne '2'
                   7098: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7099: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7100:     }
1.1250    raeburn  7101: 
1.52      www      7102: # Full access at system, domain or course-wide level? Exit.
1.29      www      7103:     if ($thisallowed=~/F/) {
                   7104: 	return 'F';
                   7105:     }
                   7106: 
1.52      www      7107: # If this is generating or modifying users, exit with special codes
1.29      www      7108: 
1.643     www      7109:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7110: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7111: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7112: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7113: 	    unless ($auname) { return $thisallowed; }
                   7114: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7115: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7116: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7117: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7118: 	}
1.52      www      7119: 	return $thisallowed;
                   7120:     }
                   7121: #
1.103     harris41 7122: # Gathered so far: system, domain and course wide privileges
1.52      www      7123: #
                   7124: # Course: See if uri or referer is an individual resource that is part of 
                   7125: # the course
                   7126: 
1.620     albertel 7127:     if ($env{'request.course.id'}) {
1.232     www      7128: 
1.620     albertel 7129:        $courseprivid=$env{'request.course.id'};
                   7130:        if ($env{'request.course.sec'}) {
                   7131:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7132:        }
                   7133:        $courseprivid=~s/\_/\//;
                   7134:        my $checkreferer=1;
1.232     www      7135:        my ($match,$cond)=&is_on_map($uri);
                   7136:        if ($match) {
                   7137:            $statecond=$cond;
1.620     albertel 7138:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7139:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7140:                my $value = $1;
                   7141:                if ($priv eq 'bre') {
1.1281    raeburn  7142:                    if ($noblockcheck) {
                   7143:                        $thisallowed.=$value;
1.1162    raeburn  7144:                    } else {
1.1281    raeburn  7145:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7146:                        if (@blockers > 0) {
                   7147:                            $thisallowed = 'B';
                   7148:                        } else {
                   7149:                            $thisallowed.=$value;
                   7150:                        }
1.1162    raeburn  7151:                    }
                   7152:                } else {
                   7153:                    $thisallowed.=$value;
                   7154:                }
1.52      www      7155:                $checkreferer=0;
                   7156:            }
1.29      www      7157:        }
1.83      www      7158:        
1.148     www      7159:        if ($checkreferer) {
1.620     albertel 7160: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7161:             unless ($refuri) {
1.800     albertel 7162:                 foreach my $key (keys(%env)) {
                   7163: 		    if ($key=~/^httpref\..*\*/) {
                   7164: 			my $pattern=$key;
1.156     www      7165:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7166:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7167:                         $pattern=~s/\//\\\//g;
1.152     www      7168:                         if ($orguri=~/$pattern/) {
1.800     albertel 7169: 			    $refuri=$env{$key};
1.148     www      7170:                         }
                   7171:                     }
1.191     harris41 7172:                 }
1.148     www      7173:             }
1.232     www      7174: 
1.148     www      7175:          if ($refuri) { 
1.152     www      7176: 	  $refuri=&declutter($refuri);
1.232     www      7177:           my ($match,$cond)=&is_on_map($refuri);
                   7178:             if ($match) {
                   7179:               my $refstatecond=$cond;
1.620     albertel 7180:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7181:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7182:                   my $value = $1;
                   7183:                   if ($priv eq 'bre') {
1.1281    raeburn  7184:                       if ($noblockcheck) {
                   7185:                           $thisallowed.=$value;
1.1162    raeburn  7186:                       } else {
1.1281    raeburn  7187:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7188:                           if (@blockers > 0) {
                   7189:                               $thisallowed = 'B';
                   7190:                           } else {
                   7191:                               $thisallowed.=$value;
                   7192:                           }
1.1162    raeburn  7193:                       }
                   7194:                   } else {
                   7195:                       $thisallowed.=$value;
                   7196:                   }
1.53      www      7197:                   $uri=$refuri;
                   7198:                   $statecond=$refstatecond;
1.52      www      7199:               }
                   7200:           }
1.148     www      7201:         }
1.29      www      7202:        }
1.52      www      7203:    }
1.29      www      7204: 
1.52      www      7205: #
1.103     harris41 7206: # Gathered now: all privileges that could apply, and condition number
1.52      www      7207: # 
                   7208: #
                   7209: # Full or no access?
                   7210: #
1.29      www      7211: 
1.52      www      7212:     if ($thisallowed=~/F/) {
                   7213: 	return 'F';
                   7214:     }
1.29      www      7215: 
1.52      www      7216:     unless ($thisallowed) {
                   7217:         return '';
                   7218:     }
1.29      www      7219: 
1.52      www      7220: # Restrictions exist, deal with them
                   7221: #
                   7222: #   C:according to course preferences
                   7223: #   R:according to resource settings
                   7224: #   L:unless locked
                   7225: #   X:according to user session state
                   7226: #
                   7227: 
                   7228: # Possibly locked functionality, check all courses
1.54      www      7229: # Locks might take effect only after 10 minutes cache expiration for other
                   7230: # courses, and 2 minutes for current course
1.52      www      7231: 
                   7232:     my $envkey;
                   7233:     if ($thisallowed=~/L/) {
1.1000    raeburn  7234:         foreach $envkey (keys(%env)) {
1.54      www      7235:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7236:                my $courseid=$2;
                   7237:                my $roleid=$1.'.'.$2;
1.92      www      7238:                $courseid=~s/^\///;
1.54      www      7239:                my $expiretime=600;
1.620     albertel 7240:                if ($env{'request.role'} eq $roleid) {
1.54      www      7241: 		  $expiretime=120;
                   7242:                }
                   7243: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7244:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7245:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7246: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7247:                }
1.620     albertel 7248:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7249:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7250: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7251:                        &log($env{'user.domain'},$env{'user.name'},
                   7252:                             $env{'user.home'},
1.57      www      7253:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7254:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7255:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7256: 		       return '';
                   7257:                    }
                   7258:                }
1.620     albertel 7259:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7260:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7261: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7262:                        &log($env{'user.domain'},$env{'user.name'},
                   7263:                             $env{'user.home'},
1.57      www      7264:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7265:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7266:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7267: 		       return '';
                   7268:                    }
                   7269:                }
                   7270: 	   }
1.29      www      7271:        }
1.52      www      7272:     }
                   7273:    
                   7274: #
                   7275: # Rest of the restrictions depend on selected course
                   7276: #
                   7277: 
1.620     albertel 7278:     unless ($env{'request.course.id'}) {
1.766     albertel 7279: 	if ($thisallowed eq 'A') {
                   7280: 	    return 'A';
1.814     raeburn  7281:         } elsif ($thisallowed eq 'B') {
                   7282:             return 'B';
1.766     albertel 7283: 	} else {
                   7284: 	    return '1';
                   7285: 	}
1.52      www      7286:     }
1.29      www      7287: 
1.52      www      7288: #
                   7289: # Now user is definitely in a course
                   7290: #
1.53      www      7291: 
                   7292: 
                   7293: # Course preferences
                   7294: 
                   7295:    if ($thisallowed=~/C/) {
1.620     albertel 7296:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7297:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7298:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7299: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7300: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7301: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7302: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7303: 			$env{'request.course.id'});
                   7304: 	   }
1.237     www      7305:            return '';
                   7306:        }
                   7307: 
1.620     albertel 7308:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7309: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7310: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7311: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7312: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7313: 			$env{'request.course.id'});
                   7314: 	   }
1.54      www      7315:            return '';
                   7316:        }
1.53      www      7317:    }
                   7318: 
                   7319: # Resource preferences
                   7320: 
                   7321:    if ($thisallowed=~/R/) {
1.620     albertel 7322:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7323:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7324: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7325: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7326: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7327: 	   }
                   7328: 	   return '';
1.54      www      7329:        }
1.53      www      7330:    }
1.30      www      7331: 
1.246     www      7332: # Restricted by state or randomout?
1.30      www      7333: 
1.52      www      7334:    if ($thisallowed=~/X/) {
1.620     albertel 7335:       if ($env{'acc.randomout'}) {
1.579     albertel 7336: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7337:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7338:             return ''; 
                   7339:          }
1.247     www      7340:       }
                   7341:       if (&condval($statecond)) {
1.52      www      7342: 	 return '2';
                   7343:       } else {
                   7344:          return '';
                   7345:       }
                   7346:    }
1.30      www      7347: 
1.766     albertel 7348:     if ($thisallowed eq 'A') {
                   7349: 	return 'A';
1.814     raeburn  7350:     } elsif ($thisallowed eq 'B') {
                   7351:         return 'B';
1.766     albertel 7352:     }
1.52      www      7353:    return 'F';
1.232     www      7354: }
1.1162    raeburn  7355: 
1.1192    raeburn  7356: # ------------------------------------------- Check construction space access
                   7357: 
                   7358: sub constructaccess {
                   7359:     my ($url,$setpriv)=@_;
                   7360: 
                   7361: # We do not allow editing of previous versions of files
                   7362:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7363: 
                   7364: # Get username and domain from URL
                   7365:     my ($ownername,$ownerdomain,$ownerhome);
                   7366: 
                   7367:     ($ownerdomain,$ownername) =
1.1297    damieng  7368:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)/});
1.1192    raeburn  7369: 
                   7370: # The URL does not really point to any authorspace, forget it
                   7371:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7372: 
                   7373: # Now we need to see if the user has access to the authorspace of
                   7374: # $ownername at $ownerdomain
                   7375: 
                   7376:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7377: # Real author for this?
                   7378:        $ownerhome = $env{'user.home'};
                   7379:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7380:           return ($ownername,$ownerdomain,$ownerhome);
                   7381:        }
                   7382:     } else {
                   7383: # Co-author for this?
                   7384:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7385:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7386:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7387:             return ($ownername,$ownerdomain,$ownerhome);
                   7388:         }
1.1312    raeburn  7389:         if ($env{'request.course.id'}) {
                   7390:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   7391:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   7392:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   7393:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   7394:                     return ($ownername,$ownerdomain,$ownerhome);
                   7395:                 }
                   7396:             }
                   7397:         }
1.1192    raeburn  7398:     }
                   7399: 
                   7400: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7401: # we might as well leave
                   7402:    unless ($setpriv) { return ''; }
                   7403: 
                   7404: # Backdoor access?
                   7405:     my $allowed=&allowed('eco',$ownerdomain);
                   7406: # Nope
                   7407:     unless ($allowed) { return ''; }
                   7408: # Looks like we may have access, but could be locked by the owner of the construction space
                   7409:     if ($allowed eq 'U') {
                   7410:         my %blocked=&get('environment',['domcoord.author'],
                   7411:                          $ownerdomain,$ownername);
                   7412: # Is blocked by owner
                   7413:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7414:     }
                   7415:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7416: # Grant temporary access
                   7417:         my $then=$env{'user.login.time'};
1.1209    raeburn  7418:         my $update=$env{'user.update.time'};
1.1192    raeburn  7419:         if (!$update) { $update = $then; }
                   7420:         my $refresh=$env{'user.refresh.time'};
                   7421:         if (!$refresh) { $refresh = $update; }
                   7422:         my $now = time;
                   7423:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7424:                            $now,'ca','constructaccess');
                   7425:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7426:         return($ownername,$ownerdomain,$ownerhome);
                   7427:     }
                   7428: # No business here
                   7429:     return '';
                   7430: }
                   7431: 
1.1282    raeburn  7432: # ----------------------------------------------------------- Content Blocking
                   7433: 
                   7434: {
                   7435: # Caches for faster Course Contents display where content blocking
                   7436: # is in operation (i.e., interval param set) for timed quiz.
                   7437: #
                   7438: # User for whom data are being temporarily cached.
                   7439: my $cacheduser='';
                   7440: # Cached blockers for this user (a hash of blocking items). 
                   7441: my %cachedblockers=();
                   7442: # When the data were last cached.
                   7443: my $cachedlast='';
                   7444: 
                   7445: sub load_all_blockers {
                   7446:     my ($uname,$udom,$blocks)=@_;
                   7447:     if (($uname ne '') && ($udom ne '')) { 
                   7448:         if (($cacheduser eq $uname.':'.$udom) &&
                   7449:             (abs($cachedlast-time)<5)) {
                   7450:             return;
                   7451:         }
                   7452:     }
                   7453:     $cachedlast=time;
                   7454:     $cacheduser=$uname.':'.$udom;
                   7455:     %cachedblockers = &get_commblock_resources($blocks);
                   7456: }
                   7457: 
1.1162    raeburn  7458: sub get_comm_blocks {
                   7459:     my ($cdom,$cnum) = @_;
                   7460:     if ($cdom eq '' || $cnum eq '') {
                   7461:         return unless ($env{'request.course.id'});
                   7462:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7463:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7464:     }
                   7465:     my %commblocks;
                   7466:     my $hashid=$cdom.'_'.$cnum;
                   7467:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7468:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7469:         %commblocks = %{$blocksref};
                   7470:     } else {
                   7471:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7472:         my $cachetime = 600;
                   7473:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7474:     }
                   7475:     return %commblocks;
                   7476: }
                   7477: 
1.1282    raeburn  7478: sub get_commblock_resources {
                   7479:     my ($blocks) = @_;
                   7480:     my %blockers = ();
                   7481:     return %blockers unless ($env{'request.course.id'});
                   7482:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7483:     my %commblocks;
                   7484:     if (ref($blocks) eq 'HASH') {
                   7485:         %commblocks = %{$blocks};
                   7486:     } else {
                   7487:         %commblocks = &get_comm_blocks();
                   7488:     }
1.1282    raeburn  7489:     return %blockers unless (keys(%commblocks) > 0); 
                   7490:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7491:     return %blockers unless (ref($navmap));
1.1162    raeburn  7492:     my $now = time;
                   7493:     foreach my $block (keys(%commblocks)) {
                   7494:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7495:             my ($start,$end) = ($1,$2);
                   7496:             if ($start <= $now && $end >= $now) {
                   7497:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7498:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7499:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  7500:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7501:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  7502:                             }
                   7503:                         }
                   7504:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  7505:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7506:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7507:                             }
                   7508:                         }
                   7509:                     }
                   7510:                 }
                   7511:             }
                   7512:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7513:             my $item = $1;
1.1163    raeburn  7514:             my @to_test;
1.1162    raeburn  7515:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7516:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  7517:                     my @interval;
                   7518:                     my $type = 'map';
                   7519:                     if ($item eq 'course') {
                   7520:                         $type = 'course';
                   7521:                         @interval=&EXT("resource.0.interval");
                   7522:                     } else {
                   7523:                         if ($item =~ /___\d+___/) {
                   7524:                             $type = 'resource';
                   7525:                             @interval=&EXT("resource.0.interval",$item);
                   7526:                             if (ref($navmap)) {                        
                   7527:                                 my $res = $navmap->getBySymb($item); 
                   7528:                                 push(@to_test,$res);
                   7529:                             }
1.1162    raeburn  7530:                         } else {
1.1282    raeburn  7531:                             my $mapsymb = &symbread($item,1);
                   7532:                             if ($mapsymb) {
                   7533:                                 if (ref($navmap)) {
                   7534:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7535:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7536:                                     foreach my $res (@to_test) {
                   7537:                                         my $symb = $res->symb();
                   7538:                                         next if ($symb eq $mapsymb);
                   7539:                                         if ($symb ne '') {
                   7540:                                             @interval=&EXT("resource.0.interval",$symb);
                   7541:                                             if ($interval[1] eq 'map') {
                   7542:                                                 last;
1.1162    raeburn  7543:                                             }
                   7544:                                         }
                   7545:                                     }
                   7546:                                 }
                   7547:                             }
                   7548:                         }
1.1282    raeburn  7549:                     }
1.1310    raeburn  7550:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  7551:                         my $timelimit = $1; 
1.1282    raeburn  7552:                         my $first_access;
                   7553:                         if ($type eq 'resource') {
                   7554:                             $first_access=&get_first_access($interval[1],$item);
                   7555:                         } elsif ($type eq 'map') {
                   7556:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7557:                         } else {
                   7558:                             $first_access=&get_first_access($interval[1]);
                   7559:                         }
                   7560:                         if ($first_access) {
1.1292    raeburn  7561:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  7562:                             if ($timesup > $now) {
                   7563:                                 my $activeblock;
                   7564:                                 foreach my $res (@to_test) {
1.1283    raeburn  7565:                                     if ($res->answerable()) {
1.1282    raeburn  7566:                                         $activeblock = 1;
                   7567:                                         last;
                   7568:                                     }
                   7569:                                 }
                   7570:                                 if ($activeblock) {
                   7571:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7572:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7573:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7574:                                          }
                   7575:                                     }
                   7576:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7577:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7578:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7579:                                         }
1.1162    raeburn  7580:                                     }
                   7581:                                 }
                   7582:                             }
                   7583:                         }
                   7584:                     }
                   7585:                 }
                   7586:             }
                   7587:         }
                   7588:     }
1.1282    raeburn  7589:     return %blockers;
1.1162    raeburn  7590: }
                   7591: 
1.1282    raeburn  7592: sub has_comm_blocking {
                   7593:     my ($priv,$symb,$uri,$blocks) = @_;
                   7594:     my @blockers;
                   7595:     return unless ($env{'request.course.id'});
                   7596:     return unless ($priv eq 'bre');
                   7597:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7598:     return if ($env{'request.state'} eq 'construct');
                   7599:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7600:     return unless (keys(%cachedblockers) > 0);
                   7601:     my (%possibles,@symbs);
                   7602:     if (!$symb) {
                   7603:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7604:     }
1.1282    raeburn  7605:     if ($symb) {
                   7606:         @symbs = ($symb);
                   7607:     } elsif (keys(%possibles)) { 
                   7608:         @symbs = keys(%possibles);
                   7609:     }
                   7610:     my $noblock;
                   7611:     foreach my $symb (@symbs) {
                   7612:         last if ($noblock);
                   7613:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7614:         foreach my $block (keys(%cachedblockers)) {
                   7615:             if ($block =~ /^firstaccess____(.+)$/) {
                   7616:                 my $item = $1;
                   7617:                 if (($item eq $map) || ($item eq $symb)) {
                   7618:                     $noblock = 1;
                   7619:                     last;
                   7620:                 }
                   7621:             }
                   7622:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7623:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7624:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7625:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7626:                             push(@blockers,$block);
                   7627:                         }
                   7628:                     }
                   7629:                 }
1.1162    raeburn  7630:             }
1.1282    raeburn  7631:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7632:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7633:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7634:                         push(@blockers,$block);
                   7635:                     }
                   7636:                 }
1.1162    raeburn  7637:             }
                   7638:         }
                   7639:     }
1.1282    raeburn  7640:     return if ($noblock);
                   7641:     return @blockers;
                   7642: }
1.1162    raeburn  7643: }
                   7644: 
1.1282    raeburn  7645: # -------------------------------- Deversion and split uri into path an filename   
                   7646: 
1.1133    foxr     7647: #
1.1282    raeburn  7648: #   Removes the version from a URI and
1.1133    foxr     7649: #   splits it in to its filename and path to the filename.
                   7650: #   Seems like File::Basename could have done this more clearly.
                   7651: #   Parameters:
                   7652: #      $uri   - input URI
                   7653: #   Returns:
                   7654: #     Two element list consisting of 
                   7655: #     $pathname  - the URI up to and excluding the trailing /
                   7656: #     $filename  - The part of the URI following the last /
                   7657: #  NOTE:
                   7658: #    Another realization of this is simply:
                   7659: #    use File::Basename;
                   7660: #    ...
                   7661: #    $uri = shift;
                   7662: #    $filename = basename($uri);
                   7663: #    $path     = dirname($uri);
                   7664: #    return ($filename, $path);
                   7665: #
                   7666: #     The implementation below is probably faster however.
                   7667: #
1.710     albertel 7668: sub split_uri_for_cond {
                   7669:     my $uri=&deversion(&declutter(shift));
                   7670:     my @uriparts=split(/\//,$uri);
                   7671:     my $filename=pop(@uriparts);
                   7672:     my $pathname=join('/',@uriparts);
                   7673:     return ($pathname,$filename);
                   7674: }
1.232     www      7675: # --------------------------------------------------- Is a resource on the map?
                   7676: 
                   7677: sub is_on_map {
1.710     albertel 7678:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7679:     #Trying to find the conditional for the file
1.620     albertel 7680:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7681: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7682:     if ($match) {
1.289     bowersj2 7683: 	return (1,$1);
                   7684:     } else {
1.434     www      7685: 	return (0,0);
1.289     bowersj2 7686:     }
1.12      www      7687: }
                   7688: 
1.427     www      7689: # --------------------------------------------------------- Get symb from alias
                   7690: 
                   7691: sub get_symb_from_alias {
                   7692:     my $symb=shift;
                   7693:     my ($map,$resid,$url)=&decode_symb($symb);
                   7694: # Already is a symb
                   7695:     if ($url) { return $symb; }
                   7696: # Must be an alias
                   7697:     my $aliassymb='';
                   7698:     my %bighash;
1.620     albertel 7699:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7700:                             &GDBM_READER(),0640)) {
                   7701:         my $rid=$bighash{'mapalias_'.$symb};
                   7702: 	if ($rid) {
                   7703: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7704: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7705: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7706: 	}
                   7707:         untie %bighash;
                   7708:     }
                   7709:     return $aliassymb;
                   7710: }
                   7711: 
1.12      www      7712: # ----------------------------------------------------------------- Define Role
                   7713: 
                   7714: sub definerole {
                   7715:   if (allowed('mcr','/')) {
                   7716:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7717:     foreach my $role (split(':',$sysrole)) {
                   7718: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7719:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7720:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7721: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7722:                return "refused:s:$crole&$cqual"; 
                   7723:             }
                   7724:         }
1.191     harris41 7725:     }
1.800     albertel 7726:     foreach my $role (split(':',$domrole)) {
                   7727: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7728:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7729:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7730: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7731:                return "refused:d:$crole&$cqual"; 
                   7732:             }
                   7733:         }
1.191     harris41 7734:     }
1.800     albertel 7735:     foreach my $role (split(':',$courole)) {
                   7736: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7737:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7738:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7739: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7740:                return "refused:c:$crole&$cqual"; 
                   7741:             }
                   7742:         }
1.191     harris41 7743:     }
1.620     albertel 7744:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7745:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7746: 	        "rolesdef_$rolename=".
                   7747:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7748:     return reply($command,$env{'user.home'});
1.12      www      7749:   } else {
                   7750:     return 'refused';
                   7751:   }
1.105     harris41 7752: }
                   7753: 
                   7754: # ---------------- Make a metadata query against the network of library servers
                   7755: 
                   7756: sub metadata_query {
1.1237    raeburn  7757:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7758:     my %rhash;
1.845     albertel 7759:     my %libserv = &all_library();
1.244     matthew  7760:     my @server_list = (defined($server_array) ? @$server_array
                   7761:                                               : keys(%libserv) );
                   7762:     for my $server (@server_list) {
1.1237    raeburn  7763:         my $domains = ''; 
                   7764:         if (ref($domains_hash) eq 'HASH') {
                   7765:             $domains = $domains_hash->{$server}; 
                   7766:         }
1.118     harris41 7767: 	unless ($custom or $customshow) {
1.1237    raeburn  7768: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7769: 	    $rhash{$server}=$reply;
                   7770: 	}
                   7771: 	else {
                   7772: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7773: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7774: 			     $server);
                   7775: 	    $rhash{$server}=$reply;
                   7776: 	}
1.112     harris41 7777:     }
1.118     harris41 7778:     return \%rhash;
1.240     www      7779: }
                   7780: 
                   7781: # ----------------------------------------- Send log queries and wait for reply
                   7782: 
                   7783: sub log_query {
                   7784:     my ($uname,$udom,$query,%filters)=@_;
                   7785:     my $uhome=&homeserver($uname,$udom);
                   7786:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7787:     my $uhost=&hostname($uhome);
1.800     albertel 7788:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7789:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7790:                        $uhome);
1.479     albertel 7791:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7792:     return get_query_reply($queryid);
                   7793: }
                   7794: 
1.818     raeburn  7795: # -------------------------- Update MySQL table for portfolio file
                   7796: 
                   7797: sub update_portfolio_table {
1.821     raeburn  7798:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7799:     if ($group ne '') {
                   7800:         $file_name =~s /^\Q$group\E//;
                   7801:     }
1.818     raeburn  7802:     my $homeserver = &homeserver($uname,$udom);
                   7803:     my $queryid=
1.821     raeburn  7804:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7805:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7806:     my $reply = &get_query_reply($queryid);
                   7807:     return $reply;
                   7808: }
                   7809: 
1.899     raeburn  7810: # -------------------------- Update MySQL allusers table
                   7811: 
                   7812: sub update_allusers_table {
                   7813:     my ($uname,$udom,$names) = @_;
                   7814:     my $homeserver = &homeserver($uname,$udom);
                   7815:     my $queryid=
                   7816:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7817:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7818:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7819:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7820:                'generation='.&escape($names->{'generation'}).'%%'.
                   7821:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7822:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7823:     return;
1.899     raeburn  7824: }
                   7825: 
1.508     raeburn  7826: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7827: 
                   7828: sub fetch_enrollment_query {
1.511     raeburn  7829:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7830:     my $homeserver;
1.547     raeburn  7831:     my $maxtries = 1;
1.508     raeburn  7832:     if ($context eq 'automated') {
                   7833:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7834:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7835:     } else {
                   7836:         $homeserver = &homeserver($cnum,$dom);
                   7837:     }
1.838     albertel 7838:     my $host=&hostname($homeserver);
1.506     raeburn  7839:     my $cmd = '';
1.1000    raeburn  7840:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7841:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7842:     }
                   7843:     $cmd =~ s/%%$//;
                   7844:     $cmd = &escape($cmd);
                   7845:     my $query = 'fetchenrollment';
1.620     albertel 7846:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7847:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7848:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7849:         return 'error: '.$queryid;
                   7850:     }
1.506     raeburn  7851:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7852:     my $tries = 1;
                   7853:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7854:         $reply = &get_query_reply($queryid);
                   7855:         $tries ++;
                   7856:     }
1.526     raeburn  7857:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7858:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7859:     } else {
1.901     albertel 7860:         my @responses = split(/:/,$reply);
1.515     raeburn  7861:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7862:             foreach my $line (@responses) {
                   7863:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7864:                 $$replyref{$key} = $value;
                   7865:             }
                   7866:         } else {
1.1117    foxr     7867:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7868:             foreach my $line (@responses) {
                   7869:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7870:                 $$replyref{$key} = $value;
                   7871:                 if ($value > 0) {
1.800     albertel 7872:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7873:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7874:                         my $destname = $pathname.'/'.$filename;
                   7875:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7876:                         if ($xml_classlist =~ /^error/) {
                   7877:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7878:                         } else {
1.506     raeburn  7879:                             if ( open(FILE,">$destname") ) {
                   7880:                                 print FILE &unescape($xml_classlist);
                   7881:                                 close(FILE);
1.526     raeburn  7882:                             } else {
                   7883:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7884:                             }
                   7885:                         }
                   7886:                     }
                   7887:                 }
                   7888:             }
                   7889:         }
                   7890:         return 'ok';
                   7891:     }
                   7892:     return 'error';
                   7893: }
                   7894: 
1.242     www      7895: sub get_query_reply {
                   7896:     my $queryid=shift;
1.1117    foxr     7897:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7898:     my $reply='';
                   7899:     for (1..100) {
1.1289    damieng  7900: 	sleep(0.2);
1.240     www      7901:         if (-e $replyfile.'.end') {
1.448     albertel 7902: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7903: 		$reply = join('',<$fh>);
                   7904: 		close($fh);
1.240     www      7905: 	   } else { return 'error: reply_file_error'; }
1.242     www      7906:            return &unescape($reply);
                   7907: 	}
1.240     www      7908:     }
1.242     www      7909:     return 'timeout:'.$queryid;
1.240     www      7910: }
                   7911: 
                   7912: sub courselog_query {
1.241     www      7913: #
                   7914: # possible filters:
                   7915: # url: url or symb
                   7916: # username
                   7917: # domain
                   7918: # action: view, submit, grade
                   7919: # start: timestamp
                   7920: # end: timestamp
                   7921: #
1.240     www      7922:     my (%filters)=@_;
1.620     albertel 7923:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7924:     if ($filters{'url'}) {
                   7925: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7926:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7927:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7928:     }
1.620     albertel 7929:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7930:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7931:     return &log_query($cname,$cdom,'courselog',%filters);
                   7932: }
                   7933: 
                   7934: sub userlog_query {
1.858     raeburn  7935: #
                   7936: # possible filters:
                   7937: # action: log check role
                   7938: # start: timestamp
                   7939: # end: timestamp
                   7940: #
1.240     www      7941:     my ($uname,$udom,%filters)=@_;
                   7942:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7943: }
                   7944: 
1.506     raeburn  7945: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7946: 
                   7947: sub auto_run {
1.508     raeburn  7948:     my ($cnum,$cdom) = @_;
1.876     raeburn  7949:     my $response = 0;
                   7950:     my $settings;
                   7951:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7952:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7953:         $settings = $domconfig{'autoenroll'};
                   7954:         if ($settings->{'run'} eq '1') {
                   7955:             $response = 1;
                   7956:         }
                   7957:     } else {
1.934     raeburn  7958:         my $homeserver;
                   7959:         if (&is_course($cdom,$cnum)) {
                   7960:             $homeserver = &homeserver($cnum,$cdom);
                   7961:         } else {
                   7962:             $homeserver = &domain($cdom,'primary');
                   7963:         }
                   7964:         if ($homeserver ne 'no_host') {
                   7965:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7966:         }
1.876     raeburn  7967:     }
1.506     raeburn  7968:     return $response;
                   7969: }
1.776     albertel 7970: 
1.506     raeburn  7971: sub auto_get_sections {
1.508     raeburn  7972:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7973:     my $homeserver;
                   7974:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7975:         $homeserver = &homeserver($cnum,$cdom);
                   7976:     }
                   7977:     if (!defined($homeserver)) { 
                   7978:         if ($cdom =~ /^$match_domain$/) {
                   7979:             $homeserver = &domain($cdom,'primary');
                   7980:         }
                   7981:     }
                   7982:     my @secs;
                   7983:     if (defined($homeserver)) {
                   7984:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7985:         unless ($response eq 'refused') {
                   7986:             @secs = split(/:/,$response);
                   7987:         }
1.506     raeburn  7988:     }
                   7989:     return @secs;
                   7990: }
1.776     albertel 7991: 
1.506     raeburn  7992: sub auto_new_course {
1.1099    raeburn  7993:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7994:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7995:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7996:     return $response;
                   7997: }
1.776     albertel 7998: 
1.506     raeburn  7999: sub auto_validate_courseID {
1.508     raeburn  8000:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8001:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8002:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8003:     return $response;
                   8004: }
1.776     albertel 8005: 
1.1007    raeburn  8006: sub auto_validate_instcode {
1.1020    raeburn  8007:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8008:     my ($homeserver,$response);
                   8009:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8010:         $homeserver = &homeserver($cnum,$cdom);
                   8011:     }
                   8012:     if (!defined($homeserver)) {
                   8013:         if ($cdom =~ /^$match_domain$/) {
                   8014:             $homeserver = &domain($cdom,'primary');
                   8015:         }
                   8016:     }
1.1065    raeburn  8017:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8018:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8019:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8020:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8021: }
                   8022: 
1.506     raeburn  8023: sub auto_create_password {
1.873     raeburn  8024:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8025:     my ($homeserver,$response);
1.506     raeburn  8026:     my $create_passwd = 0;
                   8027:     my $authchk = '';
1.873     raeburn  8028:     if ($udom =~ /^$match_domain$/) {
                   8029:         $homeserver = &domain($udom,'primary');
                   8030:     }
                   8031:     if ($homeserver eq '') {
                   8032:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8033:             $homeserver = &homeserver($cnum,$cdom);
                   8034:         }
                   8035:     }
                   8036:     if ($homeserver eq '') {
                   8037:         $authchk = 'nodomain';
1.506     raeburn  8038:     } else {
1.873     raeburn  8039:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8040:         if ($response eq 'refused') {
                   8041:             $authchk = 'refused';
                   8042:         } else {
1.901     albertel 8043:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8044:         }
1.506     raeburn  8045:     }
                   8046:     return ($authparam,$create_passwd,$authchk);
                   8047: }
                   8048: 
1.706     raeburn  8049: sub auto_photo_permission {
                   8050:     my ($cnum,$cdom,$students) = @_;
                   8051:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8052:     my ($outcome,$perm_reqd,$conditions) = 
                   8053: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8054:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8055: 	return (undef,undef);
                   8056:     }
1.706     raeburn  8057:     return ($outcome,$perm_reqd,$conditions);
                   8058: }
                   8059: 
                   8060: sub auto_checkphotos {
                   8061:     my ($uname,$udom,$pid) = @_;
                   8062:     my $homeserver = &homeserver($uname,$udom);
                   8063:     my ($result,$resulttype);
                   8064:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8065: 				   &escape($uname).':'.&escape($pid),
                   8066: 				   $homeserver));
1.709     albertel 8067:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8068: 	return (undef,undef);
                   8069:     }
1.706     raeburn  8070:     if ($outcome) {
                   8071:         ($result,$resulttype) = split(/:/,$outcome);
                   8072:     } 
                   8073:     return ($result,$resulttype);
                   8074: }
                   8075: 
                   8076: sub auto_photochoice {
                   8077:     my ($cnum,$cdom) = @_;
                   8078:     my $homeserver = &homeserver($cnum,$cdom);
                   8079:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8080: 						       &escape($cdom),
                   8081: 						       $homeserver)));
1.709     albertel 8082:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8083: 	return (undef,undef);
                   8084:     }
1.706     raeburn  8085:     return ($update,$comment);
                   8086: }
                   8087: 
                   8088: sub auto_photoupdate {
                   8089:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8090:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8091:     my $host=&hostname($homeserver);
1.706     raeburn  8092:     my $cmd = '';
                   8093:     my $maxtries = 1;
1.800     albertel 8094:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8095:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8096:     }
                   8097:     $cmd =~ s/%%$//;
                   8098:     $cmd = &escape($cmd);
                   8099:     my $query = 'institutionalphotos';
                   8100:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8101:     unless ($queryid=~/^\Q$host\E\_/) {
                   8102:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8103:         return 'error: '.$queryid;
                   8104:     }
                   8105:     my $reply = &get_query_reply($queryid);
                   8106:     my $tries = 1;
                   8107:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8108:         $reply = &get_query_reply($queryid);
                   8109:         $tries ++;
                   8110:     }
                   8111:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8112:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8113:     } else {
                   8114:         my @responses = split(/:/,$reply);
                   8115:         my $outcome = shift(@responses); 
                   8116:         foreach my $item (@responses) {
                   8117:             my ($key,$value) = split(/=/,$item);
                   8118:             $$photo{$key} = $value;
                   8119:         }
                   8120:         return $outcome;
                   8121:     }
                   8122:     return 'error';
                   8123: }
                   8124: 
1.521     raeburn  8125: sub auto_instcode_format {
1.793     albertel 8126:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8127: 	$cat_order) = @_;
1.521     raeburn  8128:     my $courses = '';
1.772     raeburn  8129:     my @homeservers;
1.521     raeburn  8130:     if ($caller eq 'global') {
1.841     albertel 8131: 	my %servers = &get_servers($codedom,'library');
                   8132: 	foreach my $tryserver (keys(%servers)) {
                   8133: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8134: 		push(@homeservers,$tryserver);
                   8135: 	    }
1.584     raeburn  8136:         }
1.1022    raeburn  8137:     } elsif ($caller eq 'requests') {
                   8138:         if ($codedom =~ /^$match_domain$/) {
                   8139:             my $chome = &domain($codedom,'primary');
                   8140:             unless ($chome eq 'no_host') {
                   8141:                 push(@homeservers,$chome);
                   8142:             }
                   8143:         }
1.521     raeburn  8144:     } else {
1.772     raeburn  8145:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8146:     }
1.793     albertel 8147:     foreach my $code (keys(%{$instcodes})) {
                   8148:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8149:     }
                   8150:     chop($courses);
1.772     raeburn  8151:     my $ok_response = 0;
                   8152:     my $response;
                   8153:     while (@homeservers > 0 && $ok_response == 0) {
                   8154:         my $server = shift(@homeservers); 
                   8155:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8156:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8157:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8158: 		split(/:/,$response);
1.772     raeburn  8159:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8160:             push(@{$codetitles},&str2array($codetitles_str));
                   8161:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8162:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8163:             $ok_response = 1;
                   8164:         }
                   8165:     }
                   8166:     if ($ok_response) {
1.521     raeburn  8167:         return 'ok';
1.772     raeburn  8168:     } else {
                   8169:         return $response;
1.521     raeburn  8170:     }
                   8171: }
                   8172: 
1.792     raeburn  8173: sub auto_instcode_defaults {
                   8174:     my ($domain,$returnhash,$code_order) = @_;
                   8175:     my @homeservers;
1.841     albertel 8176: 
                   8177:     my %servers = &get_servers($domain,'library');
                   8178:     foreach my $tryserver (keys(%servers)) {
                   8179: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8180: 	    push(@homeservers,$tryserver);
                   8181: 	}
1.792     raeburn  8182:     }
1.841     albertel 8183: 
1.792     raeburn  8184:     my $response;
1.841     albertel 8185:     foreach my $server (@homeservers) {
1.792     raeburn  8186:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8187:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8188: 	
                   8189: 	foreach my $pair (split(/\&/,$response)) {
                   8190: 	    my ($name,$value)=split(/\=/,$pair);
                   8191: 	    if ($name eq 'code_order') {
                   8192: 		@{$code_order} = split(/\&/,&unescape($value));
                   8193: 	    } else {
                   8194: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8195: 	    }
                   8196: 	}
                   8197: 	return 'ok';
1.792     raeburn  8198:     }
1.841     albertel 8199: 
                   8200:     return $response;
1.1003    raeburn  8201: }
                   8202: 
                   8203: sub auto_possible_instcodes {
1.1007    raeburn  8204:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8205:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8206:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8207:         return;
                   8208:     }
1.1003    raeburn  8209:     my (@homeservers,$uhome);
                   8210:     if (defined(&domain($domain,'primary'))) {
                   8211:         $uhome=&domain($domain,'primary');
                   8212:         push(@homeservers,&domain($domain,'primary'));
                   8213:     } else {
                   8214:         my %servers = &get_servers($domain,'library');
                   8215:         foreach my $tryserver (keys(%servers)) {
                   8216:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8217:                 push(@homeservers,$tryserver);
                   8218:             }
                   8219:         }
                   8220:     }
                   8221:     my $response;
                   8222:     foreach my $server (@homeservers) {
                   8223:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8224:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8225:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8226:             split(':',$response);
                   8227:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8228:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8229:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8230:             my ($name,$value)=split('=',$item);
                   8231:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8232:         }
                   8233:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8234:             my ($name,$value)=split('=',$item);
                   8235:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8236:         }
                   8237:         return 'ok';
                   8238:     }
                   8239:     return $response;
                   8240: }
1.792     raeburn  8241: 
1.1010    raeburn  8242: sub auto_courserequest_checks {
                   8243:     my ($dom) = @_;
1.1020    raeburn  8244:     my ($homeserver,%validations);
                   8245:     if ($dom =~ /^$match_domain$/) {
                   8246:         $homeserver = &domain($dom,'primary');
                   8247:     }
                   8248:     unless ($homeserver eq 'no_host') {
                   8249:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8250:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8251:             my @items = split(/&/,$response);
                   8252:             foreach my $item (@items) {
                   8253:                 my ($key,$value) = split('=',$item);
                   8254:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8255:             }
                   8256:         }
                   8257:     }
1.1010    raeburn  8258:     return %validations; 
                   8259: }
                   8260: 
1.1020    raeburn  8261: sub auto_courserequest_validation {
1.1255    raeburn  8262:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8263:     my ($homeserver,$response);
                   8264:     if ($dom =~ /^$match_domain$/) {
                   8265:         $homeserver = &domain($dom,'primary');
                   8266:     }
1.1255    raeburn  8267:     unless ($homeserver eq 'no_host') {
                   8268:         my $customdata;
                   8269:         if (ref($custominfo) eq 'HASH') {
                   8270:             $customdata = &freeze_escape($custominfo);
                   8271:         }
1.1020    raeburn  8272:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8273:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8274:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8275:                                     $customdata,$homeserver));
1.1020    raeburn  8276:     }
                   8277:     return $response;
                   8278: }
                   8279: 
1.777     albertel 8280: sub auto_validate_class_sec {
1.918     raeburn  8281:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8282:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8283:     my $ownerlist;
                   8284:     if (ref($owners) eq 'ARRAY') {
                   8285:         $ownerlist = join(',',@{$owners});
                   8286:     } else {
                   8287:         $ownerlist = $owners;
                   8288:     }
1.773     raeburn  8289:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8290:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8291:     return $response;
                   8292: }
                   8293: 
1.1248    raeburn  8294: sub auto_crsreq_update {
                   8295:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8296:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8297:     my ($homeserver,%crsreqresponse);
                   8298:     if ($cdom =~ /^$match_domain$/) {
                   8299:         $homeserver = &domain($cdom,'primary');
                   8300:     }
                   8301:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8302:         my $info;
                   8303:         if (ref($inbound) eq 'HASH') {
                   8304:             $info = &freeze_escape($inbound);
                   8305:         }
                   8306:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8307:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8308:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8309:                             &escape($title).':'.&escape($code).':'.
                   8310:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8311:                             $homeserver);
1.1248    raeburn  8312:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8313:             my @items = split(/&/,$response);
                   8314:             foreach my $item (@items) {
                   8315:                 my ($key,$value) = split('=',$item);
                   8316:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8317:             }
                   8318:         }
                   8319:     }
                   8320:     return \%crsreqresponse;
                   8321: }
                   8322: 
1.1305    raeburn  8323: sub auto_export_grades {
1.1309    raeburn  8324:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8325:     my ($homeserver,%exportresponse);
                   8326:     if ($cdom =~ /^$match_domain$/) {
                   8327:         $homeserver = &domain($cdom,'primary');
                   8328:     }
                   8329:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8330:         my $info;
                   8331:         if (ref($inforef) eq 'HASH') {
                   8332:             $info = &freeze_escape($inforef);
                   8333:         }
                   8334:         if (ref($gradesref) eq 'HASH') {
                   8335:             my $grades = &freeze_escape($gradesref);
                   8336:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8337:                                 $info.':'.$grades,$homeserver);
                   8338:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8339:                 my @items = split(/&/,$response);
                   8340:                 foreach my $item (@items) {
                   8341:                     my ($key,$value) = split('=',$item);
                   8342:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8343:                 }
                   8344:             }
                   8345:         }
                   8346:     }
                   8347:     return \%exportresponse;
1.1305    raeburn  8348: }
                   8349: 
1.1287    raeburn  8350: sub check_instcode_cloning {
                   8351:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8352:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8353:         return;
                   8354:     }
                   8355:     my $canclone;
                   8356:     if (@{$code_order} > 0) {
                   8357:         my $instcoderegexp ='^';
                   8358:         my @clonecodes = split(/\&/,$cloner);
                   8359:         foreach my $item (@{$code_order}) {
                   8360:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8361:                 foreach my $pair (@clonecodes) {
                   8362:                     my ($key,$val) = split(/\=/,$pair,2);
                   8363:                     $val = &unescape($val);
                   8364:                     if ($key eq $item) {
                   8365:                         $instcoderegexp .= '('.$val.')';
                   8366:                         last;
                   8367:                     }
                   8368:                 }
                   8369:             } else {
                   8370:                 $instcoderegexp .= $codedefaults->{$item};
                   8371:             }
                   8372:         }
                   8373:         $instcoderegexp .= '$';
                   8374:         my (@from,@to);
                   8375:         eval {
                   8376:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8377:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8378:         };
                   8379:         if ((@from > 0) && (@to > 0)) {
                   8380:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8381:             if (!@diffs) {
                   8382:                 $canclone = 1;
                   8383:             }
                   8384:         }
                   8385:     }
                   8386:     return $canclone;
                   8387: }
                   8388: 
                   8389: sub default_instcode_cloning {
                   8390:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8391:     my (%codedefaults,@code_order,$canclone);
                   8392:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8393:         %codedefaults = %{$codedefaultsref};
                   8394:         @code_order = @{$codeorderref};
                   8395:     } elsif ($clonedom) {
                   8396:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8397:     }
                   8398:     if (($domdefclone) && (@code_order)) {
                   8399:         my @clonecodes = split(/\+/,$domdefclone);
                   8400:         my $instcoderegexp ='^';
                   8401:         foreach my $item (@code_order) {
                   8402:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8403:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8404:             } else {
                   8405:                 $instcoderegexp .= $codedefaults{$item};
                   8406:             }
                   8407:         }
                   8408:         $instcoderegexp .= '$';
                   8409:         my (@from,@to);
                   8410:         eval {
                   8411:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8412:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8413:         };
                   8414:         if ((@from > 0) && (@to > 0)) {
                   8415:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8416:             if (!@diffs) {
                   8417:                 $canclone = 1;
                   8418:             }
                   8419:         }
                   8420:     }
                   8421:     return $canclone;
                   8422: }
                   8423: 
1.679     raeburn  8424: # ------------------------------------------------------- Course Group routines
                   8425: 
                   8426: sub get_coursegroups {
1.809     raeburn  8427:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8428:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8429: }
                   8430: 
1.679     raeburn  8431: sub modify_coursegroup {
                   8432:     my ($cdom,$cnum,$groupsettings) = @_;
                   8433:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8434: }
                   8435: 
1.809     raeburn  8436: sub toggle_coursegroup_status {
                   8437:     my ($cdom,$cnum,$group,$action) = @_;
                   8438:     my ($from_namespace,$to_namespace);
                   8439:     if ($action eq 'delete') {
                   8440:         $from_namespace = 'coursegroups';
                   8441:         $to_namespace = 'deleted_groups';
                   8442:     } else {
                   8443:         $from_namespace = 'deleted_groups';
                   8444:         $to_namespace = 'coursegroups';
                   8445:     }
                   8446:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8447:     if (my $tmp = &error(%curr_group)) {
                   8448:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8449:         return ('read error',$tmp);
                   8450:     } else {
                   8451:         my %savedsettings = %curr_group; 
1.809     raeburn  8452:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8453:         my $deloutcome;
                   8454:         if ($result eq 'ok') {
1.809     raeburn  8455:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8456:         } else {
                   8457:             return ('write error',$result);
                   8458:         }
                   8459:         if ($deloutcome eq 'ok') {
                   8460:             return 'ok';
                   8461:         } else {
                   8462:             return ('delete error',$deloutcome);
                   8463:         }
                   8464:     }
                   8465: }
                   8466: 
1.679     raeburn  8467: sub modify_group_roles {
1.957     raeburn  8468:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8469:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8470:     my $role = 'gr/'.&escape($userprivs);
                   8471:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8472:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8473:     if ($result eq 'ok') {
                   8474:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8475:     }
1.679     raeburn  8476:     return $result;
                   8477: }
                   8478: 
                   8479: sub modify_coursegroup_membership {
                   8480:     my ($cdom,$cnum,$membership) = @_;
                   8481:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8482:     return $result;
                   8483: }
                   8484: 
1.682     raeburn  8485: sub get_active_groups {
                   8486:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8487:     my $now = time;
                   8488:     my %groups = ();
                   8489:     foreach my $key (keys(%env)) {
1.811     albertel 8490:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8491:             my ($start,$end) = split(/\./,$env{$key});
                   8492:             if (($end!=0) && ($end<$now)) { next; }
                   8493:             if (($start!=0) && ($start>$now)) { next; }
                   8494:             if ($1 eq $cdom && $2 eq $cnum) {
                   8495:                 $groups{$3} = $env{$key} ;
                   8496:             }
                   8497:         }
                   8498:     }
                   8499:     return %groups;
                   8500: }
                   8501: 
1.683     raeburn  8502: sub get_group_membership {
                   8503:     my ($cdom,$cnum,$group) = @_;
                   8504:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8505: }
                   8506: 
                   8507: sub get_users_groups {
                   8508:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8509:     my @usersgroups;
1.683     raeburn  8510:     my $cachetime=1800;
                   8511: 
                   8512:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8513:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8514:     if (defined($cached)) {
1.734     albertel 8515:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8516:     } else {  
                   8517:         $grouplist = '';
1.816     raeburn  8518:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8519:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8520:         my $access_end = $env{'course.'.$courseid.
                   8521:                               '.default_enrollment_end_date'};
                   8522:         my $now = time;
                   8523:         foreach my $key (keys(%roleshash)) {
                   8524:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8525:                 my $group = $1;
                   8526:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8527:                     my $start = $2;
                   8528:                     my $end = $1;
                   8529:                     if ($start == -1) { next; } # deleted from group
                   8530:                     if (($start!=0) && ($start>$now)) { next; }
                   8531:                     if (($end!=0) && ($end<$now)) {
                   8532:                         if ($access_end && $access_end < $now) {
                   8533:                             if ($access_end - $end < 86400) {
                   8534:                                 push(@usersgroups,$group);
1.733     raeburn  8535:                             }
                   8536:                         }
1.817     raeburn  8537:                         next;
1.733     raeburn  8538:                     }
1.817     raeburn  8539:                     push(@usersgroups,$group);
1.683     raeburn  8540:                 }
                   8541:             }
                   8542:         }
1.817     raeburn  8543:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8544:         $grouplist = join(':',@usersgroups);
                   8545:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8546:     }
1.733     raeburn  8547:     return @usersgroups;
1.683     raeburn  8548: }
                   8549: 
                   8550: sub devalidate_getgroups_cache {
                   8551:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8552:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8553: 
1.683     raeburn  8554:     my $hashid="$udom:$uname:$courseid";
                   8555:     &devalidate_cache_new('getgroups',$hashid);
                   8556: }
                   8557: 
1.12      www      8558: # ------------------------------------------------------------------ Plain Text
                   8559: 
                   8560: sub plaintext {
1.988     raeburn  8561:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8562:     if ($short =~ m{^cr/}) {
1.758     albertel 8563: 	return (split('/',$short))[-1];
                   8564:     }
1.742     raeburn  8565:     if (!defined($cid)) {
                   8566:         $cid = $env{'request.course.id'};
                   8567:     }
                   8568:     my %rolenames = (
1.1008    raeburn  8569:                       Course    => 'std',
                   8570:                       Community => 'alt1',
1.1305    raeburn  8571:                       Placement => 'std',
1.742     raeburn  8572:                     );
1.1037    raeburn  8573:     if ($cid ne '') {
                   8574:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8575:             unless ($forcedefault) {
                   8576:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8577:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8578:                 return &Apache::lonlocal::mt($roletext);
                   8579:             }
                   8580:         }
                   8581:     }
                   8582:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8583:         (defined($rolenames{$type})) && 
                   8584:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8585:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8586:     } elsif ($cid ne '') {
                   8587:         my $crstype = $env{'course.'.$cid.'.type'};
                   8588:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8589:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8590:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8591:         }
1.742     raeburn  8592:     }
1.1037    raeburn  8593:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8594: }
                   8595: 
                   8596: # ----------------------------------------------------------------- Assign Role
                   8597: 
                   8598: sub assignrole {
1.957     raeburn  8599:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8600:         $context)=@_;
1.21      www      8601:     my $mrole;
                   8602:     if ($role =~ /^cr\//) {
1.393     www      8603:         my $cwosec=$url;
1.811     albertel 8604:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8605: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8606:            my $refused = 1;
                   8607:            if ($context eq 'requestcourses') {
                   8608:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8609:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8610:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8611:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8612:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8613:                            if ($crsenv{'internal.courseowner'} eq
                   8614:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8615:                                $refused = '';
                   8616:                            }
                   8617:                        }
                   8618:                    }
                   8619:                }
                   8620:            }
                   8621:            if ($refused) {
                   8622:                &logthis('Refused custom assignrole: '.
                   8623:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8624:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8625:                return 'refused';
                   8626:            }
1.104     www      8627:         }
1.21      www      8628:         $mrole='cr';
1.678     raeburn  8629:     } elsif ($role =~ /^gr\//) {
                   8630:         my $cwogrp=$url;
1.811     albertel 8631:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8632:         unless (&allowed('mdg',$cwogrp)) {
                   8633:             &logthis('Refused group assignrole: '.
                   8634:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8635:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8636:             return 'refused';
                   8637:         }
                   8638:         $mrole='gr';
1.21      www      8639:     } else {
1.82      www      8640:         my $cwosec=$url;
1.811     albertel 8641:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8642:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8643:             my $refused;
                   8644:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8645:                 if (!(&allowed('c'.$role,$url))) {
                   8646:                     $refused = 1;
                   8647:                 }
                   8648:             } else {
                   8649:                 $refused = 1;
                   8650:             }
1.947     raeburn  8651:             if ($refused) {
1.1045    raeburn  8652:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8653:                 if (!$selfenroll && $context eq 'course') {
                   8654:                     my %crsenv;
                   8655:                     if ($role eq 'cc' || $role eq 'co') {
                   8656:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8657:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8658:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8659:                                 if ($crsenv{'internal.courseowner'} eq 
                   8660:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8661:                                     $refused = '';
                   8662:                                 }
                   8663:                             }
                   8664:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8665:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8666:                                 if ($crsenv{'internal.courseowner'} eq 
                   8667:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8668:                                     $refused = '';
                   8669:                                 }
                   8670:                             }
                   8671:                         }
                   8672:                     }
                   8673:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8674:                     $refused = '';
1.1017    raeburn  8675:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8676:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8677:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8678:                         my $wrongcc;
                   8679:                         if ($cnum =~ /^$match_community$/) {
                   8680:                             $wrongcc = 1 if ($role eq 'cc');
                   8681:                         } else {
                   8682:                             $wrongcc = 1 if ($role eq 'co');
                   8683:                         }
                   8684:                         unless ($wrongcc) {
                   8685:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8686:                             if ($crsenv{'internal.courseowner'} eq 
                   8687:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8688:                                 $refused = '';
                   8689:                             }
1.1017    raeburn  8690:                         }
                   8691:                     }
1.1183    raeburn  8692:                 } elsif ($context eq 'requestauthor') {
                   8693:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8694:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8695:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8696:                             $refused = '';
                   8697:                         } else {
                   8698:                             my %domdefaults = &get_domain_defaults($udom);
                   8699:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8700:                                 my $checkbystatus;
                   8701:                                 if ($env{'user.adv'}) { 
                   8702:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8703:                                     if ($disposition eq 'automatic') {
                   8704:                                         $refused = '';
                   8705:                                     } elsif ($disposition eq '') {
                   8706:                                         $checkbystatus = 1;
                   8707:                                     } 
                   8708:                                 } else {
                   8709:                                     $checkbystatus = 1;
                   8710:                                 }
                   8711:                                 if ($checkbystatus) {
                   8712:                                     if ($env{'environment.inststatus'}) {
                   8713:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8714:                                         foreach my $type (@inststatuses) {
                   8715:                                             if (($type ne '') &&
                   8716:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8717:                                                 $refused = '';
                   8718:                                             }
                   8719:                                         }
                   8720:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8721:                                         $refused = '';
                   8722:                                     }
                   8723:                                 }
                   8724:                             }
                   8725:                         }
                   8726:                     }
1.1017    raeburn  8727:                 }
                   8728:                 if ($refused) {
1.947     raeburn  8729:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8730:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8731: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8732:                     return 'refused';
                   8733:                 }
1.932     raeburn  8734:             }
1.1131    raeburn  8735:         } elsif ($role eq 'au') {
                   8736:             if ($url ne '/'.$udom.'/') {
                   8737:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8738:                          ' to assign author role for '.$uname.':'.$udom.
                   8739:                          ' in domain: '.$url.' refused (wrong domain).');
                   8740:                 return 'refused';
                   8741:             }
1.104     www      8742:         }
1.21      www      8743:         $mrole=$role;
                   8744:     }
1.620     albertel 8745:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8746:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8747:     if ($end) { $command.='_'.$end; }
1.21      www      8748:     if ($start) {
                   8749: 	if ($end) { 
1.81      www      8750:            $command.='_'.$start; 
1.21      www      8751:         } else {
1.81      www      8752:            $command.='_0_'.$start;
1.21      www      8753:         }
                   8754:     }
1.739     raeburn  8755:     my $origstart = $start;
                   8756:     my $origend = $end;
1.957     raeburn  8757:     my $delflag;
1.357     www      8758: # actually delete
                   8759:     if ($deleteflag) {
1.373     www      8760: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8761: # modify command to delete the role
1.620     albertel 8762:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8763:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8764: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8765: # set start and finish to negative values for userrolelog
                   8766:            $start=-1;
                   8767:            $end=-1;
1.957     raeburn  8768:            $delflag = 1;
1.357     www      8769:         }
                   8770:     }
                   8771: # send command
1.349     www      8772:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8773: # log new user role if status is ok
1.349     www      8774:     if ($answer eq 'ok') {
1.663     raeburn  8775: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8776:         if (($role eq 'cc') || ($role eq 'in') ||
                   8777:             ($role eq 'ep') || ($role eq 'ad') ||
                   8778:             ($role eq 'ta') || ($role eq 'st') ||
                   8779:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8780:             ($role eq 'co')) {
1.1200    raeburn  8781: # for course roles, perform group memberships changes triggered by role change.
                   8782:             unless ($role =~ /^gr/) {
                   8783:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8784:                                                  $origstart,$selfenroll,$context);
                   8785:             }
1.1184    raeburn  8786:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8787:                            $selfenroll,$context);
                   8788:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8789:                  ($role eq 'au') || ($role eq 'dc')) {
                   8790:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8791:                            $context);
                   8792:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8793:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8794:                              $context); 
                   8795:         }
1.1053    raeburn  8796:         if ($role eq 'cc') {
                   8797:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8798:         }
1.349     www      8799:     }
                   8800:     return $answer;
1.169     harris41 8801: }
                   8802: 
1.1053    raeburn  8803: sub autoupdate_coowners {
                   8804:     my ($url,$end,$start,$uname,$udom) = @_;
                   8805:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8806:     if (($cdom ne '') && ($cnum ne '')) {
                   8807:         my $now = time;
                   8808:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8809:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8810:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8811:             my $instcode = $coursehash{'internal.coursecode'};
                   8812:             if ($instcode ne '') {
1.1056    raeburn  8813:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8814:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8815:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8816:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8817:                         if ($result eq 'valid') {
                   8818:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8819:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8820:                                     push(@newcoowners,$coowner);
                   8821:                                 }
                   8822:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8823:                                     push(@newcoowners,$uname.':'.$udom);
                   8824:                                 }
                   8825:                                 @newcoowners = sort(@newcoowners);
                   8826:                             } else {
                   8827:                                 push(@newcoowners,$uname.':'.$udom);
                   8828:                             }
                   8829:                         } else {
                   8830:                             if ($coursehash{'internal.co-owners'}) {
                   8831:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8832:                                     unless ($coowner eq $uname.':'.$udom) {
                   8833:                                         push(@newcoowners,$coowner);
                   8834:                                     }
                   8835:                                 }
                   8836:                                 unless (@newcoowners > 0) {
                   8837:                                     $delcoowners = 1;
                   8838:                                     $coowners = '';
                   8839:                                 }
                   8840:                             }
                   8841:                         }
                   8842:                         if (@newcoowners || $delcoowners) {
                   8843:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8844:                                             $delcoowners,@newcoowners);
                   8845:                         }
                   8846:                     }
                   8847:                 }
                   8848:             }
                   8849:         }
                   8850:     }
                   8851: }
                   8852: 
                   8853: sub store_coowners {
                   8854:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8855:     my $cid = $cdom.'_'.$cnum;
                   8856:     my ($coowners,$delresult,$putresult);
                   8857:     if (@newcoowners) {
                   8858:         $coowners = join(',',@newcoowners);
                   8859:         my %coownershash = (
                   8860:                             'internal.co-owners' => $coowners,
                   8861:                            );
                   8862:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8863:         if ($putresult eq 'ok') {
                   8864:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8865:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8866:             }
                   8867:         }
                   8868:     }
                   8869:     if ($delcoowners) {
                   8870:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8871:         if ($delresult eq 'ok') {
                   8872:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8873:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8874:             }
                   8875:         }
                   8876:     }
                   8877:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8878:         my %crsinfo =
                   8879:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8880:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8881:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8882:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8883:         }
                   8884:     }
                   8885: }
                   8886: 
1.169     harris41 8887: # -------------------------------------------------- Modify user authentication
1.197     www      8888: # Overrides without validation
                   8889: 
1.169     harris41 8890: sub modifyuserauth {
                   8891:     my ($udom,$uname,$umode,$upass)=@_;
                   8892:     my $uhome=&homeserver($uname,$udom);
1.197     www      8893:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8894:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8895:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8896:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8897:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8898: 		     &escape($upass),$uhome);
1.620     albertel 8899:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8900:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8901:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8902:     &log($udom,,$uname,$uhome,
1.620     albertel 8903:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8904:                                      $env{'user.name'}.', '.$umode.
1.197     www      8905:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8906:     unless ($reply eq 'ok') {
1.197     www      8907:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8908: 	return 'error: '.$reply;
                   8909:     }   
1.170     harris41 8910:     return 'ok';
1.80      www      8911: }
                   8912: 
1.81      www      8913: # --------------------------------------------------------------- Modify a user
1.80      www      8914: 
1.81      www      8915: sub modifyuser {
1.206     matthew  8916:     my ($udom,    $uname, $uid,
                   8917:         $umode,   $upass, $first,
                   8918:         $middle,  $last,  $gene,
1.1058    raeburn  8919:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8920:     $udom= &LONCAPA::clean_domain($udom);
                   8921:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8922:     my $showcandelete = 'none';
                   8923:     if (ref($candelete) eq 'ARRAY') {
                   8924:         if (@{$candelete} > 0) {
                   8925:             $showcandelete = join(', ',@{$candelete});
                   8926:         }
                   8927:     }
1.81      www      8928:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8929:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8930: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8931:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8932:                                      ' desiredhome not specified'). 
1.620     albertel 8933:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8934:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8935:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8936:     my $newuser;
                   8937:     if ($uhome eq 'no_host') {
                   8938:         $newuser = 1;
                   8939:     }
1.80      www      8940: # ----------------------------------------------------------------- Create User
1.406     albertel 8941:     if (($uhome eq 'no_host') && 
                   8942: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8943:         my $unhome='';
1.844     albertel 8944:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8945:             $unhome = $desiredhome;
1.620     albertel 8946: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8947: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8948:         } else { # load balancing routine for determining $unhome
1.81      www      8949:             my $loadm=10000000;
1.841     albertel 8950: 	    my %servers = &get_servers($udom,'library');
                   8951: 	    foreach my $tryserver (keys(%servers)) {
                   8952: 		my $answer=reply('load',$tryserver);
                   8953: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8954: 		    $loadm=$answer;
                   8955: 		    $unhome=$tryserver;
                   8956: 		}
1.80      www      8957: 	    }
                   8958:         }
                   8959:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8960: 	    return 'error: unable to find a home server for '.$uname.
                   8961:                    ' in domain '.$udom;
1.80      www      8962:         }
                   8963:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8964:                          &escape($upass),$unhome);
                   8965: 	unless ($reply eq 'ok') {
                   8966:             return 'error: '.$reply;
                   8967:         }   
1.230     stredwic 8968:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8969:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8970: 	    return 'error: unable verify users home machine.';
1.80      www      8971:         }
1.209     matthew  8972:     }   # End of creation of new user
1.80      www      8973: # ---------------------------------------------------------------------- Add ID
                   8974:     if ($uid) {
                   8975:        $uid=~tr/A-Z/a-z/;
                   8976:        my %uidhash=&idrget($udom,$uname);
1.196     www      8977:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8978:          && (!$forceid)) {
1.80      www      8979: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8980: 	      return 'error: user id "'.$uid.'" does not match '.
                   8981:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8982:           }
                   8983:        } else {
1.1300    raeburn  8984: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      8985:        }
                   8986:     }
                   8987: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8988:     my @tmp=&get('environment',
1.899     raeburn  8989: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8990:                     'permanentemail','inststatus'],
1.134     albertel 8991: 		   $udom,$uname);
1.1075    raeburn  8992:     my (%names,%oldnames);
1.313     matthew  8993:     if ($tmp[0] =~ m/^error:.*/) { 
                   8994:         %names=(); 
                   8995:     } else {
                   8996:         %names = @tmp;
1.1075    raeburn  8997:         %oldnames = %names;
1.313     matthew  8998:     }
1.388     www      8999: #
1.1058    raeburn  9000: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9001: # of users did not contain them), do not overwrite existing values
                   9002: # unless field is in $candelete array ref.  
                   9003: #
                   9004: 
                   9005:     my @fields = ('firstname','middlename','lastname','generation',
                   9006:                   'permanentemail','id');
                   9007:     my %newvalues;
                   9008:     if (ref($candelete) eq 'ARRAY') {
                   9009:         foreach my $field (@fields) {
                   9010:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9011:                 if ($field eq 'firstname') {
                   9012:                     $names{$field} = $first;
                   9013:                 } elsif ($field eq 'middlename') {
                   9014:                     $names{$field} = $middle;
                   9015:                 } elsif ($field eq 'lastname') {
                   9016:                     $names{$field} = $last;
                   9017:                 } elsif ($field eq 'generation') { 
                   9018:                     $names{$field} = $gene;
                   9019:                 } elsif ($field eq 'permanentemail') {
                   9020:                     $names{$field} = $email;
                   9021:                 } elsif ($field eq 'id') {
                   9022:                     $names{$field}  = $uid;
                   9023:                 }
                   9024:             }
                   9025:         }
                   9026:     }
1.388     www      9027:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9028:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9029:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9030:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9031:     if ($email) {
                   9032:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9033:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9034:     }
1.899     raeburn  9035:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9036:     if (defined($inststatus)) {
                   9037:         $names{'inststatus'} = '';
                   9038:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9039:         if (ref($usertypes) eq 'HASH') {
                   9040:             my @okstatuses; 
                   9041:             foreach my $item (split(/:/,$inststatus)) {
                   9042:                 if (defined($usertypes->{$item})) {
                   9043:                     push(@okstatuses,$item);  
                   9044:                 }
                   9045:             }
                   9046:             if (@okstatuses) {
                   9047:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9048:             }
                   9049:         }
                   9050:     }
1.1075    raeburn  9051:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9052:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9053:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9054:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9055:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9056:     } else {
                   9057:         $logmsg .= ' during self creation';
                   9058:     }
1.1075    raeburn  9059:     my $changed;
                   9060:     if ($newuser) {
                   9061:         $changed = 1;
                   9062:     } else {
                   9063:         foreach my $field (@fields) {
                   9064:             if ($names{$field} ne $oldnames{$field}) {
                   9065:                 $changed = 1;
                   9066:                 last;
                   9067:             }
                   9068:         }
                   9069:     }
                   9070:     unless ($changed) {
                   9071:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9072:         &logthis($logmsg);
                   9073:         return 'ok';
                   9074:     }
                   9075:     my $reply = &put('environment', \%names, $udom,$uname);
                   9076:     if ($reply ne 'ok') { 
                   9077:         return 'error: '.$reply;
                   9078:     }
1.1087    raeburn  9079:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9080:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9081:     }
1.1075    raeburn  9082:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9083:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9084:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9085:     &logthis($logmsg);
1.134     albertel 9086:     return 'ok';
1.80      www      9087: }
                   9088: 
1.81      www      9089: # -------------------------------------------------------------- Modify student
1.80      www      9090: 
1.81      www      9091: sub modifystudent {
                   9092:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9093:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314  ! raeburn  9094:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9095:     if (!$cid) {
1.620     albertel 9096: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9097: 	    return 'not_in_class';
                   9098: 	}
1.80      www      9099:     }
                   9100: # --------------------------------------------------------------- Make the user
1.81      www      9101:     my $reply=&modifyuser
1.209     matthew  9102: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9103:          $desiredhome,$email,$inststatus);
1.80      www      9104:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9105:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9106:     # student's environment
1.297     matthew  9107:     $uid = undef if (!$forceid);
1.455     albertel 9108:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9109:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314  ! raeburn  9110:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9111:     return $reply;
                   9112: }
                   9113: 
                   9114: sub modify_student_enrollment {
1.1216    raeburn  9115:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314  ! raeburn  9116:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9117:     my ($cdom,$cnum,$chome);
                   9118:     if (!$cid) {
1.620     albertel 9119: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9120: 	    return 'not_in_class';
                   9121: 	}
1.620     albertel 9122: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9123: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9124:     } else {
                   9125: 	($cdom,$cnum)=split(/_/,$cid);
                   9126:     }
1.620     albertel 9127:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9128:     if (!$chome) {
1.457     raeburn  9129: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9130:     }
1.455     albertel 9131:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9132:     # Make sure the user exists
1.81      www      9133:     my $uhome=&homeserver($uname,$udom);
                   9134:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9135: 	return 'error: no such user';
                   9136:     }
1.297     matthew  9137:     # Get student data if we were not given enough information
                   9138:     if (!defined($first)  || $first  eq '' || 
                   9139:         !defined($last)   || $last   eq '' || 
                   9140:         !defined($uid)    || $uid    eq '' || 
                   9141:         !defined($middle) || $middle eq '' || 
                   9142:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9143:         # They did not supply us with enough data to enroll the student, so
                   9144:         # we need to pick up more information.
1.297     matthew  9145:         my %tmp = &get('environment',
1.294     matthew  9146:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9147:                        ,$udom,$uname);
                   9148: 
1.800     albertel 9149:         #foreach my $key (keys(%tmp)) {
                   9150:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9151:         #}
1.294     matthew  9152:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9153:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9154:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9155:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9156:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9157:     }
1.556     albertel 9158:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9159:     my $user = "$uname:$udom";
                   9160:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9161:     my $reply=cput('classlist',
1.1148    raeburn  9162: 		   {$user => 
1.1314  ! raeburn  9163: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9164: 		   $cdom,$cnum);
1.1148    raeburn  9165:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9166:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9167:     } else { 
1.81      www      9168: 	return 'error: '.$reply;
                   9169:     }
1.297     matthew  9170:     # Add student role to user
1.83      www      9171:     my $uurl='/'.$cid;
1.81      www      9172:     $uurl=~s/\_/\//g;
                   9173:     if ($usec) {
                   9174: 	$uurl.='/'.$usec;
                   9175:     }
1.1148    raeburn  9176:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9177:                              $selfenroll,$context);
                   9178:     if ($result ne 'ok') {
                   9179:         if ($old_entry{$user} ne '') {
                   9180:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9181:         } else {
                   9182:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9183:         }
                   9184:     }
                   9185:     return $result; 
1.21      www      9186: }
                   9187: 
1.556     albertel 9188: sub format_name {
                   9189:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9190:     my $name;
                   9191:     if ($first ne 'lastname') {
                   9192: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9193:     } else {
                   9194: 	if ($lastname=~/\S/) {
                   9195: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9196: 	    $name=~s/\s+,/,/;
                   9197: 	} else {
                   9198: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9199: 	}
                   9200:     }
                   9201:     $name=~s/^\s+//;
                   9202:     $name=~s/\s+$//;
                   9203:     $name=~s/\s+/ /g;
                   9204:     return $name;
                   9205: }
                   9206: 
1.84      www      9207: # ------------------------------------------------- Write to course preferences
                   9208: 
                   9209: sub writecoursepref {
                   9210:     my ($courseid,%prefs)=@_;
                   9211:     $courseid=~s/^\///;
                   9212:     $courseid=~s/\_/\//g;
                   9213:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9214:     my $chome=homeserver($cnum,$cdomain);
                   9215:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9216: 	return 'error: no such course';
                   9217:     }
                   9218:     my $cstring='';
1.800     albertel 9219:     foreach my $pref (keys(%prefs)) {
                   9220: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9221:     }
1.84      www      9222:     $cstring=~s/\&$//;
                   9223:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9224: }
                   9225: 
                   9226: # ---------------------------------------------------------- Make/modify course
                   9227: 
                   9228: sub createcourse {
1.741     raeburn  9229:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9230:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9231:     $url=&declutter($url);
                   9232:     my $cid='';
1.1028    raeburn  9233:     if ($context eq 'requestcourses') {
                   9234:         my $can_create = 0;
                   9235:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9236:         if ($udom eq $ownerdom) {
                   9237:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9238:                                   $context)) {
                   9239:                 $can_create = 1;
                   9240:             }
                   9241:         } else {
                   9242:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9243:                                            $category);
                   9244:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9245:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9246:                 if (@curr > 0) {
                   9247:                     my @options = qw(approval validate autolimit);
                   9248:                     my $optregex = join('|',@options);
                   9249:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9250:                         $can_create = 1;
                   9251:                     }
                   9252:                 }
                   9253:             }
                   9254:         }
                   9255:         if ($can_create) {
                   9256:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9257:                 unless (&allowed('ccc',$udom)) {
                   9258:                     return 'refused'; 
                   9259:                 }
1.1017    raeburn  9260:             }
                   9261:         } else {
                   9262:             return 'refused';
                   9263:         }
1.1028    raeburn  9264:     } elsif (!&allowed('ccc',$udom)) {
                   9265:         return 'refused';
1.84      www      9266:     }
1.1011    raeburn  9267: # --------------------------------------------------------------- Get Unique ID
                   9268:     my $uname;
                   9269:     if ($cnum =~ /^$match_courseid$/) {
                   9270:         my $chome=&homeserver($cnum,$udom,'true');
                   9271:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9272:             $uname = $cnum;
                   9273:         } else {
1.1038    raeburn  9274:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9275:         }
                   9276:     } else {
1.1038    raeburn  9277:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9278:     }
                   9279:     return $uname if ($uname =~ /^error/);
                   9280: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9281:     if (!defined($course_server)) {
                   9282:         if (defined(&domain($udom,'primary'))) {
                   9283:             $course_server = &domain($udom,'primary');
                   9284:         } else {
                   9285:             $course_server = $env{'user.home'}; 
                   9286:         }
                   9287:     }
                   9288:     my %host_servers =
                   9289:         &Apache::lonnet::get_servers($udom,'library');
                   9290:     unless ($host_servers{$course_server}) {
                   9291:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9292:     }
1.84      www      9293: # ------------------------------------------------------------- Make the course
                   9294:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9295:                       $course_server);
1.84      www      9296:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9297:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9298:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9299: 	return 'error: no such course';
                   9300:     }
1.271     www      9301: # ----------------------------------------------------------------- Course made
1.516     raeburn  9302: # log existence
1.1029    raeburn  9303:     my $now = time;
1.918     raeburn  9304:     my $newcourse = {
                   9305:                     $udom.'_'.$uname => {
1.921     raeburn  9306:                                      description => $description,
                   9307:                                      inst_code   => $inst_code,
                   9308:                                      owner       => $course_owner,
                   9309:                                      type        => $crstype,
1.1029    raeburn  9310:                                      creator     => $env{'user.name'}.':'.
                   9311:                                                     $env{'user.domain'},
                   9312:                                      created     => $now,
                   9313:                                      context     => $context,
1.918     raeburn  9314:                                                 },
                   9315:                     };
1.921     raeburn  9316:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9317: # set toplevel url
1.271     www      9318:     my $topurl=$url;
                   9319:     unless ($nonstandard) {
                   9320: # ------------------------------------------ For standard courses, make top url
                   9321:         my $mapurl=&clutter($url);
1.278     www      9322:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9323:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9324: <map>
                   9325: <resource id="1" type="start"></resource>
                   9326: <resource id="2" src="$mapurl"></resource>
                   9327: <resource id="3" type="finish"></resource>
                   9328: <link index="1" from="1" to="2"></link>
                   9329: <link index="2" from="2" to="3"></link>
                   9330: </map>
                   9331: ENDINITMAP
                   9332:         $topurl=&declutter(
1.638     albertel 9333:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9334:                           );
                   9335:     }
                   9336: # ----------------------------------------------------------- Write preferences
1.84      www      9337:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9338:                      ('description'              => $description,
                   9339:                       'url'                      => $topurl,
                   9340:                       'internal.creator'         => $env{'user.name'}.':'.
                   9341:                                                     $env{'user.domain'},
                   9342:                       'internal.created'         => $now,
                   9343:                       'internal.creationcontext' => $context)
                   9344:                     );
1.84      www      9345:     return '/'.$udom.'/'.$uname;
                   9346: }
                   9347: 
1.1011    raeburn  9348: # ------------------------------------------------------------------- Create ID
                   9349: sub generate_coursenum {
1.1038    raeburn  9350:     my ($udom,$crstype) = @_;
1.1011    raeburn  9351:     my $domdesc = &domain($udom);
                   9352:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9353:     my $first;
                   9354:     if ($crstype eq 'Community') {
                   9355:         $first = '0';
                   9356:     } else {
                   9357:         $first = int(1+rand(9)); 
                   9358:     } 
                   9359:     my $uname=$first.
1.1011    raeburn  9360:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9361:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9362:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9363: # ----------------------------------------------- Make sure that does not exist
                   9364:     my $uhome=&homeserver($uname,$udom,'true');
                   9365:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9366:         if ($crstype eq 'Community') {
                   9367:             $first = '0';
                   9368:         } else {
                   9369:             $first = int(1+rand(9));
                   9370:         }
                   9371:         $uname=$first.
1.1011    raeburn  9372:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9373:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9374:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9375:         $uhome=&homeserver($uname,$udom,'true');
                   9376:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9377:             return 'error: unable to generate unique course-ID';
                   9378:         }
                   9379:     }
                   9380:     return $uname;
                   9381: }
                   9382: 
1.813     albertel 9383: sub is_course {
1.1167    droeschl 9384:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9385:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9386: 
                   9387:     return unless $cdom and $cnum;
                   9388: 
                   9389:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9390:         '.');
                   9391: 
1.1219    raeburn  9392:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9393:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9394: }
                   9395: 
1.1015    raeburn  9396: sub store_userdata {
                   9397:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9398:     my $result;
1.1016    raeburn  9399:     if ($datakey ne '') {
1.1013    raeburn  9400:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9401:             if ($udom eq '' || $uname eq '') {
                   9402:                 $udom = $env{'user.domain'};
                   9403:                 $uname = $env{'user.name'};
                   9404:             }
                   9405:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9406:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9407:                 $result = 'error: no_host';
                   9408:             } else {
                   9409:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9410:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9411: 
                   9412:                 my $namevalue='';
                   9413:                 foreach my $key (keys(%{$storehash})) {
                   9414:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9415:                 }
                   9416:                 $namevalue=~s/\&$//;
1.1224    raeburn  9417:                 unless ($namespace eq 'courserequests') {
                   9418:                     $datakey = &escape($datakey);
                   9419:                 }
1.1105    raeburn  9420:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9421:                                   $namevalue,$uhome);
1.1013    raeburn  9422:             }
                   9423:         } else {
                   9424:             $result = 'error: data to store was not a hash reference'; 
                   9425:         }
                   9426:     } else {
                   9427:         $result= 'error: invalid requestkey'; 
                   9428:     }
                   9429:     return $result;
                   9430: }
                   9431: 
1.21      www      9432: # ---------------------------------------------------------- Assign Custom Role
                   9433: 
                   9434: sub assigncustomrole {
1.957     raeburn  9435:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9436:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9437:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9438: }
                   9439: 
                   9440: # ----------------------------------------------------------------- Revoke Role
                   9441: 
                   9442: sub revokerole {
1.957     raeburn  9443:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9444:     my $now=time;
1.965     raeburn  9445:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9446: }
                   9447: 
                   9448: # ---------------------------------------------------------- Revoke Custom Role
                   9449: 
                   9450: sub revokecustomrole {
1.957     raeburn  9451:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9452:     my $now=time;
1.357     www      9453:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9454:            $deleteflag,$selfenroll,$context);
1.17      www      9455: }
                   9456: 
1.533     banghart 9457: # ------------------------------------------------------------ Disk usage
1.535     albertel 9458: sub diskusage {
1.955     raeburn  9459:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9460:     $directorypath =~ s/\/$//;
                   9461:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9462:                        .&escape($getpropath).':'.&escape($uname).':'
                   9463:                        .&escape($udom),homeserver($uname,$udom));
                   9464:     if ($listing eq 'unknown_cmd') {
                   9465:         if ($getpropath) {
                   9466:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9467:         }
                   9468:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9469:     }
1.514     albertel 9470:     return $listing;
1.512     banghart 9471: }
                   9472: 
1.566     banghart 9473: sub is_locked {
1.1096    raeburn  9474:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9475:     my @check;
                   9476:     my $is_locked;
1.1093    raeburn  9477:     push (@check,$file_name);
1.613     albertel 9478:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9479: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9480:     my ($tmp)=keys(%locked);
                   9481:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9482:     
1.566     banghart 9483:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9484:         $is_locked = 'false';
                   9485:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9486:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9487:                $is_locked = 'true';
1.1096    raeburn  9488:                if (ref($which) eq 'ARRAY') {
                   9489:                    push(@{$which},$entry);
                   9490:                } else {
                   9491:                    last;
                   9492:                }
1.745     raeburn  9493:            }
                   9494:        }
1.566     banghart 9495:     } else {
                   9496:         $is_locked = 'false';
                   9497:     }
1.1093    raeburn  9498:     return $is_locked;
1.566     banghart 9499: }
                   9500: 
1.759     albertel 9501: sub declutter_portfile {
                   9502:     my ($file) = @_;
1.833     albertel 9503:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9504:     return $file;
                   9505: }
                   9506: 
1.559     banghart 9507: # ------------------------------------------------------------- Mark as Read Only
                   9508: 
                   9509: sub mark_as_readonly {
                   9510:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9511:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9512:     my ($tmp)=keys(%current_permissions);
                   9513:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9514:     foreach my $file (@{$files}) {
1.759     albertel 9515: 	$file = &declutter_portfile($file);
1.561     banghart 9516:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9517:     }
1.613     albertel 9518:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9519:     return;
                   9520: }
                   9521: 
1.572     banghart 9522: # ------------------------------------------------------------Save Selected Files
                   9523: 
                   9524: sub save_selected_files {
                   9525:     my ($user, $path, @files) = @_;
                   9526:     my $filename = $user."savedfiles";
1.573     banghart 9527:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9528:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9529:     foreach my $file (@files) {
1.620     albertel 9530:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9531:     }
                   9532:     foreach my $file (@other_files) {
1.574     banghart 9533:         print (OUT $file."\n");
1.572     banghart 9534:     }
1.574     banghart 9535:     close (OUT);
1.572     banghart 9536:     return 'ok';
                   9537: }
                   9538: 
1.574     banghart 9539: sub clear_selected_files {
                   9540:     my ($user) = @_;
                   9541:     my $filename = $user."savedfiles";
1.1117    foxr     9542:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9543:     print (OUT undef);
                   9544:     close (OUT);
                   9545:     return ("ok");    
                   9546: }
                   9547: 
1.572     banghart 9548: sub files_in_path {
                   9549:     my ($user, $path) = @_;
                   9550:     my $filename = $user."savedfiles";
                   9551:     my %return_files;
1.1117    foxr     9552:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9553:     while (my $line_in = <IN>) {
1.574     banghart 9554:         chomp ($line_in);
                   9555:         my @paths_and_file = split (m!/!, $line_in);
                   9556:         my $file_part = pop (@paths_and_file);
                   9557:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9558:         $path_part.='/';
                   9559:         my $path_and_file = $path_part.$file_part;
                   9560:         if ($path_part eq $path) {
                   9561:             $return_files{$file_part}= 'selected';
                   9562:         }
                   9563:     }
1.574     banghart 9564:     close (IN);
                   9565:     return (\%return_files);
1.572     banghart 9566: }
                   9567: 
                   9568: # called in portfolio select mode, to show files selected NOT in current directory
                   9569: sub files_not_in_path {
                   9570:     my ($user, $path) = @_;
                   9571:     my $filename = $user."savedfiles";
                   9572:     my @return_files;
                   9573:     my $path_part;
1.1117    foxr     9574:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9575:     while (my $line = <IN>) {
1.572     banghart 9576:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9577:         my @paths_and_file = split(m|/|, $line);
                   9578:         my $file_part = pop(@paths_and_file);
                   9579:         chomp($file_part);
                   9580:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9581:         $path_part .= '/';
                   9582:         my $path_and_file = $path_part.$file_part;
                   9583:         if ($path_part ne $path) {
1.800     albertel 9584:             push(@return_files, ($path_and_file));
1.572     banghart 9585:         }
                   9586:     }
1.800     albertel 9587:     close(OUT);
1.574     banghart 9588:     return (@return_files);
1.572     banghart 9589: }
                   9590: 
1.1273    raeburn  9591: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9592:  
                   9593: sub portfiles_versioning {
                   9594:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   9595:     my $portfolio_root = '/userfiles/portfolio';
                   9596:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   9597:     foreach my $file (@{$portfiles}) {
                   9598:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   9599:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   9600:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   9601:         my $getpropath = 1;
                   9602:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   9603:                                              $stu_name,$getpropath);
                   9604:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   9605:         my $new_answer = 
                   9606:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   9607:         if ($new_answer ne 'problem getting file') {
                   9608:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   9609:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   9610:                               [$symb,$env{'request.course.id'},'graded']);
                   9611:         }
                   9612:     }
                   9613: }
                   9614: 
                   9615: sub get_next_version {
                   9616:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   9617:     my $version;
                   9618:     if (ref($dir_list) eq 'ARRAY') {
                   9619:         foreach my $row (@{$dir_list}) {
                   9620:             my ($file) = split(/\&/,$row,2);
                   9621:             my ($file_name,$file_version,$file_ext) =
                   9622:                 &file_name_version_ext($file);
                   9623:             if (($file_name eq $answer_name) &&
                   9624:                 ($file_ext eq $answer_ext)) {
                   9625:                      # gets here if filename and extension match,
                   9626:                      # regardless of version
                   9627:                 if ($file_version ne '') {
                   9628:                     # a versioned file is found  so save it for later
                   9629:                     if ($file_version > $version) {
                   9630:                         $version = $file_version;
                   9631:                     }
                   9632:                 }
                   9633:             }
                   9634:         }
                   9635:     }
                   9636:     $version ++;
                   9637:     return($version);
                   9638: }
                   9639: 
                   9640: sub version_selected_portfile {
                   9641:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   9642:     my ($answer_name,$answer_ver,$answer_ext) =
                   9643:         &file_name_version_ext($file_name);
                   9644:     my $new_answer;
                   9645:     $env{'form.copy'} =
                   9646:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   9647:     if($env{'form.copy'} eq '-1') {
                   9648:         $new_answer = 'problem getting file';
                   9649:     } else {
                   9650:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   9651:         my $copy_result = 
                   9652:             &finishuserfileupload($stu_name,$domain,'copy',
                   9653:                                   '/portfolio'.$directory.$new_answer);
                   9654:     }
                   9655:     undef($env{'form.copy'});
                   9656:     return ($new_answer);
                   9657: }
                   9658: 
                   9659: sub file_name_version_ext {
                   9660:     my ($file)=@_;
                   9661:     my @file_parts = split(/\./, $file);
                   9662:     my ($name,$version,$ext);
                   9663:     if (@file_parts > 1) {
                   9664:         $ext=pop(@file_parts);
                   9665:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   9666:             $version=pop(@file_parts);
                   9667:         }
                   9668:         $name=join('.',@file_parts);
                   9669:     } else {
                   9670:         $name=join('.',@file_parts);
                   9671:     }
                   9672:     return($name,$version,$ext);
                   9673: }
                   9674: 
1.745     raeburn  9675: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9676: 
1.745     raeburn  9677: sub get_portfile_permissions {
                   9678:     my ($domain,$user) = @_;
1.613     albertel 9679:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9680:     my ($tmp)=keys(%current_permissions);
                   9681:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9682:     return \%current_permissions;
                   9683: }
                   9684: 
                   9685: #---------------------------------------------Get portfolio file access controls
                   9686: 
1.749     raeburn  9687: sub get_access_controls {
1.745     raeburn  9688:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9689:     my %access;
                   9690:     my $real_file = $file;
                   9691:     $file =~ s/\.meta$//;
1.745     raeburn  9692:     if (defined($file)) {
1.749     raeburn  9693:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9694:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9695:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9696:             }
                   9697:         }
1.745     raeburn  9698:     } else {
1.749     raeburn  9699:         foreach my $key (keys(%{$current_permissions})) {
                   9700:             if ($key =~ /\0accesscontrol$/) {
                   9701:                 if (defined($group)) {
                   9702:                     if ($key !~ m-^\Q$group\E/-) {
                   9703:                         next;
                   9704:                     }
                   9705:                 }
                   9706:                 my ($fullpath) = split(/\0/,$key);
                   9707:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9708:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9709:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9710:                     }
                   9711:                 }
                   9712:             }
                   9713:         }
                   9714:     }
                   9715:     return %access;
                   9716: }
                   9717: 
                   9718: sub modify_access_controls {
                   9719:     my ($file_name,$changes,$domain,$user)=@_;
                   9720:     my ($outcome,$deloutcome);
                   9721:     my %store_permissions;
                   9722:     my %new_values;
                   9723:     my %new_control;
                   9724:     my %translation;
                   9725:     my @deletions = ();
                   9726:     my $now = time;
                   9727:     if (exists($$changes{'activate'})) {
                   9728:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9729:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9730:             my $numnew = scalar(@newitems);
                   9731:             for (my $i=0; $i<$numnew; $i++) {
                   9732:                 my $newkey = $newitems[$i];
                   9733:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9734:                 if ($newkey =~ /^\d+:/) { 
                   9735:                     $newkey =~ s/^(\d+)/$newid/;
                   9736:                     $translation{$1} = $newid;
                   9737:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9738:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9739:                     $translation{$1} = $newid;
                   9740:                 }
1.749     raeburn  9741:                 $new_values{$file_name."\0".$newkey} = 
                   9742:                                           $$changes{'activate'}{$newitems[$i]};
                   9743:                 $new_control{$newkey} = $now;
                   9744:             }
                   9745:         }
                   9746:     }
                   9747:     my %todelete;
                   9748:     my %changed_items;
                   9749:     foreach my $action ('delete','update') {
                   9750:         if (exists($$changes{$action})) {
                   9751:             if (ref($$changes{$action}) eq 'HASH') {
                   9752:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9753:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9754:                     if ($action eq 'delete') { 
                   9755:                         $todelete{$itemnum} = 1;
                   9756:                     } else {
                   9757:                         $changed_items{$itemnum} = $key;
                   9758:                     }
                   9759:                 }
1.745     raeburn  9760:             }
                   9761:         }
1.749     raeburn  9762:     }
                   9763:     # get lock on access controls for file.
                   9764:     my $lockhash = {
                   9765:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9766:                                                        ':'.$env{'user.domain'},
                   9767:                    }; 
                   9768:     my $tries = 0;
                   9769:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9770:    
1.1288    damieng  9771:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  9772:         $tries ++;
1.1289    damieng  9773:         sleep(0.1);
1.749     raeburn  9774:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9775:     }
                   9776:     if ($gotlock eq 'ok') {
                   9777:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9778:         my ($tmp)=keys(%curr_permissions);
                   9779:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9780:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9781:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9782:             if (ref($curr_controls) eq 'HASH') {
                   9783:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9784:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9785:                     if (defined($todelete{$itemnum})) {
                   9786:                         push(@deletions,$file_name."\0".$control_item);
                   9787:                     } else {
                   9788:                         if (defined($changed_items{$itemnum})) {
                   9789:                             $new_control{$changed_items{$itemnum}} = $now;
                   9790:                             push(@deletions,$file_name."\0".$control_item);
                   9791:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9792:                         } else {
                   9793:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9794:                         }
                   9795:                     }
1.745     raeburn  9796:                 }
                   9797:             }
                   9798:         }
1.970     raeburn  9799:         my ($group);
                   9800:         if (&is_course($domain,$user)) {
                   9801:             ($group,my $file) = split(/\//,$file_name,2);
                   9802:         }
1.749     raeburn  9803:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9804:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9805:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9806:         #  remove lock
                   9807:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9808:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9809:         my $sqlresult =
1.970     raeburn  9810:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9811:                                     $group);
1.749     raeburn  9812:     } else {
                   9813:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9814:     }
1.749     raeburn  9815:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9816: }
                   9817: 
1.827     raeburn  9818: sub make_public_indefinitely {
1.1271    raeburn  9819:     my (@requrl) = @_;
                   9820:     return &automated_portfile_access('public',\@requrl);
                   9821: }
                   9822: 
                   9823: sub automated_portfile_access {
                   9824:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  9825:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   9826:         return 'invalid';
                   9827:     }
1.1271    raeburn  9828:     my %urls;
                   9829:     if (ref($addsref) eq 'ARRAY') {
                   9830:         foreach my $requrl (@{$addsref}) {
                   9831:             if (&is_portfolio_url($requrl)) {
                   9832:                 unless (exists($urls{$requrl})) {
                   9833:                     $urls{$requrl} = 'add';
                   9834:                 }
                   9835:             }
                   9836:         }
                   9837:     }
                   9838:     if (ref($delsref) eq 'ARRAY') {
                   9839:         foreach my $requrl (@{$delsref}) { 
                   9840:             if (&is_portfolio_url($requrl)) {
                   9841:                 unless (exists($urls{$requrl})) {
                   9842:                     $urls{$requrl} = 'delete'; 
                   9843:                 }
                   9844:             }
                   9845:         }
                   9846:     }
                   9847:     unless (keys(%urls)) {
                   9848:         return 'invalid';
                   9849:     }
                   9850:     my $ip;
                   9851:     if ($accesstype eq 'ip') {
                   9852:         if (ref($info) eq 'HASH') {
                   9853:             if ($info->{'ip'} ne '') {
                   9854:                 $ip = $info->{'ip'};
                   9855:             }
                   9856:         }
                   9857:         if ($ip eq '') {
                   9858:             return 'invalid';
                   9859:         }
                   9860:     }
                   9861:     my $errors;
1.827     raeburn  9862:     my $now = time;
1.1271    raeburn  9863:     my %current_perms;
                   9864:     foreach my $requrl (sort(keys(%urls))) {
                   9865:         my $action;
                   9866:         if ($urls{$requrl} eq 'add') {
                   9867:             $action = 'activate';
                   9868:         } else {
                   9869:             $action = 'none';
                   9870:         }
                   9871:         my $aclnum = 0;
1.827     raeburn  9872:         my (undef,$udom,$unum,$file_name,$group) =
                   9873:             &parse_portfolio_url($requrl);
1.1271    raeburn  9874:         unless (exists($current_perms{$unum.':'.$udom})) {
                   9875:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   9876:         }
                   9877:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  9878:                                                    $group,$file_name);
                   9879:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9880:             my ($num,$scope,$end,$start) = 
                   9881:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  9882:             if ($scope eq $accesstype) {
                   9883:                 if (($start <= $now) && ($end == 0)) {
                   9884:                     if ($accesstype eq 'ip') {
                   9885:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   9886:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   9887:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   9888:                                     if ($urls{$requrl} eq 'add') {
                   9889:                                         $action = 'none';
                   9890:                                         last;
                   9891:                                     } else {
                   9892:                                         $action = 'delete';
                   9893:                                         $aclnum = $num;
                   9894:                                         last;
                   9895:                                     }
                   9896:                                 }
                   9897:                             }
                   9898:                         }
                   9899:                     } elsif ($accesstype eq 'public') {
                   9900:                         if ($urls{$requrl} eq 'add') {
                   9901:                             $action = 'none';
                   9902:                             last;
                   9903:                         } else {
                   9904:                             $action = 'delete';
                   9905:                             $aclnum = $num;
                   9906:                             last;
                   9907:                         }
                   9908:                     }
                   9909:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  9910:                     $action = 'update';
                   9911:                     $aclnum = $num;
1.1271    raeburn  9912:                     last;
1.827     raeburn  9913:                 }
                   9914:             }
                   9915:         }
                   9916:         if ($action eq 'none') {
1.1271    raeburn  9917:             next;
1.827     raeburn  9918:         } else {
                   9919:             my %changes;
                   9920:             my $newend = 0;
                   9921:             my $newstart = $now;
1.1271    raeburn  9922:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  9923:             $changes{$action}{$newkey} = {
1.1271    raeburn  9924:                 type => $accesstype,
1.827     raeburn  9925:                 time => {
                   9926:                     start => $newstart,
                   9927:                     end   => $newend,
                   9928:                 },
                   9929:             };
1.1271    raeburn  9930:             if ($accesstype eq 'ip') {
                   9931:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   9932:             }
1.827     raeburn  9933:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9934:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  9935:             unless ($outcome eq 'ok') {
                   9936:                 $errors .= $outcome.' ';
                   9937:             }
1.827     raeburn  9938:         }
1.1271    raeburn  9939:     }
                   9940:     if ($errors) {
                   9941:         $errors =~ s/\s$//;
                   9942:         return $errors;
1.827     raeburn  9943:     } else {
1.1271    raeburn  9944:         return 'ok';
1.827     raeburn  9945:     }
                   9946: }
                   9947: 
1.745     raeburn  9948: #------------------------------------------------------Get Marked as Read Only
                   9949: 
                   9950: sub get_marked_as_readonly {
                   9951:     my ($domain,$user,$what,$group) = @_;
                   9952:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9953:     my @readonly_files;
1.629     banghart 9954:     my $cmp1=$what;
                   9955:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9956:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9957:         if (defined($group)) {
                   9958:             if ($file_name !~ m-^\Q$group\E/-) {
                   9959:                 next;
                   9960:             }
                   9961:         }
1.561     banghart 9962:         if (ref($value) eq "ARRAY"){
                   9963:             foreach my $stored_what (@{$value}) {
1.629     banghart 9964:                 my $cmp2=$stored_what;
1.759     albertel 9965:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9966:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9967:                 }
1.629     banghart 9968:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9969:                     push(@readonly_files, $file_name);
1.745     raeburn  9970:                     last;
1.563     banghart 9971:                 } elsif (!defined($what)) {
                   9972:                     push(@readonly_files, $file_name);
1.745     raeburn  9973:                     last;
1.561     banghart 9974:                 }
                   9975:             }
1.745     raeburn  9976:         }
1.561     banghart 9977:     }
                   9978:     return @readonly_files;
                   9979: }
1.577     banghart 9980: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9981: 
1.577     banghart 9982: sub get_marked_as_readonly_hash {
1.745     raeburn  9983:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9984:     my %readonly_files;
1.745     raeburn  9985:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9986:         if (defined($group)) {
                   9987:             if ($file_name !~ m-^\Q$group\E/-) {
                   9988:                 next;
                   9989:             }
                   9990:         }
1.577     banghart 9991:         if (ref($value) eq "ARRAY"){
                   9992:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9993:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9994:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9995:                         if ($lock_descriptor eq 'graded') {
                   9996:                             $readonly_files{$file_name} = 'graded';
                   9997:                         } elsif ($lock_descriptor eq 'handback') {
                   9998:                             $readonly_files{$file_name} = 'handback';
                   9999:                         } else {
                   10000:                             if (!exists($readonly_files{$file_name})) {
                   10001:                                 $readonly_files{$file_name} = 'locked';
                   10002:                             }
                   10003:                         }
1.745     raeburn  10004:                     }
1.750     banghart 10005:                 } 
1.577     banghart 10006:             }
                   10007:         } 
                   10008:     }
                   10009:     return %readonly_files;
                   10010: }
1.559     banghart 10011: # ------------------------------------------------------------ Unmark as Read Only
                   10012: 
                   10013: sub unmark_as_readonly {
1.629     banghart 10014:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10015:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10016:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10017:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10018:     my $symb_crs = $what;
                   10019:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10020:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10021:     my ($tmp)=keys(%current_permissions);
                   10022:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10023:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10024:     foreach my $file (@readonly_files) {
1.759     albertel 10025: 	my $clean_file = &declutter_portfile($file);
                   10026: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10027: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10028:         my @new_locks;
                   10029:         my @del_keys;
                   10030:         if (ref($current_locks) eq "ARRAY"){
                   10031:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10032:                 my $compare=$locker;
1.749     raeburn  10033:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10034:                     $compare=join('',@{$locker});
1.746     raeburn  10035:                     if ($compare ne $symb_crs) {
                   10036:                         push(@new_locks, $locker);
                   10037:                     }
1.563     banghart 10038:                 }
                   10039:             }
1.650     albertel 10040:             if (scalar(@new_locks) > 0) {
1.563     banghart 10041:                 $current_permissions{$file} = \@new_locks;
                   10042:             } else {
                   10043:                 push(@del_keys, $file);
1.613     albertel 10044:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10045:                 delete($current_permissions{$file});
1.563     banghart 10046:             }
                   10047:         }
1.561     banghart 10048:     }
1.613     albertel 10049:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10050:     return;
                   10051: }
1.512     banghart 10052: 
1.17      www      10053: # ------------------------------------------------------------ Directory lister
                   10054: 
                   10055: sub dirlist {
1.955     raeburn  10056:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10057:     $uri=~s/^\///;
                   10058:     $uri=~s/\/$//;
1.253     stredwic 10059:     my ($udom, $uname);
1.955     raeburn  10060:     if ($getuserdir) {
1.253     stredwic 10061:         $udom = $userdomain;
                   10062:         $uname = $username;
1.955     raeburn  10063:     } else {
                   10064:         (undef,$udom,$uname)=split(/\//,$uri);
                   10065:         if(defined($userdomain)) {
                   10066:             $udom = $userdomain;
                   10067:         }
                   10068:         if(defined($username)) {
                   10069:             $uname = $username;
                   10070:         }
1.253     stredwic 10071:     }
1.955     raeburn  10072:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10073: 
1.955     raeburn  10074:     $dirRoot = $perlvar{'lonDocRoot'};
                   10075:     if (defined($getpropath)) {
                   10076:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10077:         $dirRoot =~ s/\/$//;
1.955     raeburn  10078:     } elsif (defined($getuserdir)) {
                   10079:         my $subdir=$uname.'__';
                   10080:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10081:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10082:                    ."/$udom/$subdir/$uname";
                   10083:     } elsif (defined($alternateRoot)) {
                   10084:         $dirRoot = $alternateRoot;
1.751     banghart 10085:     }
1.253     stredwic 10086: 
                   10087:     if($udom) {
                   10088:         if($uname) {
1.1135    raeburn  10089:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10090:             if ($uhome eq 'no_host') {
                   10091:                 return ([],'no_host');
                   10092:             }
1.955     raeburn  10093:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10094:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10095:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10096:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10097:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10098:             } else {
                   10099:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10100:             }
1.605     matthew  10101:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10102:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10103:                 @listing_results = split(/:/,$listing);
                   10104:             } else {
                   10105:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10106:             }
1.1135    raeburn  10107:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10108:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10109:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10110:                 return ([],$listing);
                   10111:             } else {
                   10112:                 return (\@listing_results);
1.1135    raeburn  10113:             }
1.955     raeburn  10114:         } elsif(!$alternateRoot) {
1.1136    raeburn  10115:             my (%allusers,%listerror);
1.841     albertel 10116: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10117:  	    foreach my $tryserver (keys(%servers)) {
                   10118:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10119:                                   &escape($udom),$tryserver);
                   10120:                 if ($listing eq 'unknown_cmd') {
                   10121: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10122: 				      $udom, $tryserver);
                   10123:                 } else {
                   10124:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10125:                 }
1.841     albertel 10126: 		if ($listing eq 'unknown_cmd') {
                   10127: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10128: 				      $udom, $tryserver);
                   10129: 		    @listing_results = split(/:/,$listing);
                   10130: 		} else {
                   10131: 		    @listing_results =
                   10132: 			map { &unescape($_); } split(/:/,$listing);
                   10133: 		}
1.1136    raeburn  10134:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10135:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10136:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10137:                     $listerror{$tryserver} = $listing;
                   10138:                 } else {
1.841     albertel 10139: 		    foreach my $line (@listing_results) {
                   10140: 			my ($entry) = split(/&/,$line,2);
                   10141: 			$allusers{$entry} = 1;
                   10142: 		    }
                   10143: 		}
1.253     stredwic 10144:             }
1.1136    raeburn  10145:             my @alluserslist=();
1.800     albertel 10146:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10147:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10148:             }
1.1136    raeburn  10149:             return (\@alluserslist);
1.253     stredwic 10150:         } else {
1.1136    raeburn  10151:             return ([],'missing username');
1.253     stredwic 10152:         }
1.955     raeburn  10153:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10154:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10155:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10156:         return (\@all_domains);
1.955     raeburn  10157:     } else {
1.1136    raeburn  10158:         return ([],'missing domain');
1.275     stredwic 10159:     }
                   10160: }
                   10161: 
                   10162: # --------------------------------------------- GetFileTimestamp
                   10163: # This function utilizes dirlist and returns the date stamp for
                   10164: # when it was last modified.  It will also return an error of -1
                   10165: # if an error occurs
                   10166: 
                   10167: sub GetFileTimestamp {
1.955     raeburn  10168:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10169:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10170:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10171:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10172:                                     undef,$getuserdir);
                   10173:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10174:         return -1;
                   10175:     }
                   10176:     if (ref($fileref) eq 'ARRAY') {
                   10177:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10178:         # @stats contains first the filename, then the stat output
                   10179:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10180:     } else {
                   10181:         return -1;
1.253     stredwic 10182:     }
1.26      www      10183: }
                   10184: 
1.712     albertel 10185: sub stat_file {
                   10186:     my ($uri) = @_;
1.787     albertel 10187:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10188: 
1.955     raeburn  10189:     my ($udom,$uname,$file);
1.712     albertel 10190:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10191: 	($udom,$uname,$file) =
1.811     albertel 10192: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10193: 	$file = 'userfiles/'.$file;
                   10194:     }
                   10195:     if ($uri =~ m-^/res/-) {
                   10196: 	($udom,$uname) = 
1.807     albertel 10197: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10198: 	$file = $uri;
                   10199:     }
                   10200: 
                   10201:     if (!$udom || !$uname || !$file) {
                   10202: 	# unable to handle the uri
                   10203: 	return ();
                   10204:     }
1.956     raeburn  10205:     my $getpropath;
                   10206:     if ($file =~ /^userfiles\//) {
                   10207:         $getpropath = 1;
                   10208:     }
1.1136    raeburn  10209:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10210:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10211:         return ();
                   10212:     } else {
                   10213:         if (ref($listref) eq 'ARRAY') {
                   10214:             my @stats = split('&',$listref->[0]);
                   10215: 	    shift(@stats); #filename is first
                   10216: 	    return @stats;
                   10217:         }
1.712     albertel 10218:     }
                   10219:     return ();
                   10220: }
                   10221: 
1.1313    raeburn  10222: # --------------------------------------------------------- recursedirs
                   10223: # Recursive function to traverse either a specific user's Authoring Space
                   10224: # or corresponding Published Resource Space, and populate the hash ref:
                   10225: # $dirhashref with URLs of all directories, and if $filehashref hash
                   10226: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   10227: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   10228: # files in Authoring Space.
                   10229: #
                   10230: # Inputs:
                   10231: #
                   10232: # $is_home - true if current server is home server for user's space
                   10233: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   10234: # $docroot - Document root (i.e., /home/httpd/html
                   10235: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   10236: # $relpath - Current path (relative to top level).
                   10237: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   10238: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   10239: #
                   10240: # Returns: nothing
                   10241: #
                   10242: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   10243: #
                   10244: # Currently used by interface/londocs.pm to create linked select boxes for
                   10245: # directory and filename to import a Course "Author" resource into a course, and
                   10246: # also to create linked select boxes for Authoring Space and Directory to choose
                   10247: # save location for creation of a new "standard" problem from the Course Editor.
                   10248: #
                   10249: 
                   10250: sub recursedirs {
                   10251:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   10252:     return unless (ref($dirhashref) eq 'HASH');
                   10253:     my $currpath = $docroot.$toppath;
                   10254:     if ($relpath) {
                   10255:         $currpath .= "/$relpath";
                   10256:     }
                   10257:     my $savefile;
                   10258:     if (ref($filehashref)) {
                   10259:         $savefile = 1;
                   10260:     }
                   10261:     if ($is_home) {
                   10262:         if (opendir(my $dirh,$currpath)) {
                   10263:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   10264:                 next if ($item eq '');
                   10265:                 if (-d "$currpath/$item") {
                   10266:                     my $newpath;
                   10267:                     if ($relpath) {
                   10268:                         $newpath = "$relpath/$item";
                   10269:                     } else {
                   10270:                         $newpath = $item;
                   10271:                     }
                   10272:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10273:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10274:                 } elsif ($savefile) {
                   10275:                     if ($context eq 'priv') {
                   10276:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10277:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10278:                         }
                   10279:                     } else {
                   10280:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   10281:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10282:                         }
                   10283:                     }
                   10284:                 }
                   10285:             }
                   10286:             closedir($dirh);
                   10287:         }
                   10288:     } else {
                   10289:         my ($dirlistref,$listerror) =
                   10290:             &dirlist($toppath.$relpath);
                   10291:         my @dir_lines;
                   10292:         my $dirptr=16384;
                   10293:         if (ref($dirlistref) eq 'ARRAY') {
                   10294:             foreach my $dir_line (sort
                   10295:                               {
                   10296:                                   my ($afile)=split('&',$a,2);
                   10297:                                   my ($bfile)=split('&',$b,2);
                   10298:                                   return (lc($afile) cmp lc($bfile));
                   10299:                               } (@{$dirlistref})) {
                   10300:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   10301:                     split(/\&/,$dir_line,16);
                   10302:                 $item =~ s/\s+$//;
                   10303:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   10304:                 if ($dirptr&$testdir) {
                   10305:                     my $newpath;
                   10306:                     if ($relpath) {
                   10307:                         $newpath = "$relpath/$item";
                   10308:                     } else {
                   10309:                         $relpath = '/';
                   10310:                         $newpath = $item;
                   10311:                     }
                   10312:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10313:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10314:                 } elsif ($savefile) {
                   10315:                     if ($context eq 'priv') {
                   10316:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10317:                             $filehashref->{$relpath}{$item} = 1;
                   10318:                         }
                   10319:                     } else {
                   10320:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   10321:                             $filehashref->{$relpath}{$item} = 1;
                   10322:                         }
                   10323:                     }
                   10324:                 }
                   10325:             }
                   10326:         }
                   10327:     }
                   10328:     return;
                   10329: }
                   10330: 
1.26      www      10331: # -------------------------------------------------------- Value of a Condition
                   10332: 
1.713     albertel 10333: # gets the value of a specific preevaluated condition
                   10334: #    stored in the string  $env{user.state.<cid>}
                   10335: # or looks up a condition reference in the bighash and if if hasn't
                   10336: # already been evaluated recurses into docondval to get the value of
                   10337: # the condition, then memoizing it to 
                   10338: #   $env{user.state.<cid>.<condition>}
1.40      www      10339: sub directcondval {
                   10340:     my $number=shift;
1.620     albertel 10341:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10342: 	&Apache::lonuserstate::evalstate();
                   10343:     }
1.713     albertel 10344:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10345: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10346:     } elsif ($number =~ /^_/) {
                   10347: 	my $sub_condition;
                   10348: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10349: 		&GDBM_READER(),0640)) {
                   10350: 	    $sub_condition=$bighash{'conditions'.$number};
                   10351: 	    untie(%bighash);
                   10352: 	}
                   10353: 	my $value = &docondval($sub_condition);
1.949     raeburn  10354: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10355: 	return $value;
                   10356:     }
1.620     albertel 10357:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10358:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10359:     } else {
                   10360:        return 2;
                   10361:     }
                   10362: }
                   10363: 
1.713     albertel 10364: # get the collection of conditions for this resource
1.26      www      10365: sub condval {
                   10366:     my $condidx=shift;
1.54      www      10367:     my $allpathcond='';
1.713     albertel 10368:     foreach my $cond (split(/\|/,$condidx)) {
                   10369: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10370: 	    $allpathcond.=
                   10371: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10372: 	}
1.191     harris41 10373:     }
1.54      www      10374:     $allpathcond=~s/\|$//;
1.713     albertel 10375:     return &docondval($allpathcond);
                   10376: }
                   10377: 
                   10378: #evaluates an expression of conditions
                   10379: sub docondval {
                   10380:     my ($allpathcond) = @_;
                   10381:     my $result=0;
                   10382:     if ($env{'request.course.id'}
                   10383: 	&& defined($allpathcond)) {
                   10384: 	my $operand='|';
                   10385: 	my @stack;
                   10386: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10387: 	    if ($chunk eq '(') {
                   10388: 		push @stack,($operand,$result);
                   10389: 	    } elsif ($chunk eq ')') {
                   10390: 		my $before=pop @stack;
                   10391: 		if (pop @stack eq '&') {
                   10392: 		    $result=$result>$before?$before:$result;
                   10393: 		} else {
                   10394: 		    $result=$result>$before?$result:$before;
                   10395: 		}
                   10396: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10397: 		$operand=$chunk;
                   10398: 	    } else {
                   10399: 		my $new=directcondval($chunk);
                   10400: 		if ($operand eq '&') {
                   10401: 		    $result=$result>$new?$new:$result;
                   10402: 		} else {
                   10403: 		    $result=$result>$new?$result:$new;
                   10404: 		}
                   10405: 	    }
                   10406: 	}
1.26      www      10407:     }
                   10408:     return $result;
1.421     albertel 10409: }
                   10410: 
                   10411: # ---------------------------------------------------- Devalidate courseresdata
                   10412: 
                   10413: sub devalidatecourseresdata {
                   10414:     my ($coursenum,$coursedomain)=@_;
                   10415:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10416:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10417: }
                   10418: 
1.763     www      10419: 
1.200     www      10420: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10421: #
                   10422: #  Parameters:
                   10423: #      $coursenum    - Number of the course.
                   10424: #      $coursedomain - Domain at which the course was created.
                   10425: #  Returns:
                   10426: #     A hash of the course parameters along (I think) with timestamps
                   10427: #     and version info.
1.877     foxr     10428: 
1.624     albertel 10429: sub get_courseresdata {
                   10430:     my ($coursenum,$coursedomain)=@_;
1.200     www      10431:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10432:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10433:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10434:     my %dumpreply;
1.417     albertel 10435:     unless (defined($cached)) {
1.624     albertel 10436: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10437: 	$result=\%dumpreply;
1.251     albertel 10438: 	my ($tmp) = keys(%dumpreply);
                   10439: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10440: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10441: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10442: 	    return $tmp;
1.416     albertel 10443: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10444: 	    $result=undef;
1.599     albertel 10445: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10446: 	}
                   10447:     }
1.624     albertel 10448:     return $result;
                   10449: }
                   10450: 
1.633     albertel 10451: sub devalidateuserresdata {
                   10452:     my ($uname,$udom)=@_;
                   10453:     my $hashid="$udom:$uname";
                   10454:     &devalidate_cache_new('userres',$hashid);
                   10455: }
                   10456: 
1.624     albertel 10457: sub get_userresdata {
                   10458:     my ($uname,$udom)=@_;
                   10459:     #most student don\'t have any data set, check if there is some data
                   10460:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10461: 
                   10462:     my $hashid="$udom:$uname";
                   10463:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10464:     if (!defined($cached)) {
                   10465: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10466: 	$result=\%resourcedata;
                   10467: 	&do_cache_new('userres',$hashid,$result,600);
                   10468:     }
                   10469:     my ($tmp)=keys(%$result);
                   10470:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10471: 	return $result;
                   10472:     }
                   10473:     #error 2 occurs when the .db doesn't exist
                   10474:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  10475:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10476: 	    &logthis("<font color=\"blue\">WARNING:".
                   10477: 		     " Trying to get resource data for ".
                   10478: 		     $uname." at ".$udom.": ".
                   10479: 		     $tmp."</font>");
                   10480:         }
1.624     albertel 10481:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10482: 	#&EXT_cache_set($udom,$uname);
                   10483: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10484: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10485:     }
                   10486:     return $tmp;
                   10487: }
1.879     foxr     10488: #----------------------------------------------- resdata - return resource data
                   10489: #  Purpose:
                   10490: #    Return resource data for either users or for a course.
                   10491: #  Parameters:
                   10492: #     $name      - Course/user name.
                   10493: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  10494: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  10495: #     $mapp      - decluttered URL of enclosing map  
                   10496: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   10497: #     $recurseup - Ref to array of map URLs, starting with map containing
                   10498: #                  $mapp up through hierarchy of nested maps to top level map.  
                   10499: #     $courseid  - CourseID (first part of param identifier).
                   10500: #     $modifier  - Middle part of param identifier.
                   10501: #     $what      - Last part of param identifier.
1.879     foxr     10502: #     @which     - Array of names of resources desired.
                   10503: #  Returns:
                   10504: #     The value of the first reasource in @which that is found in the
                   10505: #     resource hash.
                   10506: #  Exceptional Conditions:
                   10507: #     If the $type passed in is not valid (not the string 'course' or 
                   10508: #     'user', an undefined  reference is returned.
                   10509: #     If none of the resources are found, an undef is returned
1.624     albertel 10510: sub resdata {
1.1301    raeburn  10511:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   10512:         $modifier,$what,@which)=@_;
1.624     albertel 10513:     my $result;
                   10514:     if ($type eq 'course') {
                   10515: 	$result=&get_courseresdata($name,$domain);
                   10516:     } elsif ($type eq 'user') {
                   10517: 	$result=&get_userresdata($name,$domain);
                   10518:     }
                   10519:     if (!ref($result)) { return $result; }    
1.251     albertel 10520:     foreach my $item (@which) {
1.1301    raeburn  10521:         if ($item->[1] eq 'course') {
                   10522:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   10523:                 unless ($$recursed) {
1.1302    raeburn  10524:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  10525:                     $$recursed = 1;
                   10526:                 }
                   10527:                 foreach my $item (@${recurseup}) {
                   10528:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   10529:                     last if (defined($result->{$norecursechk}));
                   10530:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   10531:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   10532:                 }
                   10533:             }
                   10534:         }
                   10535:         if (defined($result->{$item->[0]})) {
1.927     albertel 10536: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10537: 	}
1.250     albertel 10538:     }
1.291     albertel 10539:     return undef;
1.200     www      10540: }
                   10541: 
1.1298    raeburn  10542: sub get_domain_ltitools {
                   10543:     my ($cdom) = @_;
                   10544:     my %ltitools;
                   10545:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   10546:     if (defined($cached)) {
                   10547:         if (ref($result) eq 'HASH') {
                   10548:             %ltitools = %{$result};
                   10549:         }
                   10550:     } else {
                   10551:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   10552:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   10553:             %ltitools = %{$domconfig{'ltitools'}};
                   10554:         }
                   10555:         my $cachetime = 24*60*60;
                   10556:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   10557:     }
                   10558:     return %ltitools;
                   10559: }
                   10560: 
1.1236    raeburn  10561: sub get_numsuppfiles {
                   10562:     my ($cnum,$cdom,$ignorecache)=@_;
                   10563:     my $hashid=$cnum.':'.$cdom;
                   10564:     my ($suppcount,$cached);
                   10565:     unless ($ignorecache) {
                   10566:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10567:     }
                   10568:     unless (defined($cached)) {
                   10569:         my $chome=&homeserver($cnum,$cdom);
                   10570:         unless ($chome eq 'no_host') {
                   10571:             ($suppcount,my $errors) = (0,0);
                   10572:             my $suppmap = 'supplemental.sequence';
                   10573:             ($suppcount,$errors) = 
                   10574:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10575:         }
                   10576:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10577:     }
                   10578:     return $suppcount;
                   10579: }
                   10580: 
1.379     matthew  10581: #
                   10582: # EXT resource caching routines
                   10583: #
                   10584: 
1.1302    raeburn  10585: {
                   10586: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   10587: #
                   10588: # The course for which we cache
                   10589: my $cachedmapkey='';
                   10590: # The cached recursive maps for this course
                   10591: my %cachedmaps=();
                   10592: # When this was last done
                   10593: my $cachedmaptime='';
                   10594: 
1.379     matthew  10595: sub clear_EXT_cache_status {
1.383     albertel 10596:     &delenv('cache.EXT.');
1.379     matthew  10597: }
                   10598: 
                   10599: sub EXT_cache_status {
                   10600:     my ($target_domain,$target_user) = @_;
1.383     albertel 10601:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10602:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10603:         # We know already the user has no data
                   10604:         return 1;
                   10605:     } else {
                   10606:         return 0;
                   10607:     }
                   10608: }
                   10609: 
                   10610: sub EXT_cache_set {
                   10611:     my ($target_domain,$target_user) = @_;
1.383     albertel 10612:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10613:     #&appenv({$cachename => time});
1.379     matthew  10614: }
                   10615: 
1.28      www      10616: # --------------------------------------------------------- Value of a Variable
1.58      www      10617: sub EXT {
1.715     albertel 10618: 
1.1228    raeburn  10619:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10620:     unless ($varname) { return ''; }
1.218     albertel 10621:     #get real user name/domain, courseid and symb
                   10622:     my $courseid;
1.359     albertel 10623:     my $publicuser;
1.427     www      10624:     if ($symbparm) {
                   10625: 	$symbparm=&get_symb_from_alias($symbparm);
                   10626:     }
1.218     albertel 10627:     if (!($uname && $udom)) {
1.790     albertel 10628:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10629:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10630:     } else {
1.620     albertel 10631: 	$courseid=$env{'request.course.id'};
1.218     albertel 10632:     }
1.48      www      10633:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10634:     my $rest;
1.320     albertel 10635:     if (defined($therest[0])) {
1.48      www      10636:        $rest=join('.',@therest);
                   10637:     } else {
                   10638:        $rest='';
                   10639:     }
1.320     albertel 10640: 
1.57      www      10641:     my $qualifierrest=$qualifier;
                   10642:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10643:     my $spacequalifierrest=$space;
                   10644:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10645:     if ($realm eq 'user') {
1.48      www      10646: # --------------------------------------------------------------- user.resource
                   10647: 	if ($space eq 'resource') {
1.651     albertel 10648: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10649: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10650: 		 &&
1.744     albertel 10651: 		 ($symbparm eq &symbread()) ) {	
                   10652: 		# if we are in the middle of processing the resource the
                   10653: 		# get the value we are planning on committing
                   10654:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10655:                     return $Apache::lonhomework::results{$qualifierrest};
                   10656:                 } else {
                   10657:                     return $Apache::lonhomework::history{$qualifierrest};
                   10658:                 }
1.335     albertel 10659: 	    } else {
1.359     albertel 10660: 		my %restored;
1.620     albertel 10661: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10662: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10663: 		} else {
                   10664: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10665: 		}
1.335     albertel 10666: 		return $restored{$qualifierrest};
                   10667: 	    }
1.48      www      10668: # ----------------------------------------------------------------- user.access
                   10669:         } elsif ($space eq 'access') {
1.218     albertel 10670: 	    # FIXME - not supporting calls for a specific user
1.48      www      10671:             return &allowed($qualifier,$rest);
                   10672: # ------------------------------------------ user.preferences, user.environment
                   10673:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10674: 	    if (($uname eq $env{'user.name'}) &&
                   10675: 		($udom eq $env{'user.domain'})) {
                   10676: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10677: 	    } else {
1.359     albertel 10678: 		my %returnhash;
                   10679: 		if (!$publicuser) {
                   10680: 		    %returnhash=&userenvironment($udom,$uname,
                   10681: 						 $qualifierrest);
                   10682: 		}
1.218     albertel 10683: 		return $returnhash{$qualifierrest};
                   10684: 	    }
1.48      www      10685: # ----------------------------------------------------------------- user.course
                   10686:         } elsif ($space eq 'course') {
1.218     albertel 10687: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10688:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10689: # ------------------------------------------------------------------- user.role
                   10690:         } elsif ($space eq 'role') {
1.218     albertel 10691: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10692:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10693:             if ($qualifier eq 'value') {
                   10694: 		return $role;
                   10695:             } elsif ($qualifier eq 'extent') {
                   10696:                 return $where;
                   10697:             }
                   10698: # ----------------------------------------------------------------- user.domain
                   10699:         } elsif ($space eq 'domain') {
1.218     albertel 10700:             return $udom;
1.48      www      10701: # ------------------------------------------------------------------- user.name
                   10702:         } elsif ($space eq 'name') {
1.218     albertel 10703:             return $uname;
1.48      www      10704: # ---------------------------------------------------- Any other user namespace
1.29      www      10705:         } else {
1.359     albertel 10706: 	    my %reply;
                   10707: 	    if (!$publicuser) {
                   10708: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10709: 	    }
                   10710: 	    return $reply{$qualifierrest};
1.48      www      10711:         }
1.236     www      10712:     } elsif ($realm eq 'query') {
                   10713: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10714:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10715: 						[$spacequalifierrest]);
1.620     albertel 10716: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10717:    } elsif ($realm eq 'request') {
1.48      www      10718: # ------------------------------------------------------------- request.browser
                   10719:         if ($space eq 'browser') {
1.1145    bisitz   10720:             return $env{'browser.'.$qualifier};
1.57      www      10721: # ------------------------------------------------------------ request.filename
                   10722:         } else {
1.620     albertel 10723:             return $env{'request.'.$spacequalifierrest};
1.29      www      10724:         }
1.28      www      10725:     } elsif ($realm eq 'course') {
1.48      www      10726: # ---------------------------------------------------------- course.description
1.620     albertel 10727:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10728:     } elsif ($realm eq 'resource') {
1.165     www      10729: 
1.620     albertel 10730: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10731: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10732: 	}
1.693     albertel 10733: 
1.1232    raeburn  10734:         if ($qualifier eq '') {
                   10735: 	    if ($space eq 'title') {
                   10736: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10737: 	        return &gettitle($symbparm);
                   10738: 	    }
1.693     albertel 10739: 	
1.1232    raeburn  10740: 	    if ($space eq 'map') {
                   10741: 	        my ($map) = &decode_symb($symbparm);
                   10742: 	        return &symbread($map);
                   10743: 	    }
                   10744:             if ($space eq 'maptitle') {
                   10745:                 my ($map) = &decode_symb($symbparm);
                   10746:                 return &gettitle($map);
                   10747:             }
                   10748: 	    if ($space eq 'filename') {
                   10749: 	        if ($symbparm) {
                   10750: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10751: 	        }
                   10752: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10753: 	    }
1.1232    raeburn  10754: 
1.1233    raeburn  10755:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10756:                 if ($space eq 'visibleparts') {
                   10757:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10758:                     my $item;
                   10759:                     if (ref($navmap)) {
                   10760:                         my $res = $navmap->getBySymb($symbparm);
                   10761:                         my $parts = $res->parts();
                   10762:                         if (ref($parts) eq 'ARRAY') {
                   10763:                             $item = join(',',@{$parts});
                   10764:                         }
                   10765:                         undef($navmap);
1.1232    raeburn  10766:                     }
1.1233    raeburn  10767:                     return $item;
1.1232    raeburn  10768:                 }
                   10769:             }
                   10770:         }
1.693     albertel 10771: 
1.1301    raeburn  10772: 	my ($section, $group, @groups, @recurseup, $recursed);
                   10773: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  10774:         if (($courseid eq '') && ($cid)) {
                   10775:             $courseid = $cid;
                   10776:         }
                   10777: 	if (($symbparm && $courseid) && 
                   10778: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      10779: 
1.218     albertel 10780: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10781: 
1.60      www      10782: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10783: 	    my $symbp=$symbparm;
1.1301    raeburn  10784: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10785: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  10786:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 10787: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 10788: 	    if (($env{'user.name'} eq $uname) &&
                   10789: 		($env{'user.domain'} eq $udom)) {
                   10790: 		$section=$env{'request.course.sec'};
1.733     raeburn  10791:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10792:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10793: 	    } else {
1.539     albertel 10794: 		if (! defined($usection)) {
1.551     albertel 10795: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10796: 		} else {
                   10797: 		    $section = $usection;
                   10798: 		}
1.733     raeburn  10799:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10800: 	    }
                   10801: 
                   10802: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10803: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  10804:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 10805: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10806: 
1.593     albertel 10807: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10808: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  10809:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 10810: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10811: 
1.60      www      10812: # ----------------------------------------------------------- first, check user
1.624     albertel 10813: 
1.1301    raeburn  10814: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   10815:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 10816: 				       ([$courselevelr,'resource'],
                   10817: 					[$courselevelm,'map'     ],
1.1301    raeburn  10818:                                         [$courseleveli,'map'     ],
1.927     albertel 10819: 					[$courselevel, 'course'  ]));
1.931     albertel 10820: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10821: 
1.594     albertel 10822: # ------------------------------------------------ second, check some of course
1.684     raeburn  10823:             my $coursereply;
1.691     raeburn  10824:             if (@groups > 0) {
                   10825:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  10826:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   10827:                                        $mapp,\$recursed,\@recurseup);
                   10828:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  10829:             }
1.96      www      10830: 
1.684     raeburn  10831: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10832: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10833: 				  'course',$mapp,\$recursed,\@recurseup,
                   10834:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 10835: 				  ([$seclevelr,   'resource'],
                   10836: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  10837:                                    [$secleveli,   'map'     ],
1.927     albertel 10838: 				   [$seclevel,    'course'  ],
                   10839: 				   [$courselevelr,'resource']));
                   10840: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10841: 
1.60      www      10842: # ------------------------------------------------------ third, check map parms
1.218     albertel 10843: 	    my %parmhash=();
                   10844: 	    my $thisparm='';
                   10845: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10846: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10847: 		    &GDBM_READER(),0640)) {
1.218     albertel 10848: 		$thisparm=$parmhash{$symbparm};
                   10849: 		untie(%parmhash);
                   10850: 	    }
1.927     albertel 10851: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10852: 	}
1.594     albertel 10853: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  10854:  
                   10855:         my $what = $spacequalifierrest;
                   10856: 	$what=~s/\./\_/;
1.282     albertel 10857: 	my $filename;
                   10858: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10859: 	if ($symbparm) {
1.409     www      10860: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10861: 	} else {
1.620     albertel 10862: 	    $filename=$env{'request.filename'};
1.282     albertel 10863: 	}
1.1301    raeburn  10864: 	my $metadata=&metadata($filename,$what);
1.927     albertel 10865: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301    raeburn  10866: 	$metadata=&metadata($filename,'parameter_'.$what);
1.927     albertel 10867: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10868: 
1.1301    raeburn  10869: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 10870: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10871: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10872: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10873: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10874: 				     'course',$mapp,\$recursed,\@recurseup,
                   10875:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 10876: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  10877:                                       [$courseleveli,'map'   ],
1.927     albertel 10878: 				      [$courselevel, 'course']));
                   10879: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10880: 	}
1.145     www      10881: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10882: 	unless ($space eq '0') {
1.336     albertel 10883: 	    my @parts=split(/_/,$space);
                   10884: 	    my $id=pop(@parts);
                   10885: 	    my $part=join('_',@parts);
                   10886: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10887: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10888: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10889: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10890: 	}
1.395     albertel 10891: 	if ($recurse) { return undef; }
                   10892: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10893: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10894: # ---------------------------------------------------- Any other user namespace
                   10895:     } elsif ($realm eq 'environment') {
                   10896: # ----------------------------------------------------------------- environment
1.620     albertel 10897: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10898: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10899: 	} else {
1.770     albertel 10900: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10901: 		return '';
                   10902: 	    }
1.219     albertel 10903: 	    my %returnhash=&userenvironment($udom,$uname,
                   10904: 					    $spacequalifierrest);
                   10905: 	    return $returnhash{$spacequalifierrest};
                   10906: 	}
1.28      www      10907:     } elsif ($realm eq 'system') {
1.48      www      10908: # ----------------------------------------------------------------- system.time
                   10909: 	if ($space eq 'time') {
                   10910: 	    return time;
                   10911:         }
1.696     albertel 10912:     } elsif ($realm eq 'server') {
                   10913: # ----------------------------------------------------------------- system.time
                   10914: 	if ($space eq 'name') {
                   10915: 	    return $ENV{'SERVER_NAME'};
                   10916:         }
1.28      www      10917:     }
1.48      www      10918:     return '';
1.61      www      10919: }
                   10920: 
1.927     albertel 10921: sub get_reply {
                   10922:     my ($reply_value) = @_;
1.940     raeburn  10923:     if (ref($reply_value) eq 'ARRAY') {
                   10924:         if (wantarray) {
                   10925: 	    return @$reply_value;
                   10926:         }
                   10927:         return $reply_value->[0];
                   10928:     } else {
                   10929:         return $reply_value;
1.927     albertel 10930:     }
                   10931: }
                   10932: 
1.691     raeburn  10933: sub check_group_parms {
1.1301    raeburn  10934:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   10935:         $recursed,$recurseupref) = @_;
                   10936:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   10937:                   [$what,'course']);
                   10938:     my $coursereply;
1.691     raeburn  10939:     foreach my $group (@{$groups}) {
1.1301    raeburn  10940:         my @groupitems = ();
1.691     raeburn  10941:         foreach my $level (@levels) {
1.927     albertel 10942:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10943:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10944:         }
1.1301    raeburn  10945:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10946:                                    $env{'course.'.$courseid.'.domain'},
                   10947:                                    'course',$mapp,$recursed,$recurseupref,
                   10948:                                    $courseid,'.['.$group.'].',$what,
                   10949:                                    @groupitems);
                   10950:         last if (defined($coursereply));
1.691     raeburn  10951:     }
                   10952:     return $coursereply;
                   10953: }
                   10954: 
1.1301    raeburn  10955: sub get_map_hierarchy {
1.1302    raeburn  10956:     my ($mapname,$courseid) = @_;
                   10957:     my @recurseup = ();
1.1301    raeburn  10958:     if ($mapname) {
1.1302    raeburn  10959:         if (($cachedmapkey eq $courseid) &&
                   10960:             (abs($cachedmaptime-time)<5)) {
                   10961:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   10962:                 return @{$cachedmaps{$mapname}};
                   10963:             }
                   10964:         }
1.1301    raeburn  10965:         my $navmap = Apache::lonnavmaps::navmap->new();
                   10966:         if (ref($navmap)) {
                   10967:             @recurseup = $navmap->recurseup_maps($mapname);
                   10968:             undef($navmap);
1.1302    raeburn  10969:             $cachedmaps{$mapname} = \@recurseup;
                   10970:             $cachedmaptime=time;
                   10971:             $cachedmapkey=$courseid;
1.1301    raeburn  10972:         }
                   10973:     }
                   10974:     return @recurseup;
                   10975: }
                   10976: 
1.1302    raeburn  10977: }
                   10978: 
1.691     raeburn  10979: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10980:     my ($courseid,@groups) = @_;
                   10981:     @groups = sort(@groups);
1.691     raeburn  10982:     return @groups;
                   10983: }
                   10984: 
1.395     albertel 10985: sub packages_tab_default {
                   10986:     my ($uri,$varname)=@_;
                   10987:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10988: 
                   10989:     my (@extension,@specifics,$do_default);
                   10990:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10991: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10992: 	if ($pack_type eq 'default') {
                   10993: 	    $do_default=1;
                   10994: 	} elsif ($pack_type eq 'extension') {
                   10995: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10996: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10997: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10998: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10999: 	}
                   11000:     }
                   11001:     # first look for a package that matches the requested part id
                   11002:     foreach my $package (@specifics) {
                   11003: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11004: 	next if ($pack_part ne $part);
                   11005: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11006: 	    return $packagetab{"$pack_type&$name&default"};
                   11007: 	}
                   11008:     }
                   11009:     # look for any possible matching non extension_ package
                   11010:     foreach my $package (@specifics) {
                   11011: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11012: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11013: 	    return $packagetab{"$pack_type&$name&default"};
                   11014: 	}
1.585     albertel 11015: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11016: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11017: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11018: 	}
                   11019:     }
1.738     albertel 11020:     # look for any posible extension_ match
                   11021:     foreach my $package (@extension) {
                   11022: 	my ($package,$pack_type)=@{$package};
                   11023: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11024: 	    return $packagetab{"$pack_type&$name&default"};
                   11025: 	}
                   11026: 	if (defined($packagetab{$package."&$name&default"})) {
                   11027: 	    return $packagetab{$package."&$name&default"};
                   11028: 	}
                   11029:     }
                   11030:     # look for a global default setting
                   11031:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11032: 	return $packagetab{"default&$name&default"};
                   11033:     }
1.395     albertel 11034:     return undef;
                   11035: }
                   11036: 
1.334     albertel 11037: sub add_prefix_and_part {
                   11038:     my ($prefix,$part)=@_;
                   11039:     my $keyroot;
                   11040:     if (defined($prefix) && $prefix !~ /^__/) {
                   11041: 	# prefix that has a part already
                   11042: 	$keyroot=$prefix;
                   11043:     } elsif (defined($prefix)) {
                   11044: 	# prefix that is missing a part
                   11045: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11046:     } else {
                   11047: 	# no prefix at all
                   11048: 	if (defined($part)) { $keyroot='_'.$part; }
                   11049:     }
                   11050:     return $keyroot;
                   11051: }
                   11052: 
1.71      www      11053: # ---------------------------------------------------------------- Get metadata
                   11054: 
1.599     albertel 11055: my %metaentry;
1.1070    www      11056: my %importedpartids;
1.71      www      11057: sub metadata {
1.176     www      11058:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11059:     $uri=&declutter($uri);
1.288     albertel 11060:     # if it is a non metadata possible uri return quickly
1.529     albertel 11061:     if (($uri eq '') || 
                   11062: 	(($uri =~ m|^/*adm/|) && 
1.1298    raeburn  11063: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108    raeburn  11064:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11065: 	return undef;
                   11066:     }
1.1261    raeburn  11067:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11068: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11069: 	return undef;
1.288     albertel 11070:     }
1.73      www      11071:     my $filename=$uri;
                   11072:     $uri=~s/\.meta$//;
1.172     www      11073: #
                   11074: # Is the metadata already cached?
1.177     www      11075: # Look at timestamp of caching
1.172     www      11076: # Everything is cached by the main uri, libraries are never directly cached
                   11077: #
1.428     albertel 11078:     if (!defined($liburi)) {
1.599     albertel 11079: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11080: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11081:     }
                   11082:     {
1.1069    www      11083: # Imported parts would go here
1.1070    www      11084:         my %importedids=();
                   11085:         my @origfileimportpartids=();
1.1069    www      11086:         my $importedparts=0;
1.172     www      11087: #
                   11088: # Is this a recursive call for a library?
                   11089: #
1.599     albertel 11090: #	if (! exists($metacache{$uri})) {
                   11091: #	    $metacache{$uri}={};
                   11092: #	}
1.924     albertel 11093: 	my $cachetime = 60*60;
1.171     www      11094:         if ($liburi) {
                   11095: 	    $liburi=&declutter($liburi);
                   11096:             $filename=$liburi;
1.401     bowersj2 11097:         } else {
1.599     albertel 11098: 	    &devalidate_cache_new('meta',$uri);
                   11099: 	    undef(%metaentry);
1.401     bowersj2 11100: 	}
1.140     www      11101:         my %metathesekeys=();
1.73      www      11102:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11103: 	my $metastring;
1.1140    www      11104: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11105: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11106: 	    $metastring = 
1.929     albertel 11107: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11108: 					  ('grade_target' => 'meta'));
                   11109: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11110: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11111:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11112: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11113: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11114: 	    $metastring=&getfile($file);
1.489     albertel 11115: 	}
1.208     albertel 11116:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11117:         my $token;
1.140     www      11118:         undef %metathesekeys;
1.71      www      11119:         while ($token=$parser->get_token) {
1.339     albertel 11120: 	    if ($token->[0] eq 'S') {
                   11121: 		if (defined($token->[2]->{'package'})) {
1.172     www      11122: #
                   11123: # This is a package - get package info
                   11124: #
1.339     albertel 11125: 		    my $package=$token->[2]->{'package'};
                   11126: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11127: 		    if (defined($token->[2]->{'id'})) { 
                   11128: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11129: 		    }
1.599     albertel 11130: 		    if ($metaentry{':packages'}) {
                   11131: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11132: 		    } else {
1.599     albertel 11133: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11134: 		    }
1.736     albertel 11135: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11136: 			my $part=$keyroot;
                   11137: 			$part=~s/^\_//;
1.736     albertel 11138: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11139: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11140: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11141: 			    # ignore package.tab specified default values
                   11142:                             # here &package_tab_default() will fetch those
                   11143: 			    if ($subp eq 'default') { next; }
1.736     albertel 11144: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11145: 			    my $unikey;
                   11146: 			    if ($pack =~ /_0$/) {
                   11147: 				$unikey='parameter_0_'.$name;
                   11148: 				$part=0;
                   11149: 			    } else {
                   11150: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11151: 			    }
1.339     albertel 11152: 			    if ($subp eq 'display') {
                   11153: 				$value.=' [Part: '.$part.']';
                   11154: 			    }
1.599     albertel 11155: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11156: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11157: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11158: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11159: 			    }
1.599     albertel 11160: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11161: 				$metaentry{':'.$unikey}=
                   11162: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11163: 			    }
1.339     albertel 11164: 			}
                   11165: 		    }
                   11166: 		} else {
1.172     www      11167: #
                   11168: # This is not a package - some other kind of start tag
1.339     albertel 11169: #
                   11170: 		    my $entry=$token->[1];
1.1068    www      11171: 		    my $unikey='';
1.175     www      11172: 
1.339     albertel 11173: 		    if ($entry eq 'import') {
1.175     www      11174: #
                   11175: # Importing a library here
1.339     albertel 11176: #
1.1067    www      11177:                         my $location=$parser->get_text('/import');
                   11178:                         my $dir=$filename;
                   11179:                         $dir=~s|[^/]*$||;
                   11180:                         $location=&filelocation($dir,$location);
1.1069    www      11181:                        
1.1068    www      11182:                         my $importmode=$token->[2]->{'importmode'};
                   11183:                         if ($importmode eq 'problem') {
1.1069    www      11184: # Import as problem/response
1.1068    www      11185:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11186:                         } elsif ($importmode eq 'part') {
                   11187: # Import as part(s)
1.1069    www      11188:                            $importedparts=1;
                   11189: # We need to get the original file and the imported file to get the part order correct
                   11190: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11191: # Load and inspect original file
1.1070    www      11192:                            if ($#origfileimportpartids<0) {
                   11193:                               undef(%importedpartids);
                   11194:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11195:                               my $origfile=&getfile($origfilelocation);
                   11196:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11197:                            }
                   11198: 
1.1069    www      11199: # Load and inspect imported file
                   11200:                            my $impfile=&getfile($location);
                   11201:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11202:                            if ($#impfilepartids>=0) {
                   11203: # This problem had parts
1.1070    www      11204:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11205:                            } else {
                   11206: # Importing by turning a single problem into a problem part
                   11207: # It gets the import-tags ID as part-ID
                   11208:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11209:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11210:                            }
1.1068    www      11211:                         } else {
                   11212: # Normal import
                   11213:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11214:                            if (defined($token->[2]->{'id'})) {
                   11215:                               $unikey.='_'.$token->[2]->{'id'};
                   11216:                            }
1.1067    www      11217:                         }
                   11218: 
1.339     albertel 11219: 			if ($depthcount<20) {
1.736     albertel 11220: 			    my $metadata = 
                   11221: 				&metadata($uri,'keys', $location,$unikey,
                   11222: 					  $depthcount+1);
                   11223: 			    foreach my $meta (split(',',$metadata)) {
                   11224: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11225: 				$metathesekeys{$meta}=1;
1.339     albertel 11226: 			    }
1.1068    www      11227: 			
                   11228:                         }
1.1067    www      11229: 		    } else {
                   11230: #
                   11231: # Not importing, some other kind of non-package, non-library start tag
                   11232: # 
                   11233:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11234:                         if (defined($token->[2]->{'id'})) {
                   11235:                             $unikey.='_'.$token->[2]->{'id'};
                   11236:                         }
1.339     albertel 11237: 			if (defined($token->[2]->{'name'})) { 
                   11238: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11239: 			}
                   11240: 			$metathesekeys{$unikey}=1;
1.736     albertel 11241: 			foreach my $param (@{$token->[3]}) {
                   11242: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11243: 				$token->[2]->{$param};
1.339     albertel 11244: 			}
                   11245: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11246: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11247: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11248: 		 # only ws inside the tag, and not in default, so use default
                   11249: 		 # as value
1.599     albertel 11250: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11251: 			} elsif ( $internaltext =~ /\S/ ) {
                   11252: 		  # something interesting inside the tag
                   11253: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11254: 			} else {
1.908     albertel 11255: 		  # no interesting values, don't set a default
1.339     albertel 11256: 			}
1.172     www      11257: # end of not-a-package not-a-library import
1.339     albertel 11258: 		    }
1.172     www      11259: # end of not-a-package start tag
1.339     albertel 11260: 		}
1.172     www      11261: # the next is the end of "start tag"
1.339     albertel 11262: 	    }
                   11263: 	}
1.483     albertel 11264: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11265: 	$extension = lc($extension);
                   11266: 	if ($extension eq 'htm') { $extension='html'; }
                   11267: 
1.737     albertel 11268: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11269: 	    #no specific packages #how's our extension
                   11270: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11271: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11272: 					 \%metathesekeys);
                   11273: 	}
1.883     albertel 11274: 
                   11275: 	if (!exists($metaentry{':packages'})
                   11276: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11277: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11278: 		#no specific packages well let's get default then
                   11279: 		if ($key!~/^default&/) { next; }
1.488     albertel 11280: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11281: 					     \%metathesekeys);
                   11282: 	    }
                   11283: 	}
1.338     www      11284: # are there custom rights to evaluate
1.599     albertel 11285: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11286: 
1.338     www      11287:     #
                   11288:     # Importing a rights file here
1.339     albertel 11289:     #
                   11290: 	    unless ($depthcount) {
1.599     albertel 11291: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11292: 		my $dir=$filename;
                   11293: 		$dir=~s|[^/]*$||;
                   11294: 		$location=&filelocation($dir,$location);
1.736     albertel 11295: 		my $rights_metadata =
                   11296: 		    &metadata($uri,'keys',$location,'_rights',
                   11297: 			      $depthcount+1);
                   11298: 		foreach my $rights (split(',',$rights_metadata)) {
                   11299: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11300: 		    $metathesekeys{$rights}=1;
1.339     albertel 11301: 		}
                   11302: 	    }
                   11303: 	}
1.737     albertel 11304: 	# uniqifiy package listing
                   11305: 	my %seen;
                   11306: 	my @uniq_packages =
                   11307: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11308: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11309: 
1.1070    www      11310:         if ($importedparts) {
                   11311: # We had imported parts and need to rebuild partorder
                   11312:            $metaentry{':partorder'}='';
                   11313:            $metathesekeys{'partorder'}=1;
                   11314:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11315:                if ($origfileimportpartids[$index] eq 'part') {
                   11316: # original part, part of the problem
                   11317:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11318:                } else {
                   11319: # we have imported parts at this position
                   11320:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11321:                }
                   11322:            }
                   11323:            $metaentry{':partorder'}=~s/^\,//;
                   11324:         }
                   11325: 
1.737     albertel 11326: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11327: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  11328: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11329: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11330: # this is the end of "was not already recently cached
1.71      www      11331:     }
1.599     albertel 11332:     return $metaentry{':'.$what};
1.261     albertel 11333: }
                   11334: 
1.488     albertel 11335: sub metadata_create_package_def {
1.483     albertel 11336:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11337:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11338:     if ($subp eq 'default') { next; }
                   11339:     
1.599     albertel 11340:     if (defined($metaentry{':packages'})) {
                   11341: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11342:     } else {
1.599     albertel 11343: 	$metaentry{':packages'}=$package;
1.483     albertel 11344:     }
                   11345:     my $value=$packagetab{$key};
                   11346:     my $unikey;
                   11347:     $unikey='parameter_0_'.$name;
1.599     albertel 11348:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11349:     $$metathesekeys{$unikey}=1;
1.599     albertel 11350:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11351: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11352:     }
1.599     albertel 11353:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11354: 	$metaentry{':'.$unikey}=
                   11355: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11356:     }
                   11357: }
                   11358: 
1.261     albertel 11359: sub metadata_generate_part0 {
                   11360:     my ($metadata,$metacache,$uri) = @_;
                   11361:     my %allnames;
1.737     albertel 11362:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11363: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11364: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11365: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11366: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11367: 	    $allnames{$name}=$part;
                   11368: 	  }
                   11369: 	}
                   11370:     }
                   11371:     foreach my $name (keys(%allnames)) {
                   11372:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11373:       my $key=":parameter_0_$name";
1.261     albertel 11374:       $$metacache{"$key.part"}='0';
                   11375:       $$metacache{"$key.name"}=$name;
1.428     albertel 11376:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11377: 					   $allnames{$name}.'_'.$name.
                   11378: 					   '.type'};
1.428     albertel 11379:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11380: 			     '.display'};
1.644     www      11381:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11382:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11383:       $$metacache{"$key.display"}=$olddis;
                   11384:     }
1.71      www      11385: }
                   11386: 
1.764     albertel 11387: # ------------------------------------------------------ Devalidate title cache
                   11388: 
                   11389: sub devalidate_title_cache {
                   11390:     my ($url)=@_;
                   11391:     if (!$env{'request.course.id'}) { return; }
                   11392:     my $symb=&symbread($url);
                   11393:     if (!$symb) { return; }
                   11394:     my $key=$env{'request.course.id'}."\0".$symb;
                   11395:     &devalidate_cache_new('title',$key);
                   11396: }
                   11397: 
1.1014    droeschl 11398: # ------------------------------------------------- Get the title of a course
                   11399: 
                   11400: sub current_course_title {
                   11401:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11402: }
1.301     www      11403: # ------------------------------------------------- Get the title of a resource
                   11404: 
                   11405: sub gettitle {
                   11406:     my $urlsymb=shift;
                   11407:     my $symb=&symbread($urlsymb);
1.534     albertel 11408:     if ($symb) {
1.620     albertel 11409: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11410: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11411: 	if (defined($cached)) { 
                   11412: 	    return $result;
                   11413: 	}
1.534     albertel 11414: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11415: 	my $title='';
1.907     albertel 11416: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11417: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11418: 	} else {
                   11419: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11420: 		    &GDBM_READER(),0640)) {
                   11421: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11422: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11423: 		untie(%bighash);
                   11424: 	    }
1.534     albertel 11425: 	}
                   11426: 	$title=~s/\&colon\;/\:/gs;
                   11427: 	if ($title) {
1.1159    www      11428: # Remember both $symb and $title for dynamic metadata
                   11429:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11430:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11431: # Cache this title and then return it
1.599     albertel 11432: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11433: 	}
                   11434: 	$urlsymb=$url;
                   11435:     }
                   11436:     my $title=&metadata($urlsymb,'title');
                   11437:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11438:     return $title;
1.301     www      11439: }
1.613     albertel 11440: 
1.614     albertel 11441: sub get_slot {
                   11442:     my ($which,$cnum,$cdom)=@_;
                   11443:     if (!$cnum || !$cdom) {
1.790     albertel 11444: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11445: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11446: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11447:     }
1.703     albertel 11448:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11449:     my %slotinfo;
                   11450:     if (exists($remembered{$key})) {
                   11451: 	$slotinfo{$which} = $remembered{$key};
                   11452:     } else {
                   11453: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11454: 	&Apache::lonhomework::showhash(%slotinfo);
                   11455: 	my ($tmp)=keys(%slotinfo);
                   11456: 	if ($tmp=~/^error:/) { return (); }
                   11457: 	$remembered{$key} = $slotinfo{$which};
                   11458:     }
1.616     albertel 11459:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11460: 	return %{$slotinfo{$which}};
                   11461:     }
                   11462:     return $slotinfo{$which};
1.614     albertel 11463: }
1.1150    raeburn  11464: 
                   11465: sub get_reservable_slots {
                   11466:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11467:     my $now = time;
                   11468:     my $reservable_info;
                   11469:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11470:     if (exists($remembered{$key})) {
                   11471:         $reservable_info = $remembered{$key};
                   11472:     } else {
                   11473:         my %resv;
                   11474:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11475:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11476:         $reservable_info = \%resv;
                   11477:         $remembered{$key} = $reservable_info;
                   11478:     }
                   11479:     return $reservable_info;
                   11480: }
                   11481: 
                   11482: sub get_course_slots {
                   11483:     my ($cnum,$cdom) = @_;
                   11484:     my $hashid=$cnum.':'.$cdom;
                   11485:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11486:     if (defined($cached)) {
                   11487:         if (ref($result) eq 'HASH') {
                   11488:             return %{$result};
                   11489:         }
                   11490:     } else {
                   11491:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11492:         my ($tmp) = keys(%slots);
                   11493:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  11494:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11495:             return %slots;
                   11496:         }
                   11497:     }
                   11498:     return;
                   11499: }
                   11500: 
                   11501: sub devalidate_slots_cache {
                   11502:     my ($cnum,$cdom)=@_;
                   11503:     my $hashid=$cnum.':'.$cdom;
                   11504:     &devalidate_cache_new('allslots',$hashid);
                   11505: }
                   11506: 
1.1181    raeburn  11507: sub get_coursechange {
                   11508:     my ($cdom,$cnum) = @_;
                   11509:     if ($cdom eq '' || $cnum eq '') {
                   11510:         return unless ($env{'request.course.id'});
                   11511:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11512:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11513:     }
                   11514:     my $hashid=$cdom.'_'.$cnum;
                   11515:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11516:     if ((defined($cached)) && ($change ne '')) {
                   11517:         return $change;
                   11518:     } else {
                   11519:         my %crshash;
                   11520:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11521:         if ($crshash{'internal.contentchange'} eq '') {
                   11522:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11523:             if ($change eq '') {
                   11524:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11525:                 $change = $crshash{'internal.created'};
                   11526:             }
                   11527:         } else {
                   11528:             $change = $crshash{'internal.contentchange'};
                   11529:         }
                   11530:         my $cachetime = 600;
                   11531:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11532:     }
                   11533:     return $change;
                   11534: }
                   11535: 
                   11536: sub devalidate_coursechange_cache {
                   11537:     my ($cnum,$cdom)=@_;
                   11538:     my $hashid=$cnum.':'.$cdom;
                   11539:     &devalidate_cache_new('crschange',$hashid);
                   11540: }
                   11541: 
1.31      www      11542: # ------------------------------------------------- Update symbolic store links
                   11543: 
                   11544: sub symblist {
                   11545:     my ($mapname,%newhash)=@_;
1.438     www      11546:     $mapname=&deversion(&declutter($mapname));
1.31      www      11547:     my %hash;
1.620     albertel 11548:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11549:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11550:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11551: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11552: 		next if ($url eq 'last_known'
                   11553: 			 && $env{'form.no_update_last_known'});
                   11554: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11555: 						    $newhash{$url}->[1],
                   11556: 						    $newhash{$url}->[0]);
1.191     harris41 11557:             }
1.31      www      11558:             if (untie(%hash)) {
                   11559: 		return 'ok';
                   11560:             }
                   11561:         }
                   11562:     }
                   11563:     return 'error';
1.212     www      11564: }
                   11565: 
                   11566: # --------------------------------------------------------------- Verify a symb
                   11567: 
                   11568: sub symbverify {
1.1190    raeburn  11569:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11570:     my $thisfn=$thisurl;
1.439     www      11571:     $thisfn=&declutter($thisfn);
1.215     www      11572: # direct jump to resource in page or to a sequence - will construct own symbs
                   11573:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11574: # check URL part
1.409     www      11575:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11576: 
1.431     www      11577:     unless ($url eq $thisfn) { return 0; }
1.213     www      11578: 
1.216     www      11579:     $symb=&symbclean($symb);
1.510     www      11580:     $thisurl=&deversion($thisurl);
1.439     www      11581:     $thisfn=&deversion($thisfn);
1.213     www      11582: 
                   11583:     my %bighash;
                   11584:     my $okay=0;
1.431     www      11585: 
1.620     albertel 11586:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11587:                             &GDBM_READER(),0640)) {
1.1204    raeburn  11588:         my $noclutter;
1.1032    raeburn  11589:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11590:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  11591:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11592:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11593:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11594:                 $noclutter = 1;
                   11595:             }
                   11596:         }
                   11597:         my $ids;
                   11598:         if ($noclutter) {
                   11599:             $ids=$bighash{'ids_'.$thisurl};
                   11600:         } else {
                   11601:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11602:         }
1.1102    raeburn  11603:         unless ($ids) {
                   11604:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   11605:             $ids=$bighash{$idkey};
1.216     www      11606:         }
                   11607:         if ($ids) {
                   11608: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  11609:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  11610:                 $symb =~ s/\?.+$//;
1.1202    raeburn  11611:             }
1.800     albertel 11612: 	    foreach my $id (split(/\,/,$ids)) {
                   11613: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11614:                if (
                   11615:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  11616:    eq $symb) {
                   11617:                    if (ref($encstate)) {
                   11618:                        $$encstate = $bighash{'encrypted_'.$id};
                   11619:                    }
1.620     albertel 11620: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  11621: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   11622:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  11623: 		       $okay=1;
1.1202    raeburn  11624:                        last;
1.582     albertel 11625: 		   }
                   11626: 	       }
1.216     www      11627: 	   }
                   11628:         }
1.213     www      11629: 	untie(%bighash);
                   11630:     }
                   11631:     return $okay;
1.31      www      11632: }
                   11633: 
1.210     www      11634: # --------------------------------------------------------------- Clean-up symb
                   11635: 
                   11636: sub symbclean {
                   11637:     my $symb=shift;
1.568     albertel 11638:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11639: # remove version from map
                   11640:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11641: 
1.210     www      11642: # remove version from URL
                   11643:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11644: 
1.507     www      11645: # remove wrapper
                   11646: 
1.510     www      11647:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11648:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11649:     return $symb;
1.409     www      11650: }
                   11651: 
                   11652: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11653: 
                   11654: sub encode_symb {
                   11655:     my ($map,$resid,$url)=@_;
                   11656:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11657: }
1.409     www      11658: 
                   11659: sub decode_symb {
1.568     albertel 11660:     my $symb=shift;
                   11661:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11662:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11663:     return (&fixversion($map),$resid,&fixversion($url));
                   11664: }
                   11665: 
                   11666: sub fixversion {
                   11667:     my $fn=shift;
1.609     banghart 11668:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11669:     my %bighash;
                   11670:     my $uri=&clutter($fn);
1.620     albertel 11671:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11672: # is this cached?
1.599     albertel 11673:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11674:     if (defined($cached)) { return $result; }
                   11675: # unfortunately not cached, or expired
1.620     albertel 11676:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11677: 	    &GDBM_READER(),0640)) {
                   11678:  	if ($bighash{'version_'.$uri}) {
                   11679:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11680:  	    unless (($version eq 'mostrecent') || 
                   11681: 		    ($version==&getversion($uri))) {
1.440     www      11682:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11683:  	    }
                   11684:  	}
                   11685:  	untie %bighash;
1.413     www      11686:     }
1.599     albertel 11687:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11688: }
                   11689: 
                   11690: sub deversion {
                   11691:     my $url=shift;
                   11692:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11693:     return $url;
1.210     www      11694: }
                   11695: 
1.31      www      11696: # ------------------------------------------------------ Return symb list entry
                   11697: 
                   11698: sub symbread {
1.1282    raeburn  11699:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  11700:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  11701:     if (defined($env{$cache_str})) {
                   11702:         if ($ignorecachednull) {
                   11703:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11704:         } else {
                   11705:             return $env{$cache_str};
                   11706:         }
                   11707:     }
1.242     www      11708: # no filename provided? try from environment
1.1265    raeburn  11709:     unless ($thisfn) {
1.620     albertel 11710:         if ($env{'request.symb'}) {
                   11711: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 11712: 	}
1.620     albertel 11713: 	$thisfn=$env{'request.filename'};
1.44      www      11714:     }
1.569     albertel 11715:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11716: # is that filename actually a symb? Verify, clean, and return
                   11717:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11718: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11719: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11720: 	}
1.242     www      11721:     }
1.44      www      11722:     $thisfn=declutter($thisfn);
1.31      www      11723:     my %hash;
1.37      www      11724:     my %bighash;
                   11725:     my $syval='';
1.620     albertel 11726:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11727:         my $targetfn = $thisfn;
1.609     banghart 11728:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11729:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11730:         }
1.687     albertel 11731: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11732: 	    $targetfn=$1;
                   11733: 	}
1.620     albertel 11734:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11735:                       &GDBM_READER(),0640)) {
1.481     raeburn  11736: 	    $syval=$hash{$targetfn};
1.37      www      11737:             untie(%hash);
                   11738:         }
                   11739: # ---------------------------------------------------------- There was an entry
                   11740:         if ($syval) {
1.601     albertel 11741: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11742: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11743: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11744: 		    #return $env{$cache_str}='';
1.601     albertel 11745: 		#}    
                   11746: 		#$syval.=$1;
                   11747: 	    #}
1.37      www      11748:         } else {
                   11749: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11750:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11751:                             &GDBM_READER(),0640)) {
1.37      www      11752: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11753:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11754:               unless ($ids) { 
                   11755:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11756:               }
                   11757:               unless ($ids) {
                   11758: # alias?
                   11759: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11760:               }
1.37      www      11761:               if ($ids) {
                   11762: # ------------------------------------------------------------------- Has ID(s)
                   11763:                  my @possibilities=split(/\,/,$ids);
1.39      www      11764:                  if ($#possibilities==0) {
                   11765: # ----------------------------------------------- There is only one possibility
1.37      www      11766: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11767: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11768: 						    $resid,$thisfn);
1.1282    raeburn  11769:                      if (ref($possibles) eq 'HASH') {
                   11770:                          $possibles->{$syval} = 1;    
                   11771:                      }
                   11772:                      if ($checkforblock) {
                   11773:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11774:                          if (@blockers) {
                   11775:                              $syval = '';
                   11776:                              return;
                   11777:                          }
                   11778:                      }
                   11779:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      11780: # ------------------------------------------ There is more than one possibility
                   11781:                      my $realpossible=0;
1.800     albertel 11782:                      foreach my $id (@possibilities) {
                   11783: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  11784:                          my $canaccess;
                   11785:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11786:                              $canaccess = 1;
                   11787:                          } else { 
                   11788:                              $canaccess = &allowed('bre',$file);
                   11789:                          }
                   11790:                          if ($canaccess) {
                   11791:          		     my ($mapid,$resid)=split(/\./,$id);
                   11792:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11793:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11794: 						             $resid,$thisfn);
                   11795:                                  if (ref($possibles) eq 'HASH') {
                   11796:                                      $possibles->{$syval} = 1;
                   11797:                                  }
                   11798:                                  if ($checkforblock) {
                   11799:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11800:                                      unless (@blockers > 0) {
                   11801:                                          $syval = $poss_syval;
                   11802:                                          $realpossible++;
                   11803:                                      }
                   11804:                                  } else {
                   11805:                                      $syval = $poss_syval;
                   11806:                                      $realpossible++;
                   11807:                                  }
                   11808:                              }
1.39      www      11809: 			 }
1.191     harris41 11810:                      }
1.39      www      11811: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11812:                  } else {
                   11813:                      $syval='';
1.37      www      11814:                  }
                   11815: 	      }
1.1282    raeburn  11816:               untie(%bighash);
1.481     raeburn  11817:            }
1.31      www      11818:         }
1.62      www      11819:         if ($syval) {
1.620     albertel 11820: 	    return $env{$cache_str}=$syval;
1.62      www      11821:         }
1.31      www      11822:     }
1.949     raeburn  11823:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11824:     return $env{$cache_str}='';
1.31      www      11825: }
                   11826: 
                   11827: # ---------------------------------------------------------- Return random seed
                   11828: 
1.32      www      11829: sub numval {
                   11830:     my $txt=shift;
                   11831:     $txt=~tr/A-J/0-9/;
                   11832:     $txt=~tr/a-j/0-9/;
                   11833:     $txt=~tr/K-T/0-9/;
                   11834:     $txt=~tr/k-t/0-9/;
                   11835:     $txt=~tr/U-Z/0-5/;
                   11836:     $txt=~tr/u-z/0-5/;
                   11837:     $txt=~s/\D//g;
1.564     albertel 11838:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11839:     return int($txt);
1.368     albertel 11840: }
                   11841: 
1.484     albertel 11842: sub numval2 {
                   11843:     my $txt=shift;
                   11844:     $txt=~tr/A-J/0-9/;
                   11845:     $txt=~tr/a-j/0-9/;
                   11846:     $txt=~tr/K-T/0-9/;
                   11847:     $txt=~tr/k-t/0-9/;
                   11848:     $txt=~tr/U-Z/0-5/;
                   11849:     $txt=~tr/u-z/0-5/;
                   11850:     $txt=~s/\D//g;
                   11851:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11852:     my $total;
                   11853:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11854:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11855:     return int($total);
                   11856: }
                   11857: 
1.575     albertel 11858: sub numval3 {
                   11859:     use integer;
                   11860:     my $txt=shift;
                   11861:     $txt=~tr/A-J/0-9/;
                   11862:     $txt=~tr/a-j/0-9/;
                   11863:     $txt=~tr/K-T/0-9/;
                   11864:     $txt=~tr/k-t/0-9/;
                   11865:     $txt=~tr/U-Z/0-5/;
                   11866:     $txt=~tr/u-z/0-5/;
                   11867:     $txt=~s/\D//g;
                   11868:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11869:     my $total;
                   11870:     foreach my $val (@txts) { $total+=$val; }
                   11871:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11872:     return $total;
                   11873: }
                   11874: 
1.675     albertel 11875: sub digest {
                   11876:     my ($data)=@_;
                   11877:     my $digest=&Digest::MD5::md5($data);
                   11878:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11879:     my ($e,$f);
                   11880:     {
                   11881:         use integer;
                   11882:         $e=($a+$b);
                   11883:         $f=($c+$d);
                   11884:         if ($_64bit) {
                   11885:             $e=(($e<<32)>>32);
                   11886:             $f=(($f<<32)>>32);
                   11887:         }
                   11888:     }
                   11889:     if (wantarray) {
                   11890: 	return ($e,$f);
                   11891:     } else {
                   11892: 	my $g;
                   11893: 	{
                   11894: 	    use integer;
                   11895: 	    $g=($e+$f);
                   11896: 	    if ($_64bit) {
                   11897: 		$g=(($g<<32)>>32);
                   11898: 	    }
                   11899: 	}
                   11900: 	return $g;
                   11901:     }
                   11902: }
                   11903: 
1.368     albertel 11904: sub latest_rnd_algorithm_id {
1.675     albertel 11905:     return '64bit5';
1.366     albertel 11906: }
1.32      www      11907: 
1.503     albertel 11908: sub get_rand_alg {
                   11909:     my ($courseid)=@_;
1.790     albertel 11910:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11911:     if ($courseid) {
1.620     albertel 11912: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11913:     }
                   11914:     return &latest_rnd_algorithm_id();
                   11915: }
                   11916: 
1.562     albertel 11917: sub validCODE {
                   11918:     my ($CODE)=@_;
                   11919:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11920:     return 0;
                   11921: }
                   11922: 
1.491     albertel 11923: sub getCODE {
1.620     albertel 11924:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11925:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11926: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11927: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11928: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11929:     }
                   11930:     return undef;
                   11931: }
1.1133    foxr     11932: #
                   11933: #  Determines the random seed for a specific context:
                   11934: #
                   11935: # parameters:
                   11936: #   symb      - in course context the symb for the seed.
                   11937: #   course_id - The course id of the form domain_coursenum.
                   11938: #   domain    - Domain for the user.
                   11939: #   course    - Course for the user.
                   11940: #   cenv      - environment of the course.
                   11941: #
                   11942: # NOTE:
                   11943: #   All parameters are picked out of the environment if missing
                   11944: #   or not defined.
                   11945: #   If a symb cannot be determined the current time is used instead.
                   11946: #
                   11947: #  For a given well defined symb, courside, domain, username,
                   11948: #  and course environment, the seed is reproducible.
                   11949: #
1.31      www      11950: sub rndseed {
1.1133    foxr     11951:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11952:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11953:     if (!defined($symb)) {
1.366     albertel 11954: 	unless ($symb=$wsymb) { return time; }
                   11955:     }
1.1146    foxr     11956:     if (!defined $courseid) { 
                   11957: 	$courseid=$wcourseid; 
                   11958:     }
                   11959:     if (!defined $domain) { $domain=$wdomain; }
                   11960:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11961: 
                   11962:     my $which;
                   11963:     if (defined($cenv->{'rndseed'})) {
                   11964: 	$which = $cenv->{'rndseed'};
                   11965:     } else {
                   11966: 	$which =&get_rand_alg($courseid);
                   11967:     }
1.491     albertel 11968:     if (defined(&getCODE())) {
1.1133    foxr     11969: 
1.675     albertel 11970: 	if ($which eq '64bit5') {
                   11971: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11972: 	} elsif ($which eq '64bit4') {
1.575     albertel 11973: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11974: 	} else {
                   11975: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11976: 	}
1.675     albertel 11977:     } elsif ($which eq '64bit5') {
                   11978: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11979:     } elsif ($which eq '64bit4') {
                   11980: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11981:     } elsif ($which eq '64bit3') {
                   11982: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11983:     } elsif ($which eq '64bit2') {
                   11984: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11985:     } elsif ($which eq '64bit') {
                   11986: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11987:     }
                   11988:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11989: }
                   11990: 
                   11991: sub rndseed_32bit {
                   11992:     my ($symb,$courseid,$domain,$username)=@_;
                   11993:     {
                   11994: 	use integer;
                   11995: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11996: 	my $symbseed=numval($symb) << 22;
                   11997: 	my $namechck=unpack("%32C*",$username) << 17;
                   11998: 	my $nameseed=numval($username) << 12;
                   11999: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12000: 	my $courseseed=unpack("%32C*",$courseid);
                   12001: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12002: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12003: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12004: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12005: 	return $num;
                   12006:     }
                   12007: }
                   12008: 
                   12009: sub rndseed_64bit {
                   12010:     my ($symb,$courseid,$domain,$username)=@_;
                   12011:     {
                   12012: 	use integer;
                   12013: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12014: 	my $symbseed=numval($symb) << 10;
                   12015: 	my $namechck=unpack("%32S*",$username);
                   12016: 	
                   12017: 	my $nameseed=numval($username) << 21;
                   12018: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12019: 	my $courseseed=unpack("%32S*",$courseid);
                   12020: 	
                   12021: 	my $num1=$symbchck+$symbseed+$namechck;
                   12022: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12023: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12024: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12025: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12026: 	return "$num1,$num2";
1.155     albertel 12027:     }
1.366     albertel 12028: }
                   12029: 
1.443     albertel 12030: sub rndseed_64bit2 {
                   12031:     my ($symb,$courseid,$domain,$username)=@_;
                   12032:     {
                   12033: 	use integer;
                   12034: 	# strings need to be an even # of cahracters long, it it is odd the
                   12035:         # last characters gets thrown away
                   12036: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12037: 	my $symbseed=numval($symb) << 10;
                   12038: 	my $namechck=unpack("%32S*",$username.' ');
                   12039: 	
                   12040: 	my $nameseed=numval($username) << 21;
1.501     albertel 12041: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12042: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12043: 	
                   12044: 	my $num1=$symbchck+$symbseed+$namechck;
                   12045: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12046: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12047: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12048: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12049: 	return "$num1,$num2";
                   12050:     }
                   12051: }
                   12052: 
                   12053: sub rndseed_64bit3 {
                   12054:     my ($symb,$courseid,$domain,$username)=@_;
                   12055:     {
                   12056: 	use integer;
                   12057: 	# strings need to be an even # of cahracters long, it it is odd the
                   12058:         # last characters gets thrown away
                   12059: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12060: 	my $symbseed=numval2($symb) << 10;
                   12061: 	my $namechck=unpack("%32S*",$username.' ');
                   12062: 	
                   12063: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12064: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12065: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12066: 	
                   12067: 	my $num1=$symbchck+$symbseed+$namechck;
                   12068: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12069: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12070: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12071: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12072: 	
1.503     albertel 12073: 	return "$num1:$num2";
1.443     albertel 12074:     }
                   12075: }
                   12076: 
1.575     albertel 12077: sub rndseed_64bit4 {
                   12078:     my ($symb,$courseid,$domain,$username)=@_;
                   12079:     {
                   12080: 	use integer;
                   12081: 	# strings need to be an even # of cahracters long, it it is odd the
                   12082:         # last characters gets thrown away
                   12083: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12084: 	my $symbseed=numval3($symb) << 10;
                   12085: 	my $namechck=unpack("%32S*",$username.' ');
                   12086: 	
                   12087: 	my $nameseed=numval3($username) << 21;
                   12088: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12089: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12090: 	
                   12091: 	my $num1=$symbchck+$symbseed+$namechck;
                   12092: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12093: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12094: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12095: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12096: 	
1.575     albertel 12097: 	return "$num1:$num2";
                   12098:     }
                   12099: }
                   12100: 
1.675     albertel 12101: sub rndseed_64bit5 {
                   12102:     my ($symb,$courseid,$domain,$username)=@_;
                   12103:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12104:     return "$num1:$num2";
                   12105: }
                   12106: 
1.366     albertel 12107: sub rndseed_CODE_64bit {
                   12108:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12109:     {
1.366     albertel 12110: 	use integer;
1.443     albertel 12111: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12112: 	my $symbseed=numval2($symb);
1.491     albertel 12113: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12114: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12115: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12116: 	my $num1=$symbseed+$CODEchck;
                   12117: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12118: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12119: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12120: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12121: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12122: 	return "$num1:$num2";
1.366     albertel 12123:     }
                   12124: }
                   12125: 
1.575     albertel 12126: sub rndseed_CODE_64bit4 {
                   12127:     my ($symb,$courseid,$domain,$username)=@_;
                   12128:     {
                   12129: 	use integer;
                   12130: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12131: 	my $symbseed=numval3($symb);
                   12132: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12133: 	my $CODEseed=numval3(&getCODE());
                   12134: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12135: 	my $num1=$symbseed+$CODEchck;
                   12136: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12137: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12138: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12139: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12140: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12141: 	return "$num1:$num2";
                   12142:     }
                   12143: }
                   12144: 
1.675     albertel 12145: sub rndseed_CODE_64bit5 {
                   12146:     my ($symb,$courseid,$domain,$username)=@_;
                   12147:     my $code = &getCODE();
                   12148:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12149:     return "$num1:$num2";
                   12150: }
                   12151: 
1.366     albertel 12152: sub setup_random_from_rndseed {
                   12153:     my ($rndseed)=@_;
1.503     albertel 12154:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  12155:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12156:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12157:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12158:         } else {
                   12159:             &Math::Random::random_set_seed($num1,$num2);
                   12160:         }
1.366     albertel 12161:     } else {
                   12162: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12163:     }
1.36      albertel 12164: }
                   12165: 
1.474     albertel 12166: sub latest_receipt_algorithm_id {
1.835     albertel 12167:     return 'receipt3';
1.474     albertel 12168: }
                   12169: 
1.480     www      12170: sub recunique {
                   12171:     my $fucourseid=shift;
                   12172:     my $unique;
1.835     albertel 12173:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12174: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12175: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12176:     } else {
                   12177: 	$unique=$perlvar{'lonReceipt'};
                   12178:     }
                   12179:     return unpack("%32C*",$unique);
                   12180: }
                   12181: 
                   12182: sub recprefix {
                   12183:     my $fucourseid=shift;
                   12184:     my $prefix;
1.835     albertel 12185:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12186: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12187: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12188:     } else {
                   12189: 	$prefix=$perlvar{'lonHostID'};
                   12190:     }
                   12191:     return unpack("%32C*",$prefix);
                   12192: }
                   12193: 
1.76      www      12194: sub ireceipt {
1.474     albertel 12195:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12196: 
                   12197:     my $return =&recprefix($fucourseid).'-';
                   12198: 
                   12199:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12200: 	$env{'request.state'} eq 'construct') {
                   12201: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12202: 	return $return;
                   12203:     }
                   12204: 
1.76      www      12205:     my $cuname=unpack("%32C*",$funame);
                   12206:     my $cudom=unpack("%32C*",$fudom);
                   12207:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12208:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12209:     my $cunique=&recunique($fucourseid);
1.474     albertel 12210:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12211:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12212: 
1.790     albertel 12213: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12214: 			       
                   12215: 	$return.= ($cunique%$cuname+
                   12216: 		   $cunique%$cudom+
                   12217: 		   $cusymb%$cuname+
                   12218: 		   $cusymb%$cudom+
                   12219: 		   $cucourseid%$cuname+
                   12220: 		   $cucourseid%$cudom+
                   12221: 		   $cpart%$cuname+
                   12222: 		   $cpart%$cudom);
                   12223:     } else {
                   12224: 	$return.= ($cunique%$cuname+
                   12225: 		   $cunique%$cudom+
                   12226: 		   $cusymb%$cuname+
                   12227: 		   $cusymb%$cudom+
                   12228: 		   $cucourseid%$cuname+
                   12229: 		   $cucourseid%$cudom);
                   12230:     }
                   12231:     return $return;
1.76      www      12232: }
                   12233: 
                   12234: sub receipt {
1.474     albertel 12235:     my ($part)=@_;
1.790     albertel 12236:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12237:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12238: }
1.260     ng       12239: 
1.790     albertel 12240: sub whichuser {
                   12241:     my ($passedsymb)=@_;
                   12242:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12243:     if (defined($env{'form.grade_symb'})) {
                   12244: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12245: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12246: 	if (!$allowed &&
                   12247: 	    exists($env{'request.course.sec'}) &&
                   12248: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12249: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12250: 			      '/'.$env{'request.course.sec'});
                   12251: 	}
                   12252: 	if ($allowed) {
                   12253: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12254: 	    $courseid=$tmp_courseid;
                   12255: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12256: 	    ($name)=&get_env_multiple('form.grade_username');
                   12257: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12258: 	}
                   12259:     }
                   12260:     if (!$passedsymb) {
                   12261: 	$symb=&symbread();
                   12262:     } else {
                   12263: 	$symb=$passedsymb;
                   12264:     }
                   12265:     $courseid=$env{'request.course.id'};
                   12266:     $domain=$env{'user.domain'};
                   12267:     $name=$env{'user.name'};
                   12268:     if ($name eq 'public' && $domain eq 'public') {
                   12269: 	if (!defined($env{'form.username'})) {
                   12270: 	    $env{'form.username'}.=time.rand(10000000);
                   12271: 	}
                   12272: 	$name.=$env{'form.username'};
                   12273:     }
                   12274:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12275: 
                   12276: }
                   12277: 
1.36      albertel 12278: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12279: # returns either the contents of the file or 
                   12280: # -1 if the file doesn't exist
1.481     raeburn  12281: #
                   12282: # if the target is a file that was uploaded via DOCS, 
                   12283: # a check will be made to see if a current copy exists on the local server,
                   12284: # if it does this will be served, otherwise a copy will be retrieved from
                   12285: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12286: # the local server.   
1.472     albertel 12287: 
1.36      albertel 12288: sub getfile {
1.538     albertel 12289:     my ($file) = @_;
1.609     banghart 12290:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12291:     &repcopy($file);
                   12292:     return &readfile($file);
                   12293: }
                   12294: 
                   12295: sub repcopy_userfile {
                   12296:     my ($file)=@_;
1.1142    raeburn  12297:     my $londocroot = $perlvar{'lonDocRoot'};
                   12298:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12299:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12300:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12301: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12302:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12303:     if (-e "$file") {
1.828     www      12304: # we already have a local copy, check it out
1.538     albertel 12305: 	my @fileinfo = stat($file);
1.828     www      12306: 	my $rtncode;
                   12307: 	my $info;
1.538     albertel 12308: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12309: 	if ($lwpresp ne 'ok') {
1.828     www      12310: # there is no such file anymore, even though we had a local copy
1.482     albertel 12311: 	    if ($rtncode eq '404') {
1.538     albertel 12312: 		unlink($file);
1.482     albertel 12313: 	    }
                   12314: 	    return -1;
                   12315: 	}
                   12316: 	if ($info < $fileinfo[9]) {
1.828     www      12317: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12318: 	    return 'ok';
1.828     www      12319: 	} else {
                   12320: # the file is outdated, get rid of it
                   12321: 	    unlink($file);
1.482     albertel 12322: 	}
1.828     www      12323:     }
                   12324: # one way or the other, at this point, we don't have the file
                   12325: # construct the correct path for the file
                   12326:     my @parts = ($cdom,$cnum); 
                   12327:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12328: 	push @parts, split(/\//,$1);
                   12329:     }
                   12330:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12331:     foreach my $part (@parts) {
                   12332: 	$path .= '/'.$part;
                   12333: 	if (!-e $path) {
                   12334: 	    mkdir($path,0770);
1.482     albertel 12335: 	}
                   12336:     }
1.828     www      12337: # now the path exists for sure
                   12338: # get a user agent
                   12339:     my $ua=new LWP::UserAgent;
                   12340:     my $transferfile=$file.'.in.transfer';
                   12341: # FIXME: this should flock
                   12342:     if (-e $transferfile) { return 'ok'; }
                   12343:     my $request;
                   12344:     $uri=~s/^\///;
1.980     raeburn  12345:     my $homeserver = &homeserver($cnum,$cdom);
                   12346:     my $protocol = $protocol{$homeserver};
                   12347:     $protocol = 'http' if ($protocol ne 'https');
                   12348:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12349:     my $response=$ua->request($request,$transferfile);
                   12350: # did it work?
                   12351:     if ($response->is_error()) {
                   12352: 	unlink($transferfile);
                   12353: 	&logthis("Userfile repcopy failed for $uri");
                   12354: 	return -1;
                   12355:     }
                   12356: # worked, rename the transfer file
                   12357:     rename($transferfile,$file);
1.607     raeburn  12358:     return 'ok';
1.481     raeburn  12359: }
                   12360: 
1.517     albertel 12361: sub tokenwrapper {
                   12362:     my $uri=shift;
1.980     raeburn  12363:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12364:     $uri=~s|^/||;
1.620     albertel 12365:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12366:     my $token=$1;
1.552     albertel 12367:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12368:     if ($udom && $uname && $file) {
                   12369: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12370:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12371:         my $homeserver = &homeserver($uname,$udom);
                   12372:         my $protocol = $protocol{$homeserver};
                   12373:         $protocol = 'http' if ($protocol ne 'https');
                   12374:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12375:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12376:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12377:     } else {
                   12378:         return '/adm/notfound.html';
                   12379:     }
                   12380: }
                   12381: 
1.828     www      12382: # call with reqtype HEAD: get last modification time
                   12383: # call with reqtype GET: get the file contents
                   12384: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12385: #
1.481     raeburn  12386: sub getuploaded {
                   12387:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12388:     $uri=~s/^\///;
1.980     raeburn  12389:     my $homeserver = &homeserver($cnum,$cdom);
                   12390:     my $protocol = $protocol{$homeserver};
                   12391:     $protocol = 'http' if ($protocol ne 'https');
                   12392:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12393:     my $ua=new LWP::UserAgent;
                   12394:     my $request=new HTTP::Request($reqtype,$uri);
                   12395:     my $response=$ua->request($request);
                   12396:     $$rtncode = $response->code;
1.482     albertel 12397:     if (! $response->is_success()) {
                   12398: 	return 'failed';
                   12399:     }      
                   12400:     if ($reqtype eq 'HEAD') {
1.486     www      12401: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12402:     } elsif ($reqtype eq 'GET') {
                   12403: 	$$info = $response->content;
1.472     albertel 12404:     }
1.482     albertel 12405:     return 'ok';
1.36      albertel 12406: }
                   12407: 
1.481     raeburn  12408: sub readfile {
                   12409:     my $file = shift;
                   12410:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12411:     my $fh;
                   12412:     open($fh,"<$file");
                   12413:     my $a='';
1.800     albertel 12414:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12415:     return $a;
                   12416: }
                   12417: 
1.36      albertel 12418: sub filelocation {
1.590     banghart 12419:     my ($dir,$file) = @_;
                   12420:     my $location;
                   12421:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12422: 
                   12423:     if ($file =~ m-^/adm/-) {
                   12424: 	$file=~s-^/adm/wrapper/-/-;
                   12425: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12426:     }
1.882     albertel 12427: 
1.1139    www      12428:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12429:         $location = $file;
1.609     banghart 12430:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12431:         my ($udom,$uname,$filename)=
1.811     albertel 12432:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12433:         my $home=&homeserver($uname,$udom);
                   12434:         my $is_me=0;
                   12435:         my @ids=&current_machine_ids();
                   12436:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12437:         if ($is_me) {
1.1117    foxr     12438:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12439:         } else {
                   12440:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12441:   	      $udom.'/'.$uname.'/'.$filename;
                   12442:         }
1.882     albertel 12443:     } elsif ($file =~ m-^/adm/-) {
                   12444: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12445:     } else {
                   12446:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12447:         $file=~s:^/(res|priv)/:/:;
                   12448:         my $space=$1;
1.590     banghart 12449:         if ( !( $file =~ m:^/:) ) {
                   12450:             $location = $dir. '/'.$file;
                   12451:         } else {
1.1142    raeburn  12452:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12453:         }
1.59      albertel 12454:     }
1.590     banghart 12455:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12456:     while ($location=~m{/\.\./}) {
                   12457: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12458: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12459: 	} else {
                   12460: 	    $location=~ s{/\.\./}{/}g;
                   12461: 	}
                   12462:     } #remove dir/..
1.590     banghart 12463:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12464:     return $location;
1.46      www      12465: }
1.36      albertel 12466: 
1.46      www      12467: sub hreflocation {
                   12468:     my ($dir,$file)=@_;
1.980     raeburn  12469:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12470: 	$file=filelocation($dir,$file);
1.700     albertel 12471:     } elsif ($file=~m-^/adm/-) {
                   12472: 	$file=~s-^/adm/wrapper/-/-;
                   12473: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12474:     }
                   12475:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12476: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12477:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12478: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12479: 	        {/uploaded/$1/$2/}x;
1.46      www      12480:     }
1.913     albertel 12481:     if ($file=~ m{^/userfiles/}) {
                   12482: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12483:     }
1.462     albertel 12484:     return $file;
1.465     albertel 12485: }
                   12486: 
1.1139    www      12487: 
                   12488: 
                   12489: 
                   12490: 
1.465     albertel 12491: sub current_machine_domains {
1.853     albertel 12492:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12493: }
                   12494: 
                   12495: sub machine_domains {
                   12496:     my ($hostname) = @_;
1.465     albertel 12497:     my @domains;
1.838     albertel 12498:     my %hostname = &all_hostnames();
1.465     albertel 12499:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12500: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12501: 	if ($hostname eq $name) {
1.844     albertel 12502: 	    push(@domains,&host_domain($id));
1.465     albertel 12503: 	}
                   12504:     }
                   12505:     return @domains;
                   12506: }
                   12507: 
                   12508: sub current_machine_ids {
1.853     albertel 12509:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12510: }
                   12511: 
                   12512: sub machine_ids {
                   12513:     my ($hostname) = @_;
                   12514:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12515:     my @ids;
1.888     albertel 12516:     my %name_to_host = &all_names();
1.889     albertel 12517:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12518: 	return @{ $name_to_host{$hostname} };
                   12519:     }
                   12520:     return;
1.31      www      12521: }
                   12522: 
1.824     raeburn  12523: sub additional_machine_domains {
                   12524:     my @domains;
                   12525:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12526:     while( my $line = <$fh>) {
                   12527:         $line =~ s/\s//g;
                   12528:         push(@domains,$line);
                   12529:     }
                   12530:     return @domains;
                   12531: }
                   12532: 
                   12533: sub default_login_domain {
                   12534:     my $domain = $perlvar{'lonDefDomain'};
                   12535:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12536:     foreach my $posdom (&current_machine_domains(),
                   12537:                         &additional_machine_domains()) {
                   12538:         if (lc($posdom) eq lc($testdomain)) {
                   12539:             $domain=$posdom;
                   12540:             last;
                   12541:         }
                   12542:     }
                   12543:     return $domain;
                   12544: }
                   12545: 
1.31      www      12546: # ------------------------------------------------------------- Declutters URLs
                   12547: 
                   12548: sub declutter {
                   12549:     my $thisfn=shift;
1.569     albertel 12550:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  12551:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12552:         $thisfn=~s{^/home/httpd/html}{};
                   12553:     }
1.31      www      12554:     $thisfn=~s/^\///;
1.697     albertel 12555:     $thisfn=~s|^adm/wrapper/||;
                   12556:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12557:     $thisfn=~s/^res\///;
1.1172    bisitz   12558:     $thisfn=~s/^priv\///;
1.1032    raeburn  12559:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12560:         $thisfn=~s/\?.+$//;
                   12561:     }
1.268     www      12562:     return $thisfn;
                   12563: }
                   12564: 
                   12565: # ------------------------------------------------------------- Clutter up URLs
                   12566: 
                   12567: sub clutter {
                   12568:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12569:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12570: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12571:        $thisfn='/res'.$thisfn; 
                   12572:     }
1.1031    raeburn  12573:     if ($thisfn !~m|^/adm|) {
                   12574: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12575: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12576: 	} else {
                   12577: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12578: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12579: 	    if ($embstyle eq 'ssi'
                   12580: 		|| ($embstyle eq 'hdn')
                   12581: 		|| ($embstyle eq 'rat')
                   12582: 		|| ($embstyle eq 'prv')
                   12583: 		|| ($embstyle eq 'ign')) {
                   12584: 		#do nothing with these
                   12585: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12586: 		|| ($embstyle eq 'emb')
                   12587: 		|| ($embstyle eq 'wrp')) {
                   12588: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12589: 	    } elsif ($embstyle eq 'unk'
                   12590: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12591: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12592: 	    } else {
1.718     www      12593: #		&logthis("Got a blank emb style");
1.695     albertel 12594: 	    }
1.694     albertel 12595: 	}
1.1298    raeburn  12596:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
                   12597:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 12598:     }
1.31      www      12599:     return $thisfn;
1.12      www      12600: }
                   12601: 
1.787     albertel 12602: sub clutter_with_no_wrapper {
                   12603:     my $uri = &clutter(shift);
                   12604:     if ($uri =~ m-^/adm/-) {
                   12605: 	$uri =~ s-^/adm/wrapper/-/-;
                   12606: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12607:     }
                   12608:     return $uri;
                   12609: }
                   12610: 
1.557     albertel 12611: sub freeze_escape {
                   12612:     my ($value)=@_;
                   12613:     if (ref($value)) {
                   12614: 	$value=&nfreeze($value);
                   12615: 	return '__FROZEN__'.&escape($value);
                   12616:     }
                   12617:     return &escape($value);
                   12618: }
                   12619: 
1.11      www      12620: 
1.557     albertel 12621: sub thaw_unescape {
                   12622:     my ($value)=@_;
                   12623:     if ($value =~ /^__FROZEN__/) {
                   12624: 	substr($value,0,10,undef);
                   12625: 	$value=&unescape($value);
                   12626: 	return &thaw($value);
                   12627:     }
                   12628:     return &unescape($value);
                   12629: }
                   12630: 
1.436     albertel 12631: sub correct_line_ends {
                   12632:     my ($result)=@_;
                   12633:     $$result =~s/\r\n/\n/mg;
                   12634:     $$result =~s/\r/\n/mg;
1.415     albertel 12635: }
1.1       albertel 12636: # ================================================================ Main Program
                   12637: 
1.184     www      12638: sub goodbye {
1.204     albertel 12639:    &logthis("Starting Shut down");
1.443     albertel 12640: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12641:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12642: #converted
1.599     albertel 12643: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12644:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12645: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12646: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12647: #1.1 only
1.870     albertel 12648: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12649: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12650: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12651: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12652:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12653:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12654:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12655:    &flushcourselogs();
                   12656:    &logthis("Shutting down");
                   12657: }
                   12658: 
1.852     albertel 12659: sub get_dns {
1.1210    raeburn  12660:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12661:     if (!$ignore_cache) {
                   12662: 	my ($content,$cached)=
                   12663: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12664: 	if ($cached) {
1.1210    raeburn  12665: 	    &$func($content,$hashref);
1.869     albertel 12666: 	    return;
                   12667: 	}
                   12668:     }
                   12669: 
                   12670:     my %alldns;
1.852     albertel 12671:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12672:     foreach my $dns (<$config>) {
                   12673: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12674:         my $line = $1;
                   12675:         my ($host,$protocol) = split(/:/,$line);
                   12676:         if ($protocol ne 'https') {
                   12677:             $protocol = 'http';
                   12678:         }
                   12679: 	$alldns{$host} = $protocol;
1.869     albertel 12680:     }
                   12681:     while (%alldns) {
1.1263    raeburn  12682: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12683: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12684:         $ua->timeout(30);
1.979     raeburn  12685: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12686: 	my $response=$ua->request($request);
1.979     raeburn  12687:         delete($alldns{$dns});
1.852     albertel 12688: 	next if ($response->is_error());
                   12689: 	my @content = split("\n",$response->content);
1.1210    raeburn  12690: 	unless ($nocache) {
1.1219    raeburn  12691: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  12692: 	}
                   12693: 	&$func(\@content,$hashref);
1.869     albertel 12694: 	return;
1.852     albertel 12695:     }
                   12696:     close($config);
1.871     albertel 12697:     my $which = (split('/',$url))[3];
                   12698:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12699:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12700:     my @content = <$config>;
1.1210    raeburn  12701:     &$func(\@content,$hashref);
                   12702:     return;
                   12703: }
                   12704: 
                   12705: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  12706: sub parse_dns_checksums_tab {
1.1210    raeburn  12707:     my ($lines,$hashref) = @_;
1.1264    raeburn  12708:     my $lonhost = $perlvar{'lonHostID'};
                   12709:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  12710:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  12711:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12712:     my $webconfdir = '/etc/httpd/conf';
                   12713:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12714:         $webconfdir = '/etc/apache2';
                   12715:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12716:         if ($1 >= 10) {
                   12717:             $webconfdir = '/etc/apache2';
                   12718:         }
                   12719:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12720:         if ($1 >= 10.0) {
                   12721:             $webconfdir = '/etc/apache2';
                   12722:         }
                   12723:     }
1.1210    raeburn  12724:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12725:     my (%chksum,%revnum);
                   12726:     if (ref($lines) eq 'ARRAY') {
                   12727:         chomp(@{$lines});
1.1238    raeburn  12728:         my $version = shift(@{$lines});
                   12729:         if ($version eq $release) {  
1.1210    raeburn  12730:             foreach my $line (@{$lines}) {
1.1238    raeburn  12731:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  12732:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12733:                     if ($webconfdir eq '/etc/apache2') {
                   12734:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12735:                     }
                   12736:                 }
1.1238    raeburn  12737:                 $chksum{$file} = $shasum;
                   12738:                 $revnum{$file} = $version;
1.1210    raeburn  12739:             }
                   12740:             if (ref($hashref) eq 'HASH') {
                   12741:                 %{$hashref} = (
                   12742:                                 sums     => \%chksum,
                   12743:                                 versions => \%revnum,
                   12744:                               );
                   12745:             }
                   12746:         }
                   12747:     }
1.869     albertel 12748:     return;
1.852     albertel 12749: }
1.1210    raeburn  12750: 
                   12751: sub fetch_dns_checksums {
1.1238    raeburn  12752:     my %checksums;
                   12753:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  12754:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  12755:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12756:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  12757:              \%checksums);
1.1210    raeburn  12758:     return \%checksums;
                   12759: }
                   12760: 
1.327     albertel 12761: # ------------------------------------------------------------ Read domain file
                   12762: {
1.852     albertel 12763:     my $loaded;
1.846     albertel 12764:     my %domain;
                   12765: 
1.852     albertel 12766:     sub parse_domain_tab {
                   12767: 	my ($lines) = @_;
                   12768: 	foreach my $line (@$lines) {
                   12769: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12770: 
1.846     albertel 12771: 	    chomp($line);
1.852     albertel 12772: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12773: 	    my %this_domain;
                   12774: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12775: 			       'lang_def', 'city', 'longi', 'lati',
                   12776: 			       'primary') {
                   12777: 		$this_domain{$field} = shift(@elements);
                   12778: 	    }
                   12779: 	    $domain{$name} = \%this_domain;
1.852     albertel 12780: 	}
                   12781:     }
1.864     albertel 12782: 
                   12783:     sub reset_domain_info {
                   12784: 	undef($loaded);
                   12785: 	undef(%domain);
                   12786:     }
                   12787: 
1.852     albertel 12788:     sub load_domain_tab {
1.1293    raeburn  12789: 	my ($ignore_cache,$nocache) = @_;
                   12790: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12791: 	my $fh;
                   12792: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12793: 	    my @lines = <$fh>;
                   12794: 	    &parse_domain_tab(\@lines);
1.448     albertel 12795: 	}
1.852     albertel 12796: 	close($fh);
                   12797: 	$loaded = 1;
1.327     albertel 12798:     }
1.846     albertel 12799: 
                   12800:     sub domain {
1.852     albertel 12801: 	&load_domain_tab() if (!$loaded);
                   12802: 
1.846     albertel 12803: 	my ($name,$what) = @_;
                   12804: 	return if ( !exists($domain{$name}) );
                   12805: 
                   12806: 	if (!$what) {
                   12807: 	    return $domain{$name}{'description'};
                   12808: 	}
                   12809: 	return $domain{$name}{$what};
                   12810:     }
1.974     raeburn  12811: 
                   12812:     sub domain_info {
                   12813:         &load_domain_tab() if (!$loaded);
                   12814:         return %domain;
                   12815:     }
                   12816: 
1.327     albertel 12817: }
                   12818: 
                   12819: 
1.1       albertel 12820: # ------------------------------------------------------------- Read hosts file
                   12821: {
1.838     albertel 12822:     my %hostname;
1.844     albertel 12823:     my %hostdom;
1.845     albertel 12824:     my %libserv;
1.852     albertel 12825:     my $loaded;
1.888     albertel 12826:     my %name_to_host;
1.1074    raeburn  12827:     my %internetdom;
1.1107    raeburn  12828:     my %LC_dns_serv;
1.852     albertel 12829: 
                   12830:     sub parse_hosts_tab {
                   12831: 	my ($file) = @_;
                   12832: 	foreach my $configline (@$file) {
                   12833: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12834:             chomp($configline);
                   12835: 	    if ($configline =~ /^\^/) {
                   12836:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12837:                     $LC_dns_serv{$1} = 1;
                   12838:                 }
                   12839:                 next;
                   12840:             }
1.1074    raeburn  12841: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12842: 	    $name=~s/\s//g;
                   12843: 	    if ($id && $domain && $role && $name) {
                   12844: 		$hostname{$id}=$name;
1.888     albertel 12845: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12846: 		$hostdom{$id}=$domain;
                   12847: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12848:                 if (defined($protocol)) {
                   12849:                     if ($protocol eq 'https') {
                   12850:                         $protocol{$id} = $protocol;
                   12851:                     } else {
                   12852:                         $protocol{$id} = 'http'; 
                   12853:                     }
1.968     raeburn  12854:                 } else {
1.969     raeburn  12855:                     $protocol{$id} = 'http';
1.968     raeburn  12856:                 }
1.1074    raeburn  12857:                 if (defined($intdom)) {
                   12858:                     $internetdom{$id} = $intdom;
                   12859:                 }
1.852     albertel 12860: 	    }
                   12861: 	}
                   12862:     }
1.864     albertel 12863:     
                   12864:     sub reset_hosts_info {
1.897     albertel 12865: 	&purge_remembered();
1.864     albertel 12866: 	&reset_domain_info();
                   12867: 	&reset_hosts_ip_info();
1.892     albertel 12868: 	undef(%name_to_host);
1.864     albertel 12869: 	undef(%hostname);
                   12870: 	undef(%hostdom);
                   12871: 	undef(%libserv);
                   12872: 	undef($loaded);
                   12873:     }
1.1       albertel 12874: 
1.852     albertel 12875:     sub load_hosts_tab {
1.1293    raeburn  12876: 	my ($ignore_cache,$nocache) = @_;
                   12877: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 12878: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12879: 	my @config = <$config>;
                   12880: 	&parse_hosts_tab(\@config);
                   12881: 	close($config);
                   12882: 	$loaded=1;
1.1       albertel 12883:     }
1.852     albertel 12884: 
1.838     albertel 12885:     sub hostname {
1.852     albertel 12886: 	&load_hosts_tab() if (!$loaded);
                   12887: 
1.838     albertel 12888: 	my ($lonid) = @_;
                   12889: 	return $hostname{$lonid};
                   12890:     }
1.845     albertel 12891: 
1.838     albertel 12892:     sub all_hostnames {
1.852     albertel 12893: 	&load_hosts_tab() if (!$loaded);
                   12894: 
1.838     albertel 12895: 	return %hostname;
                   12896:     }
1.845     albertel 12897: 
1.888     albertel 12898:     sub all_names {
1.1293    raeburn  12899:         my ($ignore_cache,$nocache) = @_;
                   12900: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 12901: 
                   12902: 	return %name_to_host;
                   12903:     }
                   12904: 
1.974     raeburn  12905:     sub all_host_domain {
                   12906:         &load_hosts_tab() if (!$loaded);
                   12907:         return %hostdom;
                   12908:     }
                   12909: 
1.845     albertel 12910:     sub is_library {
1.852     albertel 12911: 	&load_hosts_tab() if (!$loaded);
                   12912: 
1.845     albertel 12913: 	return exists($libserv{$_[0]});
                   12914:     }
                   12915: 
                   12916:     sub all_library {
1.852     albertel 12917: 	&load_hosts_tab() if (!$loaded);
                   12918: 
1.845     albertel 12919: 	return %libserv;
                   12920:     }
                   12921: 
1.1062    droeschl 12922:     sub unique_library {
                   12923: 	#2x reverse removes all hostnames that appear more than once
                   12924:         my %unique = reverse &all_library();
                   12925:         return reverse %unique;
                   12926:     }
                   12927: 
1.841     albertel 12928:     sub get_servers {
1.852     albertel 12929: 	&load_hosts_tab() if (!$loaded);
                   12930: 
1.841     albertel 12931: 	my ($domain,$type) = @_;
                   12932: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12933: 	                                          : %hostname;
                   12934: 	my %result;
1.842     albertel 12935: 	if (ref($domain) eq 'ARRAY') {
                   12936: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12937: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12938: 		    $result{$host} = $hostname;
                   12939: 		}
                   12940: 	    }
                   12941: 	} else {
                   12942: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12943: 		if ($hostdom{$host} eq $domain) {
                   12944: 		    $result{$host} = $hostname;
                   12945: 		}
1.841     albertel 12946: 	    }
                   12947: 	}
                   12948: 	return %result;
                   12949:     }
1.845     albertel 12950: 
1.1062    droeschl 12951:     sub get_unique_servers {
                   12952:         my %unique = reverse &get_servers(@_);
                   12953: 	return reverse %unique;
                   12954:     }
                   12955: 
1.844     albertel 12956:     sub host_domain {
1.852     albertel 12957: 	&load_hosts_tab() if (!$loaded);
                   12958: 
1.844     albertel 12959: 	my ($lonid) = @_;
                   12960: 	return $hostdom{$lonid};
                   12961:     }
                   12962: 
1.841     albertel 12963:     sub all_domains {
1.852     albertel 12964: 	&load_hosts_tab() if (!$loaded);
                   12965: 
1.841     albertel 12966: 	my %seen;
                   12967: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12968: 	return @uniq;
                   12969:     }
1.1074    raeburn  12970: 
                   12971:     sub internet_dom {
                   12972:         &load_hosts_tab() if (!$loaded);
                   12973: 
                   12974:         my ($lonid) = @_;
                   12975:         return $internetdom{$lonid};
                   12976:     }
1.1107    raeburn  12977: 
                   12978:     sub is_LC_dns {
                   12979:         &load_hosts_tab() if (!$loaded);
                   12980: 
                   12981:         my ($hostname) = @_;
                   12982:         return exists($LC_dns_serv{$hostname});
                   12983:     }
                   12984: 
1.1       albertel 12985: }
                   12986: 
1.847     albertel 12987: { 
                   12988:     my %iphost;
1.856     albertel 12989:     my %name_to_ip;
                   12990:     my %lonid_to_ip;
1.869     albertel 12991: 
1.847     albertel 12992:     sub get_hosts_from_ip {
                   12993: 	my ($ip) = @_;
                   12994: 	my %iphosts = &get_iphost();
                   12995: 	if (ref($iphosts{$ip})) {
                   12996: 	    return @{$iphosts{$ip}};
                   12997: 	}
                   12998: 	return;
1.839     albertel 12999:     }
1.864     albertel 13000:     
                   13001:     sub reset_hosts_ip_info {
                   13002: 	undef(%iphost);
                   13003: 	undef(%name_to_ip);
                   13004: 	undef(%lonid_to_ip);
                   13005:     }
1.856     albertel 13006: 
                   13007:     sub get_host_ip {
                   13008: 	my ($lonid) = @_;
                   13009: 	if (exists($lonid_to_ip{$lonid})) {
                   13010: 	    return $lonid_to_ip{$lonid};
                   13011: 	}
                   13012: 	my $name=&hostname($lonid);
                   13013:    	my $ip = gethostbyname($name);
                   13014: 	return if (!$ip || length($ip) ne 4);
                   13015: 	$ip=inet_ntoa($ip);
                   13016: 	$name_to_ip{$name}   = $ip;
                   13017: 	$lonid_to_ip{$lonid} = $ip;
                   13018: 	return $ip;
                   13019:     }
1.847     albertel 13020:     
                   13021:     sub get_iphost {
1.1293    raeburn  13022: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13023: 
1.869     albertel 13024: 	if (!$ignore_cache) {
                   13025: 	    if (%iphost) {
                   13026: 		return %iphost;
                   13027: 	    }
                   13028: 	    my ($ip_info,$cached)=
                   13029: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13030: 	    if ($cached) {
                   13031: 		%iphost      = %{$ip_info->[0]};
                   13032: 		%name_to_ip  = %{$ip_info->[1]};
                   13033: 		%lonid_to_ip = %{$ip_info->[2]};
                   13034: 		return %iphost;
                   13035: 	    }
                   13036: 	}
1.894     albertel 13037: 
                   13038: 	# get yesterday's info for fallback
                   13039: 	my %old_name_to_ip;
                   13040: 	my ($ip_info,$cached)=
                   13041: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13042: 	if ($cached) {
                   13043: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13044: 	}
                   13045: 
1.1293    raeburn  13046: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13047: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13048: 	    my $ip;
                   13049: 	    if (!exists($name_to_ip{$name})) {
                   13050: 		$ip = gethostbyname($name);
                   13051: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13052: 		    if (defined($old_name_to_ip{$name})) {
                   13053: 			$ip = $old_name_to_ip{$name};
                   13054: 			&logthis("Can't find $name defaulting to old $ip");
                   13055: 		    } else {
                   13056: 			&logthis("Name $name no IP found");
                   13057: 			next;
                   13058: 		    }
                   13059: 		} else {
                   13060: 		    $ip=inet_ntoa($ip);
1.847     albertel 13061: 		}
                   13062: 		$name_to_ip{$name} = $ip;
                   13063: 	    } else {
                   13064: 		$ip = $name_to_ip{$name};
1.653     albertel 13065: 	    }
1.888     albertel 13066: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13067: 		$lonid_to_ip{$id} = $ip;
                   13068: 	    }
                   13069: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13070: 	}
1.1293    raeburn  13071:         unless ($nocache) {
                   13072: 	    &do_cache_new('iphost','iphost',
                   13073: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13074: 		          48*60*60);
                   13075:         }
1.869     albertel 13076: 
1.847     albertel 13077: 	return %iphost;
1.598     albertel 13078:     }
                   13079: 
1.992     raeburn  13080:     #
                   13081:     #  Given a DNS returns the loncapa host name for that DNS 
                   13082:     # 
                   13083:     sub host_from_dns {
                   13084:         my ($dns) = @_;
                   13085:         my @hosts;
                   13086:         my $ip;
                   13087: 
1.993     raeburn  13088:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13089:             $ip = $name_to_ip{$dns};
                   13090:         }
                   13091:         if (!$ip) {
                   13092:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13093:             if (length($ip) == 4) { 
                   13094: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13095:             }
                   13096:         }
                   13097:         if ($ip) {
                   13098: 	    @hosts = get_hosts_from_ip($ip);
                   13099: 	    return $hosts[0];
                   13100:         }
                   13101:         return undef;
1.986     foxr     13102:     }
1.992     raeburn  13103: 
1.1074    raeburn  13104:     sub get_internet_names {
                   13105:         my ($lonid) = @_;
                   13106:         return if ($lonid eq '');
                   13107:         my ($idnref,$cached)=
                   13108:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13109:         if ($cached) {
                   13110:             return $idnref;
                   13111:         }
                   13112:         my $ip = &get_host_ip($lonid);
                   13113:         my @hosts = &get_hosts_from_ip($ip);
                   13114:         my %iphost = &get_iphost();
                   13115:         my (@idns,%seen);
                   13116:         foreach my $id (@hosts) {
                   13117:             my $dom = &host_domain($id);
                   13118:             my $prim_id = &domain($dom,'primary');
                   13119:             my $prim_ip = &get_host_ip($prim_id);
                   13120:             next if ($seen{$prim_ip});
                   13121:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13122:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13123:                     my $intdom = &internet_dom($id);
                   13124:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13125:                         push(@idns,$intdom);
                   13126:                     }
                   13127:                 }
                   13128:             }
                   13129:             $seen{$prim_ip} = 1;
                   13130:         }
1.1219    raeburn  13131:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13132:     }
                   13133: 
1.986     foxr     13134: }
                   13135: 
1.1079    raeburn  13136: sub all_loncaparevs {
1.1249    raeburn  13137:     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  13138: }
                   13139: 
1.1227    raeburn  13140: # ---------------------------------------------------------- Read loncaparev table
                   13141: {
                   13142:     sub load_loncaparevs { 
                   13143:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   13144:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   13145:                 while (my $configline=<$config>) {
                   13146:                     chomp($configline);
                   13147:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13148:                     $loncaparevs{$hostid}=$loncaparev;
                   13149:                 }
                   13150:                 close($config);
                   13151:             }
                   13152:         }
                   13153:     }
                   13154: }
                   13155: 
                   13156: # ---------------------------------------------------------- Read serverhostID table
                   13157: {
                   13158:     sub load_serverhomeIDs {
                   13159:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   13160:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   13161:                 while (my $configline=<$config>) {
                   13162:                     chomp($configline);
                   13163:                     my ($name,$id)=split(/:/,$configline);
                   13164:                     $serverhomeIDs{$name}=$id;
                   13165:                 }
                   13166:                 close($config);
                   13167:             }
                   13168:         }
                   13169:     }
                   13170: }
                   13171: 
                   13172: 
1.862     albertel 13173: BEGIN {
                   13174: 
                   13175: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13176:     unless ($readit) {
                   13177: {
                   13178:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13179:     %perlvar = (%perlvar,%{$configvars});
                   13180: }
                   13181: 
                   13182: 
1.1       albertel 13183: # ------------------------------------------------------ Read spare server file
                   13184: {
1.448     albertel 13185:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13186: 
                   13187:     while (my $configline=<$config>) {
                   13188:        chomp($configline);
1.284     matthew  13189:        if ($configline) {
1.784     albertel 13190: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13191: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13192: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13193:        }
                   13194:     }
1.448     albertel 13195:     close($config);
1.1       albertel 13196: }
1.11      www      13197: # ------------------------------------------------------------ Read permissions
                   13198: {
1.448     albertel 13199:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13200: 
                   13201:     while (my $configline=<$config>) {
1.448     albertel 13202: 	chomp($configline);
                   13203: 	if ($configline) {
                   13204: 	    my ($role,$perm)=split(/ /,$configline);
                   13205: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13206: 	}
1.11      www      13207:     }
1.448     albertel 13208:     close($config);
1.11      www      13209: }
                   13210: 
                   13211: # -------------------------------------------- Read plain texts for permissions
                   13212: {
1.448     albertel 13213:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13214: 
                   13215:     while (my $configline=<$config>) {
1.448     albertel 13216: 	chomp($configline);
                   13217: 	if ($configline) {
1.742     raeburn  13218: 	    my ($short,@plain)=split(/:/,$configline);
                   13219:             %{$prp{$short}} = ();
                   13220: 	    if (@plain > 0) {
                   13221:                 $prp{$short}{'std'} = $plain[0];
                   13222:                 for (my $i=1; $i<@plain; $i++) {
                   13223:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13224:                 }
                   13225:             }
1.448     albertel 13226: 	}
1.135     www      13227:     }
1.448     albertel 13228:     close($config);
1.135     www      13229: }
                   13230: 
                   13231: # ---------------------------------------------------------- Read package table
                   13232: {
1.448     albertel 13233:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13234: 
                   13235:     while (my $configline=<$config>) {
1.483     albertel 13236: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13237: 	chomp($configline);
                   13238: 	my ($short,$plain)=split(/:/,$configline);
                   13239: 	my ($pack,$name)=split(/\&/,$short);
                   13240: 	if ($plain ne '') {
                   13241: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13242: 	    $packagetab{$short}=$plain; 
                   13243: 	}
1.11      www      13244:     }
1.448     albertel 13245:     close($config);
1.329     matthew  13246: }
                   13247: 
1.1073    raeburn  13248: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  13249: 
                   13250: &load_loncaparevs();
1.1073    raeburn  13251: 
1.1074    raeburn  13252: # ---------------------------------------------------------- Read serverhostID table
                   13253: 
1.1227    raeburn  13254: &load_serverhomeIDs();
                   13255: 
                   13256: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13257: {
                   13258:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13259:     if (-e $file) {
                   13260:         my $parser = HTML::LCParser->new($file);
                   13261:         while (my $token = $parser->get_token()) {
                   13262:             if ($token->[0] eq 'S') {
                   13263:                 my $item = $token->[1];
                   13264:                 my $name = $token->[2]{'name'};
                   13265:                 my $value = $token->[2]{'value'};
1.1285    raeburn  13266:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  13267:                 my $namematch = $token->[2]{'namematch'};
                   13268:                 if ($item eq 'parameter') {
                   13269:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   13270:                         my $release = $parser->get_text();
                   13271:                         $release =~ s/(^\s*|\s*$ )//gx;
                   13272:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   13273:                     }
                   13274:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  13275:                     my $release = $parser->get_text();
                   13276:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  13277:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  13278:                 }
                   13279:             }
                   13280:         }
                   13281:     }
1.1073    raeburn  13282: }
                   13283: 
1.1138    raeburn  13284: # ---------------------------------------------------------- Read managers table
                   13285: {
                   13286:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   13287:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   13288:             while (my $configline=<$config>) {
                   13289:                 chomp($configline);
                   13290:                 next if ($configline =~ /^\#/);
                   13291:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13292:                     $managerstab{$configline} = 1;
                   13293:                 }
                   13294:             }
                   13295:             close($config);
                   13296:         }
                   13297:     }
                   13298: }
                   13299: 
1.329     matthew  13300: # ------------- set up temporary directory
                   13301: {
1.1117    foxr     13302:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13303: 
1.11      www      13304: }
                   13305: 
1.794     albertel 13306: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13307: 				'compress_threshold'=> 20_000,
                   13308:  			        });
1.185     www      13309: 
1.281     www      13310: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13311: $dumpcount=0;
1.958     www      13312: $locknum=0;
1.22      www      13313: 
1.163     harris41 13314: &logtouch();
1.672     albertel 13315: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13316: $readit=1;
1.564     albertel 13317:     {
                   13318: 	use integer;
                   13319: 	my $test=(2**32)+1;
1.568     albertel 13320: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13321: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13322:     }
1.195     www      13323: }
1.1       albertel 13324: }
1.179     www      13325: 
1.1       albertel 13326: 1;
1.191     harris41 13327: __END__
                   13328: 
1.243     albertel 13329: =pod
                   13330: 
1.191     harris41 13331: =head1 NAME
                   13332: 
1.243     albertel 13333: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13334: 
                   13335: =head1 SYNOPSIS
                   13336: 
1.243     albertel 13337: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13338: 
                   13339:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13340: 
1.243     albertel 13341: Common parameters:
                   13342: 
                   13343: =over 4
                   13344: 
                   13345: =item *
                   13346: 
                   13347: $uname : an internal username (if $cname expecting a course Id specifically)
                   13348: 
                   13349: =item *
                   13350: 
                   13351: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13352: 
                   13353: =item *
                   13354: 
                   13355: $symb : a resource instance identifier
                   13356: 
                   13357: =item *
                   13358: 
                   13359: $namespace : the name of a .db file that contains the data needed or
                   13360: being set.
                   13361: 
                   13362: =back
                   13363: 
1.394     bowersj2 13364: =head1 OVERVIEW
1.191     harris41 13365: 
1.394     bowersj2 13366: lonnet provides subroutines which interact with the
                   13367: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13368: about classes, users, and resources.
1.243     albertel 13369: 
                   13370: For many of these objects you can also use this to store data about
                   13371: them or modify them in various ways.
1.191     harris41 13372: 
1.394     bowersj2 13373: =head2 Symbs
1.191     harris41 13374: 
1.394     bowersj2 13375: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13376: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13377: map, the resource number of the resource in the map, and the URL of
                   13378: the resource itself. The latter is somewhat redundant, but might help
                   13379: if maps change.
                   13380: 
                   13381: An example is
                   13382: 
                   13383:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13384: 
                   13385: The respective map entry is
                   13386: 
                   13387:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13388:   title="Problem 2">
                   13389:  </resource>
                   13390: 
                   13391: Symbs are used by the random number generator, as well as to store and
                   13392: restore data specific to a certain instance of for example a problem.
                   13393: 
                   13394: =head2 Storing And Retrieving Data
                   13395: 
                   13396: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13397: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13398: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13399: is is the non-critical message twin of cstore. These functions are for
                   13400: handlers to store a perl hash to a user's permanent data space in an
                   13401: easy manner, and to retrieve it again on another call. It is expected
                   13402: that a handler would use this once at the beginning to retrieve data,
                   13403: and then again once at the end to send only the new data back.
                   13404: 
                   13405: The data is stored in the user's data directory on the user's
                   13406: homeserver under the ID of the course.
                   13407: 
                   13408: The hash that is returned by restore will have all of the previous
                   13409: value for all of the elements of the hash.
                   13410: 
                   13411: Example:
                   13412: 
                   13413:  #creating a hash
                   13414:  my %hash;
                   13415:  $hash{'foo'}='bar';
                   13416: 
                   13417:  #storing it
                   13418:  &Apache::lonnet::cstore(\%hash);
                   13419: 
                   13420:  #changing a value
                   13421:  $hash{'foo'}='notbar';
                   13422: 
                   13423:  #adding a new value
                   13424:  $hash{'bar'}='foo';
                   13425:  &Apache::lonnet::cstore(\%hash);
                   13426: 
                   13427:  #retrieving the hash
                   13428:  my %history=&Apache::lonnet::restore();
                   13429: 
                   13430:  #print the hash
                   13431:  foreach my $key (sort(keys(%history))) {
                   13432:    print("\%history{$key} = $history{$key}");
                   13433:  }
                   13434: 
                   13435: Will print out:
1.191     harris41 13436: 
1.394     bowersj2 13437:  %history{1:foo} = bar
                   13438:  %history{1:keys} = foo:timestamp
                   13439:  %history{1:timestamp} = 990455579
                   13440:  %history{2:bar} = foo
                   13441:  %history{2:foo} = notbar
                   13442:  %history{2:keys} = foo:bar:timestamp
                   13443:  %history{2:timestamp} = 990455580
                   13444:  %history{bar} = foo
                   13445:  %history{foo} = notbar
                   13446:  %history{timestamp} = 990455580
                   13447:  %history{version} = 2
                   13448: 
                   13449: Note that the special hash entries C<keys>, C<version> and
                   13450: C<timestamp> were added to the hash. C<version> will be equal to the
                   13451: total number of versions of the data that have been stored. The
                   13452: C<timestamp> attribute will be the UNIX time the hash was
                   13453: stored. C<keys> is available in every historical section to list which
                   13454: keys were added or changed at a specific historical revision of a
                   13455: hash.
                   13456: 
                   13457: B<Warning>: do not store the hash that restore returns directly. This
                   13458: will cause a mess since it will restore the historical keys as if the
                   13459: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13460: 
1.394     bowersj2 13461: Calling convention:
1.191     harris41 13462: 
1.1225    raeburn  13463:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  13464:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13465: 
1.394     bowersj2 13466: For more detailed information, see lonnet specific documentation.
1.191     harris41 13467: 
1.394     bowersj2 13468: =head1 RETURN MESSAGES
1.191     harris41 13469: 
1.394     bowersj2 13470: =over 4
1.191     harris41 13471: 
1.394     bowersj2 13472: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13473: 
1.394     bowersj2 13474: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13475: when the connection is brought back up
1.191     harris41 13476: 
1.394     bowersj2 13477: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13478: for later delivery
1.191     harris41 13479: 
1.967     bisitz   13480: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13481: 
1.394     bowersj2 13482: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13483: that was requested
1.191     harris41 13484: 
1.243     albertel 13485: =back
1.191     harris41 13486: 
1.243     albertel 13487: =head1 PUBLIC SUBROUTINES
1.191     harris41 13488: 
1.243     albertel 13489: =head2 Session Environment Functions
1.191     harris41 13490: 
1.243     albertel 13491: =over 4
1.191     harris41 13492: 
1.394     bowersj2 13493: =item * 
                   13494: X<appenv()>
1.949     raeburn  13495: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13496: the user envirnoment file, and will be restored for each access this
1.620     albertel 13497: user makes during this session, also modifies the %env for the current
1.949     raeburn  13498: process. Optional rolesarrayref - if defined contains a reference to an array
                   13499: of roles which are exempt from the restriction on modifying user.role entries 
                   13500: in the user's environment.db and in %env.    
1.191     harris41 13501: 
                   13502: =item *
1.394     bowersj2 13503: X<delenv()>
1.987     raeburn  13504: B<delenv($delthis,$regexp)>: removes all items from the session
                   13505: environment file that begin with $delthis. If the 
                   13506: optional second arg - $regexp - is true, $delthis is treated as a 
                   13507: regular expression, otherwise \Q$delthis\E is used. 
                   13508: The values are also deleted from the current processes %env.
1.191     harris41 13509: 
1.795     albertel 13510: =item * get_env_multiple($name) 
                   13511: 
                   13512: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13513: values may be defined and end up as an array ref.
                   13514: 
                   13515: returns an array of values
                   13516: 
1.243     albertel 13517: =back
                   13518: 
                   13519: =head2 User Information
1.191     harris41 13520: 
1.243     albertel 13521: =over 4
1.191     harris41 13522: 
                   13523: =item *
1.394     bowersj2 13524: X<queryauthenticate()>
                   13525: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13526: authentication scheme
                   13527: 
                   13528: =item *
1.394     bowersj2 13529: X<authenticate()>
1.1073    raeburn  13530: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13531: authenticate user from domain's lib servers (first use the current
                   13532: one). C<$upass> should be the users password.
1.1073    raeburn  13533: $checkdefauth is optional (value is 1 if a check should be made to
                   13534:    authenticate user using default authentication method, and allow
                   13535:    account creation if username does not have account in the domain).
                   13536: $clientcancheckhost is optional (value is 1 if checking whether the
                   13537:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13538: 
                   13539: =item *
1.394     bowersj2 13540: X<homeserver()>
                   13541: B<homeserver($uname,$udom)>: find the server which has
                   13542: the user's directory and files (there must be only one), this caches
                   13543: the answer, and also caches if there is a borken connection.
1.191     harris41 13544: 
                   13545: =item *
1.394     bowersj2 13546: X<idget()>
1.1300    raeburn  13547: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   13548: a list of student/employee IDs or clicker IDs
                   13549: (student/employee IDs are a unique resource in a domain, there must be 
                   13550: only 1 ID per username, and only 1 username per ID in a specific domain).
                   13551: clickerIDs are not necessarily unique, as students might share clickers.
                   13552: (returns hash: id=>name,id=>name)
1.191     harris41 13553: 
                   13554: =item *
1.394     bowersj2 13555: X<idrget()>
                   13556: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13557: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13558: 
                   13559: =item *
1.394     bowersj2 13560: X<idput()>
1.1300    raeburn  13561: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   13562: names and associated student/employee IDs or clicker IDs.
                   13563: 
                   13564: =item *
                   13565: X<iddel()>
                   13566: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   13567: student/employee ID or clicker ID username look-ups from domain.
                   13568: The homeserver ($uhome) and namespace ($namespace) are optional.
                   13569: If no $uhome is provided, it will be determined usig &homeserver()
                   13570: for each user.  If no $namespace is provided, the default is ids.
                   13571: 
                   13572: =item *
                   13573: X<updateclickers()>
                   13574: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   13575: clicker ID-to-username look-ups in clickers.db on library server.
                   13576: Permitted actions are add or del (i.e., add or delete). The 
                   13577: clickers.db contains clickerID as keys (escaped), and each corresponding
                   13578: value is an escaped comma-separated list of usernames (for whom the
                   13579: library server is the homeserver), who registered that particular ID.
                   13580: If $critical is true, the update will be sent via &critical, otherwise
                   13581: &reply() will be used.
1.191     harris41 13582: 
                   13583: =item *
1.394     bowersj2 13584: X<rolesinit()>
1.1169    droeschl 13585: B<rolesinit($udom,$username)>: get user privileges.
                   13586: returns user role, first access and timer interval hashes
1.243     albertel 13587: 
                   13588: =item *
1.1171    droeschl 13589: X<privileged()>
                   13590: B<privileged($username,$domain)>: returns a true if user has a
                   13591: privileged and active role (i.e. su or dc), false otherwise.
                   13592: 
                   13593: =item *
1.551     albertel 13594: X<getsection()>
                   13595: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13596: course $cname, return section name/number or '' for "not in course"
                   13597: and '-1' for "no section"
                   13598: 
                   13599: =item *
1.394     bowersj2 13600: X<userenvironment()>
                   13601: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13602: passed in @what from the requested user's environment, returns a hash
                   13603: 
1.858     raeburn  13604: =item * 
                   13605: X<userlog_query()>
1.859     albertel 13606: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13607: activity.log file. %filters defines filters applied when parsing the
                   13608: log file. These can be start or end timestamps, or the type of action
                   13609: - log to look for Login or Logout events, check for Checkin or
                   13610: Checkout, role for role selection. The response is in the form
                   13611: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13612: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13613: 
1.243     albertel 13614: =back
                   13615: 
                   13616: =head2 User Roles
                   13617: 
                   13618: =over 4
                   13619: 
                   13620: =item *
                   13621: 
1.1284    raeburn  13622: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13623: returns codes for allowed actions.
                   13624: 
                   13625: The first argument is required, all others are optional.
                   13626: 
                   13627: $priv is the privilege being checked.
                   13628: $uri contains additional information about what is being checked for access (e.g.,
                   13629: URL, course ID etc.). 
                   13630: $symb is the unique resource instance identifier in a course; if needed,
                   13631: but not provided, it will be retrieved via a call to &symbread(). 
                   13632: $role is the role for which a priv is being checked (only used if priv is evb). 
                   13633: $clientip is the user's IP address (only used when checking for access to portfolio 
                   13634: files).
                   13635: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   13636: prevents recursive calls to &allowed.
                   13637: 
1.243     albertel 13638:  F: full access
                   13639:  U,I,K: authentication modes (cxx only)
                   13640:  '': forbidden
                   13641:  1: user needs to choose course
                   13642:  2: browse allowed
1.766     albertel 13643:  A: passphrase authentication needed
1.1284    raeburn  13644:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13645: 
                   13646: =item *
                   13647: 
1.1192    raeburn  13648: constructaccess($url,$setpriv) : check for access to construction space URL
                   13649: 
                   13650: See if the owner domain and name in the URL match those in the
                   13651: expected environment.  If so, return three element list
                   13652: ($ownername,$ownerdomain,$ownerhome).
                   13653: 
                   13654: Otherwise return the null string.
                   13655: 
                   13656: If second argument 'setpriv' is true, it assigns the privileges,
                   13657: and returns the same three element list, unless the owner has
                   13658: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13659: in which case the null string is returned.
                   13660: 
                   13661: =item *
                   13662: 
1.243     albertel 13663: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   13664: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   13665: and course level
                   13666: 
                   13667: =item *
                   13668: 
1.988     raeburn  13669: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13670: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13671: $type is Course (default) or Community.
1.988     raeburn  13672: If $forcedefault evaluates to true, text returned will be default 
                   13673: text for $type. Otherwise, if this is a course, the text returned 
                   13674: will be a custom name for the role (if defined in the course's 
                   13675: environment).  If no custom name is defined the default is returned.
                   13676:    
1.832     raeburn  13677: =item *
                   13678: 
1.1219    raeburn  13679: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13680: All arguments are optional. Returns a hash of a roles, either for
                   13681: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13682: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13683: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13684: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13685: For each key, value is set to colon-separated start and end times for
                   13686: the role.  If no username and domain are specified, will default to
1.934     raeburn  13687: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13688: of role statuses (active, future or previous), roles 
                   13689: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13690: to restrict the list of roles reported. If no array ref is 
                   13691: provided for types, will default to return only active roles.
1.834     albertel 13692: 
1.1195    raeburn  13693: =item *
                   13694: 
                   13695: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  13696: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   13697: 
                   13698: Additional optional arguments are: $type (if role checking is to be restricted 
                   13699: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  13700: available roles) or future (roles available in the future), and
                   13701: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  13702: have active Domain Coordinator role in course's domain or in additional
                   13703: domains (specified in 'Domains to check for privileged users' in course
                   13704: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13705: 
                   13706: =item *
                   13707: 
                   13708: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13709: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13710: $possdomains and $possroles are optional array refs -- to domains to check and
                   13711: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13712: users' roles.db to check for a dc or su role in any domain. This can be
                   13713: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13714: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13715: this then allows &privileged_by_domain() to be used, which caches the identity
                   13716: of privileged users, eliminating the need for repeated calls to &dump().
                   13717: 
                   13718: =item *
                   13719: 
                   13720: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13721: where the outer hash keys are domains specified in the $possdomains array ref,
                   13722: next inner hash keys are privileged roles specified in the $roles array ref,
                   13723: and the innermost hash contains key = value pairs for username:domain = end:start
                   13724: for active or future "privileged" users with that role in that domain. To avoid
                   13725: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13726: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  13727: 
1.243     albertel 13728: =back
                   13729: 
                   13730: =head2 User Modification
                   13731: 
                   13732: =over 4
                   13733: 
                   13734: =item *
                   13735: 
1.957     raeburn  13736: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13737: user for the level given by URL.  Optional start and end dates (leave empty
                   13738: string or zero for "no date")
1.191     harris41 13739: 
                   13740: =item *
                   13741: 
1.243     albertel 13742: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13743: change a users, password, possible return values are: ok,
                   13744: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13745: refused
1.191     harris41 13746: 
                   13747: =item *
                   13748: 
1.243     albertel 13749: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13750: 
                   13751: =item *
                   13752: 
1.1058    raeburn  13753: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13754:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13755: 
                   13756: will update user information (firstname,middlename,lastname,generation,
                   13757: permanentemail), and if forceid is true, student/employee ID also.
                   13758: A user's institutional affiliation(s) can also be updated.
                   13759: User information fields will not be overwritten with empty entries 
                   13760: unless the field is included in the $candelete array reference.
                   13761: This array is included when a single user is modified via "Manage Users",
                   13762: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13763: 
                   13764: =item *
                   13765: 
1.286     matthew  13766: modifystudent
                   13767: 
1.957     raeburn  13768: modify a student's enrollment and identification information.
1.1235    raeburn  13769: The course id is resolved based on the current user's environment.  
                   13770: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13771: associated with a course.
                   13772: 
1.297     matthew  13773: This call is essentially a wrapper for lonnet::modifyuser and
                   13774: lonnet::modify_student_enrollment
1.286     matthew  13775: 
                   13776: Inputs: 
                   13777: 
                   13778: =over 4
                   13779: 
1.957     raeburn  13780: =item B<$udom> Student's loncapa domain
1.286     matthew  13781: 
1.957     raeburn  13782: =item B<$uname> Student's loncapa login name
1.286     matthew  13783: 
1.964     bisitz   13784: =item B<$uid> Student/Employee ID
1.286     matthew  13785: 
1.957     raeburn  13786: =item B<$umode> Student's authentication mode
1.286     matthew  13787: 
1.957     raeburn  13788: =item B<$upass> Student's password
1.286     matthew  13789: 
1.957     raeburn  13790: =item B<$first> Student's first name
1.286     matthew  13791: 
1.957     raeburn  13792: =item B<$middle> Student's middle name
1.286     matthew  13793: 
1.957     raeburn  13794: =item B<$last> Student's last name
1.286     matthew  13795: 
1.957     raeburn  13796: =item B<$gene> Student's generation
1.286     matthew  13797: 
1.957     raeburn  13798: =item B<$usec> Student's section in course
1.286     matthew  13799: 
                   13800: =item B<$end> Unix time of the roles expiration
                   13801: 
                   13802: =item B<$start> Unix time of the roles start date
                   13803: 
                   13804: =item B<$forceid> If defined, allow $uid to be changed
                   13805: 
                   13806: =item B<$desiredhome> server to use as home server for student
                   13807: 
1.957     raeburn  13808: =item B<$email> Student's permanent e-mail address
                   13809: 
                   13810: =item B<$type> Type of enrollment (auto or manual)
                   13811: 
1.963     raeburn  13812: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13813: 
                   13814: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13815: 
1.963     raeburn  13816: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13817: 
1.963     raeburn  13818: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13819: 
1.1216    raeburn  13820: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13821: 
                   13822: =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  13823: 
1.286     matthew  13824: =back
1.297     matthew  13825: 
                   13826: =item *
                   13827: 
                   13828: modify_student_enrollment
                   13829: 
1.1235    raeburn  13830: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13831: 'role.request.course' must be defined for this function to proceed.
                   13832: 
                   13833: Inputs:
                   13834: 
                   13835: =over 4
                   13836: 
1.1235    raeburn  13837: =item $udom, student's domain
1.297     matthew  13838: 
1.1235    raeburn  13839: =item $uname, student's name
1.297     matthew  13840: 
1.1235    raeburn  13841: =item $uid, student's user id
1.297     matthew  13842: 
1.1235    raeburn  13843: =item $first, student's first name
1.297     matthew  13844: 
                   13845: =item $middle
                   13846: 
                   13847: =item $last
                   13848: 
                   13849: =item $gene
                   13850: 
                   13851: =item $usec
                   13852: 
                   13853: =item $end
                   13854: 
                   13855: =item $start
                   13856: 
1.957     raeburn  13857: =item $type
                   13858: 
                   13859: =item $locktype
                   13860: 
                   13861: =item $cid
                   13862: 
                   13863: =item $selfenroll
                   13864: 
                   13865: =item $context
                   13866: 
1.1216    raeburn  13867: =item $credits, number of credits student will earn from this class
                   13868: 
1.1314  ! raeburn  13869: =item $instsec, institutional course section code for student
        !          13870: 
1.297     matthew  13871: =back
                   13872: 
1.191     harris41 13873: 
                   13874: =item *
                   13875: 
1.243     albertel 13876: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13877: custom role; give a custom role to a user for the level given by URL.  Specify
                   13878: name and domain of role author, and role name
1.191     harris41 13879: 
                   13880: =item *
                   13881: 
1.243     albertel 13882: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13883: 
                   13884: =item *
                   13885: 
1.243     albertel 13886: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13887: 
                   13888: =back
                   13889: 
                   13890: =head2 Course Infomation
                   13891: 
                   13892: =over 4
1.191     harris41 13893: 
                   13894: =item *
                   13895: 
1.1118    foxr     13896: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13897: specified course id, including all environment settings for the
                   13898: course, the description of the course will be in the hash under the
                   13899: key 'description'
1.191     harris41 13900: 
1.1118    foxr     13901: $options is an optional parameter that if supplied is a hash reference that controls
                   13902: what how this function works.  It has the following key/values:
                   13903: 
                   13904: =over 4
                   13905: 
                   13906: =item freshen_cache
                   13907: 
                   13908: If defined, and the environment cache for the course is valid, it is 
                   13909: returned in the returned hash.
                   13910: 
                   13911: =item one_time
                   13912: 
                   13913: If defined, the last cache time is set to _now_
                   13914: 
                   13915: =item user
                   13916: 
                   13917: If defined, the supplied username is used instead of the current user.
                   13918: 
                   13919: 
                   13920: =back
                   13921: 
1.191     harris41 13922: =item *
                   13923: 
1.624     albertel 13924: resdata($name,$domain,$type,@which) : request for current parameter
                   13925: setting for a specific $type, where $type is either 'course' or 'user',
                   13926: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  13927: answers for 10 minutes.
1.243     albertel 13928: 
1.877     foxr     13929: =item *
                   13930: 
                   13931: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13932: data base, returning a hash that is keyed by the resource name and has
                   13933: values that are the resource value.  I believe that the timestamps and
                   13934: versions are also returned.
                   13935: 
1.1236    raeburn  13936: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13937: supplemental content area. This routine caches the number of files for 
                   13938: 10 minutes.
                   13939: 
1.243     albertel 13940: =back
                   13941: 
                   13942: =head2 Course Modification
                   13943: 
                   13944: =over 4
1.191     harris41 13945: 
                   13946: =item *
                   13947: 
1.243     albertel 13948: writecoursepref($courseid,%prefs) : write preferences (environment
                   13949: database) for a course
1.191     harris41 13950: 
                   13951: =item *
                   13952: 
1.1011    raeburn  13953: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13954: 
                   13955: =item *
                   13956: 
1.1038    raeburn  13957: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13958: 
1.1167    droeschl 13959: =item *
                   13960: 
                   13961: is_course($courseid), is_course($cdom, $cnum)
                   13962: 
                   13963: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13964: two component version $cdom, $cnum. It checks if the specified course exists.
                   13965: 
                   13966: Returns:
                   13967:     undef if the course doesn't exist, otherwise
                   13968:     in scalar context the combined courseid.
                   13969:     in list context the two components of the course identifier, domain and 
                   13970:     courseid.    
                   13971: 
1.243     albertel 13972: =back
                   13973: 
                   13974: =head2 Resource Subroutines
                   13975: 
                   13976: =over 4
1.191     harris41 13977: 
                   13978: =item *
                   13979: 
1.243     albertel 13980: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13981: 
                   13982: =item *
                   13983: 
1.243     albertel 13984: repcopy($filename) : subscribes to the requested file, and attempts to
                   13985: replicate from the owning library server, Might return
1.607     raeburn  13986: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13987: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13988: resource. Expects the local filesystem pathname
                   13989: (/home/httpd/html/res/....)
                   13990: 
                   13991: =back
                   13992: 
                   13993: =head2 Resource Information
                   13994: 
                   13995: =over 4
1.191     harris41 13996: 
                   13997: =item *
                   13998: 
1.1228    raeburn  13999: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14000: and returns the value of a variety of different possible values,
                   14001: $varname should be a request string, and the other parameters can be
                   14002: used to specify who and what one is asking about. Ordinarily, $cid 
                   14003: does not need to be specified, as it is retrived from 
                   14004: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14005: within lonuserstate::loadmap() when initializing a course, before
                   14006: $env{'request.course.id'} has been set, so it needs to be provided
                   14007: in that one case.
1.243     albertel 14008: 
                   14009: Possible values for $varname are environment.lastname (or other item
                   14010: from the envirnment hash), user.name (or someother aspect about the
                   14011: user), resource.0.maxtries (or some other part and parameter of a
                   14012: resource)
1.204     albertel 14013: 
                   14014: =item *
                   14015: 
1.243     albertel 14016: directcondval($number) : get current value of a condition; reads from a state
                   14017: string
1.204     albertel 14018: 
                   14019: =item *
                   14020: 
1.243     albertel 14021: condval($condidx) : value of condition index based on state
1.204     albertel 14022: 
                   14023: =item *
                   14024: 
1.243     albertel 14025: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14026: resource's metadata, $what should be either a specific key, or either
                   14027: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14028: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14029: 
                   14030: this function automatically caches all requests
1.191     harris41 14031: 
                   14032: =item *
                   14033: 
1.243     albertel 14034: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14035: network of library servers; returns file handle of where SQL and regex results
                   14036: will be stored for query
1.191     harris41 14037: 
                   14038: =item *
                   14039: 
1.1282    raeburn  14040: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   14041: return symbolic list entry (all arguments optional). 
                   14042: 
                   14043: Args: filename is the filename (including path) for the file for which a symb 
                   14044: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   14045: to check access status if more than one resource was found in the bighash 
                   14046: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   14047: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   14048: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14049: cause possible symbs to be checked to determine if they are subject to content
                   14050: blocking, if so they will not be included as possible symbs; possibles is a
                   14051: ref to a hash, which, as a side effect, will be populated with all possible 
                   14052: symbs (content blocking not tested).
                   14053:  
1.243     albertel 14054: returns the data handle
1.191     harris41 14055: 
                   14056: =item *
                   14057: 
1.1190    raeburn  14058: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   14059: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14060: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  14061: on failure, user must be in a course, as it assumes the existence of
                   14062: the course initial hash, and uses $env('request.course.id'}.  The third
                   14063: arg is an optional reference to a scalar.  If this arg is passed in the 
                   14064: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14065: encrypted; otherwise it will be null.  
1.191     harris41 14066: 
                   14067: =item *
                   14068: 
1.243     albertel 14069: symbclean($symb) : removes versions numbers from a symb, returns the
                   14070: cleaned symb
1.191     harris41 14071: 
                   14072: =item *
                   14073: 
1.243     albertel 14074: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14075: course map, user must be in a course for it to work.
1.191     harris41 14076: 
                   14077: =item *
                   14078: 
1.243     albertel 14079: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14080: 
                   14081: =item *
                   14082: 
1.243     albertel 14083: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14084: a random seed, all arguments are optional, if they aren't sent it uses the
                   14085: environment to derive them. Note: if symb isn't sent and it can't get one
                   14086: from &symbread it will use the current time as its return value
1.191     harris41 14087: 
                   14088: =item *
                   14089: 
1.243     albertel 14090: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14091: unfakeable, receipt
1.191     harris41 14092: 
                   14093: =item *
                   14094: 
1.620     albertel 14095: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14096: 
                   14097: =item *
                   14098: 
1.243     albertel 14099: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14100: 
                   14101: =item *
                   14102: 
1.243     albertel 14103: 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 14104: 
                   14105: =item *
                   14106: 
1.243     albertel 14107: 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 14108: 
                   14109: =item *
                   14110: 
1.243     albertel 14111: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14112: 
                   14113: =item *
                   14114: 
1.243     albertel 14115: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14116: forcing spreadsheet to reevaluate the resource scores next time.
                   14117: 
1.1195    raeburn  14118: =item * 
                   14119: 
1.1196    raeburn  14120: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14121: when viewing in course context.
1.1195    raeburn  14122: 
1.1196    raeburn  14123:  input: six args -- filename (decluttered), course number, course domain,
                   14124:                     url, symb (if registered) and group (if this is a 
                   14125:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  14126: 
1.1196    raeburn  14127:  output: array of five scalars --
1.1195    raeburn  14128:          $cfile -- url for file editing if editable on current server
                   14129:          $home -- homeserver of resource (i.e., for author if published,
                   14130:                                           or course if uploaded.).
                   14131:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  14132:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   14133:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  14134: 
                   14135: =item *
                   14136: 
                   14137: is_course_upload($file,$cnum,$cdom)
                   14138: 
                   14139: Used in course context to determine if current file was uploaded to 
                   14140: the course (i.e., would be found in /userfiles/docs on the course's 
                   14141: homeserver.
                   14142: 
                   14143:   input: 3 args -- filename (decluttered), course number and course domain.
                   14144:   output: boolean -- 1 if file was uploaded.
                   14145: 
1.243     albertel 14146: =back
                   14147: 
                   14148: =head2 Storing/Retreiving Data
                   14149: 
                   14150: =over 4
1.191     harris41 14151: 
                   14152: =item *
                   14153: 
1.1269    raeburn  14154: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   14155: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14156: the remaining args aren't required and if they aren't passed or are '' they will
                   14157: be derived from the env (with the exception of $laststore, which is an 
                   14158: optional arg used when a user's submission is stored in grading).
                   14159: $laststore is $version=$timestamp, where $version is the most recent version
                   14160: number retrieved for the corresponding $symb in the $namespace db file, and
                   14161: $timestamp is the timestamp for that transaction (UNIX time).
                   14162: $laststore is currently only passed when cstore() is called by 
                   14163: structuretags::finalize_storage().
1.191     harris41 14164: 
                   14165: =item *
                   14166: 
1.1269    raeburn  14167: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   14168: but uses critical subroutine
1.191     harris41 14169: 
                   14170: =item *
                   14171: 
1.243     albertel 14172: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14173: all args are optional
1.191     harris41 14174: 
                   14175: =item *
                   14176: 
1.717     albertel 14177: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14178: dumps the complete (or key matching regexp) namespace into a hash
                   14179: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14180: normally &store()ed into
                   14181: 
                   14182: $range should be either an integer '100' (give me the first 100
                   14183:                                            matching records)
                   14184:               or be  two integers sperated by a - with no spaces
                   14185:                  '30-50' (give me the 30th through the 50th matching
                   14186:                           records)
                   14187: 
                   14188: 
                   14189: =item *
                   14190: 
1.1269    raeburn  14191: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14192: replaces a &store() version of data with a replacement set of data
                   14193: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  14194: reference. If $tolog is true, the transaction is logged in the courselog
                   14195: with an action=PUTSTORE.
1.717     albertel 14196: 
                   14197: =item *
                   14198: 
1.243     albertel 14199: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14200: works very similar to store/cstore, but all data is stored in a
                   14201: temporary location and can be reset using tmpreset, $storehash should
                   14202: be a hash reference, returns nothing on success
1.191     harris41 14203: 
                   14204: =item *
                   14205: 
1.243     albertel 14206: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14207: similar to restore, but all data is stored in a temporary location and
                   14208: can be reset using tmpreset. Returns a hash of values on success,
                   14209: error string otherwise.
1.191     harris41 14210: 
                   14211: =item *
                   14212: 
1.243     albertel 14213: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14214: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14215: 
                   14216: =item *
                   14217: 
1.243     albertel 14218: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14219: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14220: 
                   14221: =item *
                   14222: 
1.243     albertel 14223: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14224: namesp ($udom and $uname are optional)
1.191     harris41 14225: 
                   14226: =item *
                   14227: 
1.702     albertel 14228: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14229: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14230: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14231: 
1.702     albertel 14232: $range should be either an integer '100' (give me the first 100
                   14233:                                            matching records)
                   14234:               or be  two integers sperated by a - with no spaces
                   14235:                  '30-50' (give me the 30th through the 50th matching
                   14236:                           records)
1.449     matthew  14237: =item *
                   14238: 
                   14239: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14240: $store can be a scalar, an array reference, or if the amount to be 
                   14241: incremented is > 1, a hash reference.
                   14242: 
                   14243: ($udom and $uname are optional)
1.191     harris41 14244: 
                   14245: =item *
                   14246: 
1.243     albertel 14247: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14248: ($udom and $uname are optional)
1.191     harris41 14249: 
                   14250: =item *
                   14251: 
1.243     albertel 14252: cput($namespace,$storehash,$udom,$uname) : critical put
                   14253: ($udom and $uname are optional)
1.191     harris41 14254: 
                   14255: =item *
                   14256: 
1.748     albertel 14257: newput($namespace,$storehash,$udom,$uname) :
                   14258: 
                   14259: Attempts to store the items in the $storehash, but only if they don't
                   14260: currently exist, if this succeeds you can be certain that you have 
                   14261: successfully created a new key value pair in the $namespace db.
                   14262: 
                   14263: 
                   14264: Args:
                   14265:  $namespace: name of database to store values to
                   14266:  $storehash: hashref to store to the db
                   14267:  $udom: (optional) domain of user containing the db
                   14268:  $uname: (optional) name of user caontaining the db
                   14269: 
                   14270: Returns:
                   14271:  'ok' -> succeeded in storing all keys of $storehash
                   14272:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14273:                         least <key> already existed in the db (other
                   14274:                         requested keys may also already exist)
1.967     bisitz   14275:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14276:  'con_lost' -> unable to contact request server
                   14277:  'refused' -> action was not allowed by remote machine
                   14278: 
                   14279: 
                   14280: =item *
                   14281: 
1.243     albertel 14282: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14283: reference filled in from namesp (encrypts the return communication)
                   14284: ($udom and $uname are optional)
1.191     harris41 14285: 
                   14286: =item *
                   14287: 
1.243     albertel 14288: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14289: critical subroutine
                   14290: 
1.806     raeburn  14291: =item *
                   14292: 
1.860     raeburn  14293: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14294: array reference filled in from namespace found in domain level on either
                   14295: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14296: 
                   14297: =item *
                   14298: 
1.860     raeburn  14299: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14300: domain level either on specified domain server ($uhome) or primary domain 
                   14301: server ($udom and $uhome are optional)
1.806     raeburn  14302: 
1.943     raeburn  14303: =item * 
                   14304: 
1.1240    raeburn  14305: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   14306: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14307: the target domain.
                   14308: 
                   14309: May also include additional key => value pairs for the following groups:
                   14310: 
                   14311: =over
                   14312: 
                   14313: =item
                   14314: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14315: 
                   14316: =over
                   14317: 
                   14318: =item defaultquota, authorquota
                   14319: 
                   14320: =back
                   14321: 
                   14322: =item
                   14323: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14324: portfolio for users).
                   14325: 
                   14326: =over
                   14327: 
                   14328: =item
                   14329: aboutme, blog, webdav, portfolio
                   14330: 
                   14331: =back
                   14332: 
                   14333: =item
                   14334: requestcourses: ability to request courses, and how requests are processed.
                   14335: 
                   14336: =over
                   14337: 
                   14338: =item
1.1305    raeburn  14339: official, unofficial, community, textbook, placement
1.1240    raeburn  14340: 
                   14341: =back
                   14342: 
                   14343: =item
                   14344: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14345: 
                   14346: =over
                   14347: 
                   14348: =item
1.1256    raeburn  14349: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  14350: 
                   14351: =back
                   14352: 
                   14353: =item
                   14354: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14355: for course's uploaded content.
                   14356: 
                   14357: =over
                   14358: 
                   14359: =item
1.1246    raeburn  14360: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  14361: communityquota, textbookquota, placementquota
1.1240    raeburn  14362: 
                   14363: =back
                   14364: 
                   14365: =item
                   14366: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14367: on your servers.
                   14368: 
                   14369: =over
                   14370: 
                   14371: =item 
                   14372: remotesessions, hostedsessions
                   14373: 
                   14374: =back
                   14375: 
                   14376: =back
                   14377: 
                   14378: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14379: utility to create a configuration.db file on a domain's primary library server 
                   14380: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14381: -- corresponding values are authentication type (internal, krb4, krb5,
                   14382: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   14383: will be available. Values are retrieved from cache (if current), unless the
                   14384: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14385: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14386: 
                   14387: Typical usage:
1.943     raeburn  14388: 
1.1240    raeburn  14389: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14390: 
1.243     albertel 14391: =back
                   14392: 
                   14393: =head2 Network Status Functions
                   14394: 
                   14395: =over 4
1.191     harris41 14396: 
                   14397: =item *
                   14398: 
1.1137    raeburn  14399: dirlist() : return directory list based on URI (first arg).
                   14400: 
                   14401: Inputs: 1 required, 5 optional.
                   14402: 
                   14403: =over
                   14404: 
                   14405: =item 
                   14406: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14407: 
                   14408: =item
                   14409: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14410: 
                   14411: =item
                   14412: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14413: 
                   14414: =item
                   14415: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14416: 
                   14417: =item
                   14418: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14419: 
                   14420: =item 
                   14421: $alternateRoot - path to prepend in place of path from $uri.
                   14422: 
                   14423: =back
                   14424: 
                   14425: Returns: Array of up to two items.
                   14426: 
                   14427: =over
                   14428: 
                   14429: a reference to an array of files/subdirectories
                   14430: 
                   14431: =over
                   14432: 
                   14433: Each element in the array of files/subdirectories is a & separated list of
                   14434: item name and the result of running stat on the item.  If dirlist was requested
                   14435: for a file instead of a directory, the item name will be ''. For a directory 
                   14436: listing, if the item is a metadata file, the element will end &N&M 
                   14437: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14438: default copyright set (1).  
                   14439: 
                   14440: =back
                   14441: 
                   14442: a scalar containing error condition (if encountered).
                   14443: 
                   14444: =over
                   14445: 
                   14446: =item 
                   14447: no_host (no homeserver identified for $username:$domain).
                   14448: 
                   14449: =item 
                   14450: no_such_host (server contacted for listing not identified as valid host).
                   14451: 
                   14452: =item 
                   14453: con_lost (connection to remote server failed).
                   14454: 
                   14455: =item 
                   14456: refused (invalid $username:$domain received on lond side).
                   14457: 
                   14458: =item 
                   14459: no_such_dir (directory at specified path on lond side does not exist). 
                   14460: 
                   14461: =item 
                   14462: empty (directory at specified path on lond side is empty).
                   14463: 
                   14464: =over
                   14465: 
                   14466: This is currently not encountered because the &ls3, &ls2, 
                   14467: &ls (_handler) routines on the lond side do not filter out
                   14468: . and .. from a directory listing. 
                   14469: 
                   14470: =back
                   14471: 
                   14472: =back
                   14473: 
                   14474: =back
1.191     harris41 14475: 
                   14476: =item *
                   14477: 
1.243     albertel 14478: spareserver() : find server with least workload from spare.tab
                   14479: 
1.986     foxr     14480: 
                   14481: =item *
                   14482: 
                   14483: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14484: if there is no corresponding loncapa host.
                   14485: 
1.243     albertel 14486: =back
                   14487: 
1.986     foxr     14488: 
1.243     albertel 14489: =head2 Apache Request
                   14490: 
                   14491: =over 4
1.191     harris41 14492: 
                   14493: =item *
                   14494: 
1.243     albertel 14495: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14496: localhost, posts hash
                   14497: 
                   14498: =back
                   14499: 
                   14500: =head2 Data to String to Data
                   14501: 
                   14502: =over 4
1.191     harris41 14503: 
                   14504: =item *
                   14505: 
1.243     albertel 14506: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14507: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14508: 
                   14509: =item *
                   14510: 
1.243     albertel 14511: hashref2str($hashref) : convert a hashref into a string complete with
                   14512: escaping and '=' and '&' separators, supports elements that are
                   14513: arrayrefs and hashrefs
1.191     harris41 14514: 
                   14515: =item *
                   14516: 
1.243     albertel 14517: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14518: with escaping and '&' separators, supports elements that are arrayrefs
                   14519: and hashrefs
1.191     harris41 14520: 
                   14521: =item *
                   14522: 
1.243     albertel 14523: str2hash($string) : convert string to hash using unescaping and
                   14524: splitting on '=' and '&', supports elements that are arrayrefs and
                   14525: hashrefs
1.191     harris41 14526: 
                   14527: =item *
                   14528: 
1.243     albertel 14529: str2array($string) : convert string to hash using unescaping and
                   14530: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14531: 
                   14532: =back
                   14533: 
                   14534: =head2 Logging Routines
                   14535: 
                   14536: 
                   14537: These routines allow one to make log messages in the lonnet.log and
                   14538: lonnet.perm logfiles.
1.191     harris41 14539: 
1.1119    foxr     14540: =over 4
                   14541: 
1.191     harris41 14542: =item *
                   14543: 
1.243     albertel 14544: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14545: 
                   14546: =item *
                   14547: 
1.243     albertel 14548: logthis() : append message to the normal lonnet.log file, it gets
                   14549: preiodically rolled over and deleted.
1.191     harris41 14550: 
                   14551: =item *
                   14552: 
1.243     albertel 14553: logperm() : append a permanent message to lonnet.perm.log, this log
                   14554: file never gets deleted by any automated portion of the system, only
                   14555: messages of critical importance should go in here.
                   14556: 
1.1119    foxr     14557: 
1.243     albertel 14558: =back
                   14559: 
                   14560: =head2 General File Helper Routines
                   14561: 
                   14562: =over 4
1.191     harris41 14563: 
                   14564: =item *
                   14565: 
1.481     raeburn  14566: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14567: (a) files in /uploaded
                   14568:   (i) If a local copy of the file exists - 
                   14569:       compares modification date of local copy with last-modified date for 
                   14570:       definitive version stored on home server for course. If local copy is 
                   14571:       stale, requests a new version from the home server and stores it. 
                   14572:       If the original has been removed from the home server, then local copy 
                   14573:       is unlinked.
                   14574:   (ii) If local copy does not exist -
                   14575:       requests the file from the home server and stores it. 
                   14576:   
                   14577:   If $caller is 'uploadrep':  
                   14578:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14579:     for request for files originally uploaded via DOCS. 
                   14580:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14581:   
                   14582:   Otherwise:
                   14583:      This indicates a call from the content generation phase of the request.
                   14584:      -  returns the entire contents of the file or -1.
                   14585:      
                   14586: (b) files in /res
                   14587:    - returns the entire contents of a file or -1; 
                   14588:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14589: 
1.712     albertel 14590: 
                   14591: =item *
                   14592: 
                   14593: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14594:                   reference
                   14595: 
                   14596: returns either a stat() list of data about the file or an empty list
                   14597: if the file doesn't exist or couldn't find out about it (connection
                   14598: problems or user unknown)
                   14599: 
1.191     harris41 14600: =item *
                   14601: 
1.243     albertel 14602: filelocation($dir,$file) : returns file system location of a file
                   14603: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14604: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14605: and a file of ../bob will become /a/bob)
1.191     harris41 14606: 
                   14607: =item *
                   14608: 
                   14609: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14610: filelocation except for hrefs
                   14611: 
                   14612: =item *
                   14613: 
1.1261    raeburn  14614: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14615: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14616: 
1.243     albertel 14617: =back
                   14618: 
1.608     albertel 14619: =head2 Usererfile file routines (/uploaded*)
                   14620: 
                   14621: =over 4
                   14622: 
                   14623: =item *
                   14624: 
                   14625: userfileupload(): main rotine for putting a file in a user or course's
                   14626:                   filespace, arguments are,
                   14627: 
1.620     albertel 14628:  formname - required - this is the name of the element in $env where the
1.608     albertel 14629:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14630:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14631:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14632:  context - if coursedoc, store the file in the course of the active role
                   14633:              of the current user; 
                   14634:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14635:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14636:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14637:          if undefined, it will be placed in "unknown"
                   14638: 
                   14639:  (This routine calls clean_filename() to remove any dangerous
                   14640:  characters from the filename, and then calls finuserfileupload() to
                   14641:  complete the transaction)
                   14642: 
                   14643:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14644:  and /adm/notfound.html if unsuccessful
                   14645: 
                   14646: =item *
                   14647: 
                   14648: clean_filename(): routine for cleaing a filename up for storage in
                   14649:                  userfile space, argument is:
                   14650: 
                   14651:  filename - proposed filename
                   14652: 
                   14653: returns: the new clean filename
                   14654: 
                   14655: =item *
                   14656: 
1.1090    raeburn  14657: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14658: userspace, probably shouldn't be called directly
                   14659: 
                   14660:   docuname: username or courseid of destination for the file
                   14661:   docudom: domain of user/course of destination for the file
                   14662:   formname: same as for userfileupload()
1.1090    raeburn  14663:   fname: filename (including subdirectories) for the file
                   14664:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14665:   allfiles: reference to hash used to store objects found by parser
                   14666:   codebase: reference to hash used for codebases of java objects found by parser
                   14667:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14668:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14669:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14670:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14671:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14672:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14673:   mimetype: reference to scalar to accommodate mime type determined
                   14674:             from File::MMagic if $parser = parse.
1.608     albertel 14675: 
                   14676:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14677:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14678:  was 'overwrite').
                   14679:  
1.608     albertel 14680: 
                   14681: =item *
                   14682: 
                   14683: renameuserfile(): renames an existing userfile to a new name
                   14684: 
                   14685:   Args:
                   14686:    docuname: username or courseid of destination for the file
                   14687:    docudom: domain of user/course of destination for the file
                   14688:    old: current file name (including any subdirs under userfiles)
                   14689:    new: desired file name (including any subdirs under userfiles)
                   14690: 
                   14691: =item *
                   14692: 
                   14693: mkdiruserfile(): creates a directory is a userfiles dir
                   14694: 
                   14695:   Args:
                   14696:    docuname: username or courseid of destination for the file
                   14697:    docudom: domain of user/course of destination for the file
                   14698:    dir: dir to create (including any subdirs under userfiles)
                   14699: 
                   14700: =item *
                   14701: 
                   14702: removeuserfile(): removes a file that exists in userfiles
                   14703: 
                   14704:   Args:
                   14705:    docuname: username or courseid of destination for the file
                   14706:    docudom: domain of user/course of destination for the file
                   14707:    fname: filname to delete (including any subdirs under userfiles)
                   14708: 
                   14709: =item *
                   14710: 
                   14711: removeuploadedurl(): convience function for removeuserfile()
                   14712: 
                   14713:   Args:
                   14714:    url:  a full /uploaded/... url to delete
                   14715: 
1.747     albertel 14716: =item * 
                   14717: 
                   14718: get_portfile_permissions():
                   14719:   Args:
                   14720:     domain: domain of user or course contain the portfolio files
                   14721:     user: name of user or num of course contain the portfolio files
                   14722:   Returns:
                   14723:     hashref of a dump of the proper file_permissions.db
                   14724:    
                   14725: 
                   14726: =item * 
                   14727: 
                   14728: get_access_controls():
                   14729: 
                   14730: Args:
                   14731:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14732:   group: (optional) the group you want the files associated with
                   14733:   file: (optional) the file you want access info on
                   14734: 
                   14735: Returns:
1.749     raeburn  14736:     a hash (keys are file names) of hashes containing
                   14737:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14738:         values are XML containing access control settings (see below) 
1.747     albertel 14739: 
                   14740: Internal notes:
                   14741: 
1.749     raeburn  14742:  access controls are stored in file_permissions.db as key=value pairs.
                   14743:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14744:         where scope -> public,guest,course,group,domains or users.
                   14745:               end -> UNIX time for end of access (0 -> no end date)
                   14746:               start -> UNIX time for start of access
                   14747: 
                   14748:     value -> XML description of access control
                   14749:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14750:             <start></start>
                   14751:             <end></end>
                   14752: 
                   14753:             <password></password>  for scope type = guest
                   14754: 
                   14755:             <domain></domain>     for scope type = course or group
                   14756:             <number></number>
                   14757:             <roles id="">
                   14758:              <role></role>
                   14759:              <access></access>
                   14760:              <section></section>
                   14761:              <group></group>
                   14762:             </roles>
                   14763: 
                   14764:             <dom></dom>         for scope type = domains
                   14765: 
                   14766:             <users>             for scope type = users
                   14767:              <user>
                   14768:               <uname></uname>
                   14769:               <udom></udom>
                   14770:              </user>
                   14771:             </users>
                   14772:            </scope> 
                   14773:               
                   14774:  Access data is also aggregated for each file in an additional key=value pair:
                   14775:  key -> path to file/file_name\0accesscontrol 
                   14776:  value -> reference to hash
                   14777:           hash contains key = value pairs
                   14778:           where key = uniqueID:scope_end_start
                   14779:                 value = UNIX time record was last updated
                   14780: 
                   14781:           Used to improve speed of look-ups of access controls for each file.  
                   14782:  
                   14783:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14784: 
1.1198    raeburn  14785: =item *
                   14786: 
1.749     raeburn  14787: modify_access_controls():
                   14788: 
                   14789: Modifies access controls for a portfolio file
                   14790: Args
                   14791: 1. file name
                   14792: 2. reference to hash of required changes,
                   14793: 3. domain
                   14794: 4. username
                   14795:   where domain,username are the domain of the portfolio owner 
                   14796:   (either a user or a course) 
                   14797: 
                   14798: Returns:
                   14799: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14800: 2. result of deletions ('ok' or 'error', with error message).
                   14801: 3. reference to hash of any new or updated access controls.
                   14802: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14803:    key = integer (inbound ID)
1.1198    raeburn  14804:    value = uniqueID
                   14805: 
                   14806: =item *
                   14807: 
                   14808: get_timebased_id():
                   14809: 
                   14810: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   14811: course via the Course Editor (e.g., folders, composite pages, 
                   14812: group bulletin boards).
                   14813: 
                   14814: Args: (first three required; six others optional)
                   14815: 
                   14816: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14817:    docssequence, or name of group
                   14818: 
                   14819: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14820:    e.g., num, boardids
                   14821: 
                   14822: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   14823:    file will be named nohist_namespace.db
                   14824: 
                   14825: 4. cdom: domain of course; default is current course domain from %env
                   14826: 
                   14827: 5. cnum: course number; default is current course number from %env
                   14828: 
                   14829: 6. idtype: set to concat if an additional digit is to be appended to the 
                   14830:    unix timestamp to form the suffix, if the plain timestamp is already
                   14831:    in use.  Default is to not do this, but simply increment the unix 
                   14832:    timestamp by 1 until a unique key is obtained.
                   14833: 
                   14834: 7. who: holder of locking key; defaults to user:domain for user.
                   14835: 
                   14836: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   14837:    retrying); default is 3.
                   14838: 
                   14839: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   14840: 
                   14841: Returns:
                   14842: 
                   14843: 1. suffix obtained (numeric)
                   14844: 
                   14845: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14846: 
                   14847: 3. error: contains (localized) error message if an error occurred.
                   14848: 
1.747     albertel 14849: 
1.608     albertel 14850: =back
                   14851: 
1.243     albertel 14852: =head2 HTTP Helper Routines
                   14853: 
                   14854: =over 4
                   14855: 
1.191     harris41 14856: =item *
                   14857: 
                   14858: escape() : unpack non-word characters into CGI-compatible hex codes
                   14859: 
                   14860: =item *
                   14861: 
                   14862: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14863: 
1.243     albertel 14864: =back
                   14865: 
                   14866: =head1 PRIVATE SUBROUTINES
                   14867: 
                   14868: =head2 Underlying communication routines (Shouldn't call)
                   14869: 
                   14870: =over 4
                   14871: 
                   14872: =item *
                   14873: 
                   14874: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14875: 
                   14876: =item *
                   14877: 
                   14878: reply() : uses subreply to send a message to remote machine, logs all failures
                   14879: 
                   14880: =item *
                   14881: 
                   14882: critical() : passes a critical message to another server; if cannot
                   14883: get through then place message in connection buffer directory and
                   14884: returns con_delayed, if incapable of saving message, returns
                   14885: con_failed
                   14886: 
                   14887: =item *
                   14888: 
                   14889: reconlonc() : tries to reconnect lonc client processes.
                   14890: 
                   14891: =back
                   14892: 
                   14893: =head2 Resource Access Logging
                   14894: 
                   14895: =over 4
                   14896: 
                   14897: =item *
                   14898: 
                   14899: flushcourselogs() : flush (save) buffer logs and access logs
                   14900: 
                   14901: =item *
                   14902: 
                   14903: courselog($what) : save message for course in hash
                   14904: 
                   14905: =item *
                   14906: 
                   14907: courseacclog($what) : save message for course using &courselog().  Perform
                   14908: special processing for specific resource types (problems, exams, quizzes, etc).
                   14909: 
1.191     harris41 14910: =item *
                   14911: 
                   14912: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14913: as a PerlChildExitHandler
1.243     albertel 14914: 
                   14915: =back
                   14916: 
                   14917: =head2 Other
                   14918: 
                   14919: =over 4
                   14920: 
                   14921: =item *
                   14922: 
                   14923: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14924: 
                   14925: =back
                   14926: 
                   14927: =cut
1.877     foxr     14928: 

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