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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1313  ! raeburn     4: # $Id: lonnet.pm,v 1.1312 2016/06/19 04:28:19 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1182    foxr       78: 
1.1173    foxr       79: use Encode;
                     80: 
1.1245    raeburn    81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     83:             %managerstab);
1.871     albertel   84: 
                     85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        88:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        89: 
1.1       albertel   90: use IO::Socket;
1.31      www        91: use GDBM_File;
1.208     albertel   92: use HTML::LCParser;
1.88      www        93: use Fcntl qw(:flock);
1.870     albertel   94: use Storable qw(thaw nfreeze);
1.1289    damieng    95: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   96: use Cache::Memcached;
1.676     albertel   97: use Digest::MD5;
1.790     albertel   98: use Math::Random;
1.1024    raeburn    99: use File::MMagic;
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1167    droeschl  103: use LONCAPA::Lond;
1.1117    foxr      104: 
1.1090    raeburn   105: use File::Copy;
1.676     albertel  106: 
1.195     www       107: my $readit;
1.1288    damieng   108: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  109: 
1.619     albertel  110: require Exporter;
                    111: 
                    112: our @ISA = qw (Exporter);
                    113: our @EXPORT = qw(%env);
                    114: 
1.449     matthew   115: 
1.1187    raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1187    raeburn   119:     sub write_log {
1.1188    raeburn   120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1184    raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   130:         my $logentry = { 
                    131:                           $id => {
                    132:                                    'exe_uname' => $env{'user.name'},
                    133:                                    'exe_udom'  => $env{'user.domain'},
                    134:                                    'exe_time'  => $now,
                    135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    136:                                    'delflag'   => $delflag,
                    137:                                    'logentry'  => $storehash,
                    138:                                    'uname'     => $uname,
                    139:                                    'udom'      => $udom,
                    140:                                   }
                    141:                        };
                    142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       143:     }
                    144: }
1.1       albertel  145: 
1.163     harris41  146: sub logtouch {
                    147:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  148:     unless (-e "$execdir/logs/lonnet.log") {	
                    149: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  150: 	close $fh;
                    151:     }
                    152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    154: }
                    155: 
1.1       albertel  156: sub logthis {
                    157:     my $message=shift;
                    158:     my $execdir=$perlvar{'lonDaemons'};
                    159:     my $now=time;
                    160:     my $local=localtime($now);
1.448     albertel  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    163: 	print $fh $logstring;
1.448     albertel  164: 	close($fh);
                    165:     }
1.1       albertel  166:     return 1;
                    167: }
                    168: 
                    169: sub logperm {
                    170:     my $message=shift;
                    171:     my $execdir=$perlvar{'lonDaemons'};
                    172:     my $now=time;
                    173:     my $local=localtime($now);
1.448     albertel  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    175: 	print $fh "$now:$message:$local\n";
                    176: 	close($fh);
                    177:     }
1.1       albertel  178:     return 1;
                    179: }
                    180: 
1.850     albertel  181: sub create_connection {
1.853     albertel  182:     my ($hostname,$lonid) = @_;
1.851     albertel  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  184: 				     Type    => SOCK_STREAM,
                    185: 				     Timeout => 10);
                    186:     return 0 if (!$client);
1.890     albertel  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  188:     my $result = <$client>;
                    189:     chomp($result);
                    190:     return 1 if ($result eq 'done');
                    191:     return 0;
                    192: }
                    193: 
1.983     raeburn   194: sub get_server_timezone {
                    195:     my ($cnum,$cdom) = @_;
                    196:     my $home=&homeserver($cnum,$cdom);
                    197:     if ($home ne 'no_host') {
                    198:         my $cachetime = 24*3600;
                    199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    200:         if (defined($cached)) {
                    201:             return $timezone;
                    202:         } else {
                    203:             my $timezone = &reply('servertimezone',$home);
                    204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    205:         }
                    206:     }
                    207: }
1.850     albertel  208: 
1.1106    raeburn   209: sub get_server_distarch {
                    210:     my ($lonhost,$ignore_cache) = @_;
                    211:     if (defined($lonhost)) {
                    212:         if (!defined(&hostname($lonhost))) {
                    213:             return;
                    214:         }
                    215:         my $cachetime = 12*3600;
                    216:         if (!$ignore_cache) {
                    217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    218:             if (defined($cached)) {
                    219:                 return $distarch;
                    220:             }
                    221:         }
                    222:         my $rep = &reply('serverdistarch',$lonhost);
                    223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    225:                 $rep eq '') {
                    226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    227:         }
                    228:     }
                    229:     return;
                    230: }
                    231: 
1.993     raeburn   232: sub get_server_loncaparev {
1.1073    raeburn   233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   234:     if (defined($lonhost)) {
                    235:         if (!defined(&hostname($lonhost))) {
                    236:             undef($lonhost);
                    237:         }
                    238:     }
                    239:     if (!defined($lonhost)) {
                    240:         if (defined(&domain($dom,'primary'))) {
                    241:             $lonhost=&domain($dom,'primary');
                    242:             if ($lonhost eq 'no_host') {
                    243:                 undef($lonhost);
                    244:             }
                    245:         }
                    246:     }
                    247:     if (defined($lonhost)) {
1.1073    raeburn   248:         my $cachetime = 12*3600;
                    249:         if (!$ignore_cache) {
                    250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    251:             if (defined($cached)) {
                    252:                 return $loncaparev;
                    253:             }
                    254:         }
                    255:         my ($answer,$loncaparev);
                    256:         my @ids=&current_machine_ids();
                    257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    258:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   260:                 $loncaparev = $1;
                    261:             }
                    262:         } else {
                    263:             $answer = &reply('serverloncaparev',$lonhost);
                    264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    265:                 if ($caller eq 'loncron') {
                    266:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   267:                     $ua->timeout(4);
1.1073    raeburn   268:                     my $protocol = $protocol{$lonhost};
                    269:                     $protocol = 'http' if ($protocol ne 'https');
                    270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    271:                     my $request=new HTTP::Request('GET',$url);
                    272:                     my $response=$ua->request($request);
                    273:                     unless ($response->is_error()) {
                    274:                         my $content = $response->content;
1.1081    raeburn   275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   276:                             $loncaparev = $1;
                    277:                         }
                    278:                     }
                    279:                 } else {
                    280:                     $loncaparev = $loncaparevs{$lonhost};
                    281:                 }
1.1081    raeburn   282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   283:                 $loncaparev = $1;
                    284:             }
1.993     raeburn   285:         }
1.1073    raeburn   286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   287:     }
                    288: }
                    289: 
1.1074    raeburn   290: sub get_server_homeID {
                    291:     my ($hostname,$ignore_cache,$caller) = @_;
                    292:     unless ($ignore_cache) {
                    293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    294:         if (defined($cached)) {
                    295:             return $serverhomeID;
                    296:         }
                    297:     }
                    298:     my $cachetime = 12*3600;
                    299:     my $serverhomeID;
                    300:     if ($caller eq 'loncron') { 
                    301:         my @machine_ids = &machine_ids($hostname);
                    302:         foreach my $id (@machine_ids) {
                    303:             my $response = &reply('serverhomeID',$id);
                    304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    305:                 $serverhomeID = $response;
                    306:                 last;
                    307:             }
                    308:         }
                    309:         if ($serverhomeID eq '') {
                    310:             $serverhomeID = $machine_ids[-1];
                    311:         }
                    312:     } else {
                    313:         $serverhomeID = $serverhomeIDs{$hostname};
                    314:     }
                    315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    316: }
                    317: 
1.1121    raeburn   318: sub get_remote_globals {
                    319:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   320:     my ($result,%returnhash,%whatneeded);
                    321:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   322:         foreach my $what (sort(keys(%{$whathash}))) {
                    323:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   324:             my ($response,$cached);
1.1121    raeburn   325:             unless ($ignore_cache) {
1.1125    raeburn   326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   327:             }
                    328:             if (defined($cached)) {
1.1125    raeburn   329:                 $returnhash{$what} = $response;
1.1121    raeburn   330:             } else {
1.1125    raeburn   331:                 $whatneeded{$what} = 1;
1.1121    raeburn   332:             }
                    333:         }
1.1125    raeburn   334:         if (keys(%whatneeded) == 0) {
                    335:             $result = 'ok';
                    336:         } else {
1.1121    raeburn   337:             my $requested = &freeze_escape(\%whatneeded);
                    338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    340:                 ($rep eq 'unknown_cmd')) {
                    341:                 $result = $rep;
                    342:             } else {
                    343:                 $result = 'ok';
1.1121    raeburn   344:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   345:                 foreach my $item (@pairs) {
                    346:                     my ($key,$value)=split(/=/,$item,2);
                    347:                     my $what = &unescape($key);
                    348:                     my $hashid = $lonhost.'-'.$what;
                    349:                     $returnhash{$what}=&thaw_unescape($value);
                    350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   351:                 }
                    352:             }
                    353:         }
                    354:     }
1.1125    raeburn   355:     return ($result,\%returnhash);
1.1121    raeburn   356: }
                    357: 
1.1124    raeburn   358: sub remote_devalidate_cache {
1.1241    raeburn   359:     my ($lonhost,$cachekeys) = @_;
                    360:     my $items;
                    361:     return unless (ref($cachekeys) eq 'ARRAY');
                    362:     my $cachestr = join('&',@{$cachekeys});
                    363:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   364:     return $response;
                    365: }
                    366: 
1.1       albertel  367: # -------------------------------------------------- Non-critical communication
                    368: sub subreply {
                    369:     my ($cmd,$server)=@_;
1.838     albertel  370:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      371:     #
                    372:     #  With loncnew process trimming, there's a timing hole between lonc server
                    373:     #  process exit and the master server picking up the listen on the AF_UNIX
                    374:     #  socket.  In that time interval, a lock file will exist:
                    375: 
                    376:     my $lockfile=$peerfile.".lock";
                    377:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   378: 	sleep(0.1);
1.549     foxr      379:     }
                    380:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      381:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      382:     #
1.550     foxr      383:     #   We'll give the connection a few tries before abandoning it.  If
                    384:     #   connection is not possible, we'll con_lost back to the client.
                    385:     #   
                    386:     my $client;
                    387:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    388: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    389: 				      Type    => SOCK_STREAM,
                    390: 				      Timeout => 10);
1.869     albertel  391: 	if ($client) {
1.550     foxr      392: 	    last;		# Connected!
1.850     albertel  393: 	} else {
1.853     albertel  394: 	    &create_connection(&hostname($server),$server);
1.550     foxr      395: 	}
1.1289    damieng   396:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      397:     }
                    398:     my $answer;
                    399:     if ($client) {
1.704     albertel  400: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      401: 	$answer=<$client>;
                    402: 	if (!$answer) { $answer="con_lost"; }
                    403: 	chomp($answer);
                    404:     } else {
                    405: 	$answer = 'con_lost';	# Failed connection.
                    406:     }
1.1       albertel  407:     return $answer;
                    408: }
                    409: 
                    410: sub reply {
                    411:     my ($cmd,$server)=@_;
1.838     albertel  412:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  413:     my $answer=subreply($cmd,$server);
1.65      www       414:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  415:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       416:                 " $cmd to $server returned $answer</font>");
                    417:     }
1.1       albertel  418:     return $answer;
                    419: }
                    420: 
                    421: # ----------------------------------------------------------- Send USR1 to lonc
                    422: 
                    423: sub reconlonc {
1.891     albertel  424:     my ($lonid) = @_;
                    425:     if ($lonid) {
1.1295    raeburn   426:         my $hostname = &hostname($lonid);
1.891     albertel  427: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    428: 	if ($hostname && -e $peerfile) {
                    429: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    430: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    431: 					     Type    => SOCK_STREAM,
                    432: 					     Timeout => 10);
                    433: 	    if ($client) {
                    434: 		print $client ("reset_retries\n");
                    435: 		my $answer=<$client>;
                    436: 		#reset just this one.
                    437: 	    }
                    438: 	}
                    439: 	return;
                    440:     }
                    441: 
1.836     www       442:     &logthis("Trying to reconnect lonc");
1.1       albertel  443:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  444:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  445: 	my $loncpid=<$fh>;
                    446:         chomp($loncpid);
                    447:         if (kill 0 => $loncpid) {
                    448: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    449:             kill USR1 => $loncpid;
                    450:             sleep 1;
1.1295    raeburn   451:         } else {
1.12      www       452: 	    &logthis(
1.672     albertel  453:                "<font color=\"blue\">WARNING:".
1.12      www       454:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  455:         }
                    456:     } else {
1.836     www       457: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  458:     }
                    459: }
                    460: 
                    461: # ------------------------------------------------------ Critical communication
1.12      www       462: 
1.1       albertel  463: sub critical {
                    464:     my ($cmd,$server)=@_;
1.838     albertel  465:     unless (&hostname($server)) {
1.672     albertel  466:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       467:                " Critical message to unknown server ($server)</font>");
                    468:         return 'no_such_host';
                    469:     }
1.1       albertel  470:     my $answer=reply($cmd,$server);
                    471:     if ($answer eq 'con_lost') {
1.1295    raeburn   472: 	&reconlonc($server);
1.589     albertel  473: 	my $answer=reply($cmd,$server);
1.1       albertel  474:         if ($answer eq 'con_lost') {
                    475:             my $now=time;
                    476:             my $middlename=$cmd;
1.5       www       477:             $middlename=substr($middlename,0,16);
1.1       albertel  478:             $middlename=~s/\W//g;
                    479:             my $dfilename=
1.305     www       480:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    481:             $dumpcount++;
1.1       albertel  482:             {
1.448     albertel  483: 		my $dfh;
                    484: 		if (open($dfh,">$dfilename")) {
                    485: 		    print $dfh "$cmd\n"; 
                    486: 		    close($dfh);
                    487: 		}
1.1       albertel  488:             }
1.1288    damieng   489:             sleep 1;
1.1       albertel  490:             my $wcmd='';
                    491:             {
1.448     albertel  492: 		my $dfh;
                    493: 		if (open($dfh,"<$dfilename")) {
                    494: 		    $wcmd=<$dfh>; 
                    495: 		    close($dfh);
                    496: 		}
1.1       albertel  497:             }
                    498:             chomp($wcmd);
1.7       www       499:             if ($wcmd eq $cmd) {
1.672     albertel  500: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       501:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  502:                 &logperm("D:$server:$cmd");
                    503: 	        return 'con_delayed';
                    504:             } else {
1.672     albertel  505:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       506:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  507:                 &logperm("F:$server:$cmd");
                    508:                 return 'con_failed';
                    509:             }
                    510:         }
                    511:     }
                    512:     return $answer;
1.405     albertel  513: }
                    514: 
1.755     albertel  515: # ------------------------------------------- check if return value is an error
                    516: 
                    517: sub error {
                    518:     my ($result) = @_;
1.756     albertel  519:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  520: 	if ($2 == 2) { return undef; }
                    521: 	return $1;
                    522:     }
                    523:     return undef;
                    524: }
                    525: 
1.783     albertel  526: sub convert_and_load_session_env {
                    527:     my ($lonidsdir,$handle)=@_;
                    528:     my @profile;
                    529:     {
1.917     albertel  530: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    531: 	if (!$opened) {
1.915     albertel  532: 	    return 0;
                    533: 	}
1.783     albertel  534: 	flock($idf,LOCK_SH);
                    535: 	@profile=<$idf>;
                    536: 	close($idf);
                    537:     }
                    538:     my %temp_env;
                    539:     foreach my $line (@profile) {
1.786     albertel  540: 	if ($line !~ m/=/) {
                    541: 	    return 0;
                    542: 	}
1.783     albertel  543: 	chomp($line);
                    544: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    545: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    546:     }
                    547:     unlink("$lonidsdir/$handle.id");
                    548:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    549: 	    0640)) {
                    550: 	%disk_env = %temp_env;
                    551: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    552: 	untie(%disk_env);
                    553:     }
1.786     albertel  554:     return 1;
1.783     albertel  555: }
                    556: 
1.374     www       557: # ------------------------------------------- Transfer profile into environment
1.780     albertel  558: my $env_loaded;
                    559: sub transfer_profile_to_env {
1.788     albertel  560:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    561:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       562: 
1.720     albertel  563:     if (!defined($lonidsdir)) {
                    564: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    565:     }
                    566:     if (!defined($handle)) {
                    567:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    568:     }
                    569: 
1.786     albertel  570:     my $convert;
                    571:     {
1.917     albertel  572:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    573: 	if (!$opened) {
1.915     albertel  574: 	    return;
                    575: 	}
1.786     albertel  576: 	flock($idf,LOCK_SH);
                    577: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    578: 		&GDBM_READER(),0640)) {
                    579: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    580: 	    untie(%disk_env);
                    581: 	} else {
                    582: 	    $convert = 1;
                    583: 	}
                    584:     }
                    585:     if ($convert) {
                    586: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    587: 	    &logthis("Failed to load session, or convert session.");
                    588: 	}
1.374     www       589:     }
1.783     albertel  590: 
1.786     albertel  591:     my %remove;
1.783     albertel  592:     while ( my $envname = each(%env) ) {
1.433     matthew   593:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    594:             if ($time < time-300) {
1.783     albertel  595:                 $remove{$key}++;
1.433     matthew   596:             }
                    597:         }
                    598:     }
1.783     albertel  599: 
1.619     albertel  600:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  601:     $env_loaded=1;
1.783     albertel  602:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   603:         &delenv($expired_key);
1.374     www       604:     }
1.1       albertel  605: }
                    606: 
1.916     albertel  607: # ---------------------------------------------------- Check for valid session 
                    608: sub check_for_valid_session {
1.1245    raeburn   609:     my ($r,$name,$userhashref) = @_;
1.916     albertel  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   611:     if ($name eq '') {
                    612:         $name = 'lonID';
                    613:     }
                    614:     my $lonid=$cookies{$name};
1.916     albertel  615:     return undef if (!$lonid);
                    616: 
                    617:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   618:     my $lonidsdir;
                    619:     if ($name eq 'lonDAV') {
                    620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    621:     } else {
                    622:         $lonidsdir=$r->dir_config('lonIDsDir');
                    623:     }
1.916     albertel  624:     return undef if (!-e "$lonidsdir/$handle.id");
                    625: 
1.917     albertel  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    627:     return undef if (!$opened);
1.916     albertel  628: 
                    629:     flock($idf,LOCK_SH);
                    630:     my %disk_env;
                    631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    632: 	    &GDBM_READER(),0640)) {
                    633: 	return undef;	
                    634:     }
                    635: 
                    636:     if (!defined($disk_env{'user.name'})
                    637: 	|| !defined($disk_env{'user.domain'})) {
                    638: 	return undef;
                    639:     }
1.1245    raeburn   640: 
                    641:     if (ref($userhashref) eq 'HASH') {
                    642:         $userhashref->{'name'} = $disk_env{'user.name'};
                    643:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212    raeburn   644:     }
1.1245    raeburn   645: 
1.916     albertel  646:     return $handle;
                    647: }
                    648: 
1.830     albertel  649: sub timed_flock {
                    650:     my ($file,$lock_type) = @_;
                    651:     my $failed=0;
                    652:     eval {
                    653: 	local $SIG{__DIE__}='DEFAULT';
                    654: 	local $SIG{ALRM}=sub {
                    655: 	    $failed=1;
                    656: 	    die("failed lock");
                    657: 	};
                    658: 	alarm(13);
                    659: 	flock($file,$lock_type);
                    660: 	alarm(0);
                    661:     };
                    662:     if ($failed) {
                    663: 	return undef;
                    664:     } else {
                    665: 	return 1;
                    666:     }
                    667: }
                    668: 
1.5       www       669: # ---------------------------------------------------------- Append Environment
                    670: 
                    671: sub appenv {
1.949     raeburn   672:     my ($newenv,$roles) = @_;
                    673:     if (ref($newenv) eq 'HASH') {
                    674:         foreach my $key (keys(%{$newenv})) {
                    675:             my $refused = 0;
                    676: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    677:                 $refused = 1;
                    678:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   679:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   680:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    681:                         $refused = 0;
                    682:                     }
                    683:                 }
                    684:             }
                    685:             if ($refused) {
                    686:                 &logthis("<font color=\"blue\">WARNING: ".
                    687:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    688:                          .'</font>');
                    689: 	        delete($newenv->{$key});
                    690:             } else {
                    691:                 $env{$key}=$newenv->{$key};
                    692:             }
                    693:         }
                    694:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    695:         if ($opened
                    696: 	    && &timed_flock($env_file,LOCK_EX)
                    697: 	    &&
                    698: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    699: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    700: 	    while (my ($key,$value) = each(%{$newenv})) {
                    701: 	        $disk_env{$key} = $value;
                    702: 	    }
                    703: 	    untie(%disk_env);
1.35      www       704:         }
1.191     harris41  705:     }
1.56      www       706:     return 'ok';
                    707: }
                    708: # ----------------------------------------------------- Delete from Environment
                    709: 
                    710: sub delenv {
1.1104    raeburn   711:     my ($delthis,$regexp,$roles) = @_;
                    712:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    713:         my $refused = 1;
                    714:         if (ref($roles) eq 'ARRAY') {
                    715:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    716:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    717:                 $refused = 0;
                    718:             }
                    719:         }
                    720:         if ($refused) {
                    721:             &logthis("<font color=\"blue\">WARNING: ".
                    722:                      "Attempt to delete from environment ".$delthis);
                    723:             return 'error';
                    724:         }
1.56      www       725:     }
1.917     albertel  726:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    727:     if ($opened
1.915     albertel  728: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  729: 	&&
                    730: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    731: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  732: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   733: 	    if ($regexp) {
                    734:                 if ($key=~/^$delthis/) {
                    735:                     delete($env{$key});
                    736:                     delete($disk_env{$key});
                    737:                 } 
                    738:             } else {
                    739:                 if ($key=~/^\Q$delthis\E/) {
                    740: 		    delete($env{$key});
                    741: 		    delete($disk_env{$key});
                    742: 	        }
                    743:             }
1.448     albertel  744: 	}
1.783     albertel  745: 	untie(%disk_env);
1.5       www       746:     }
                    747:     return 'ok';
1.369     albertel  748: }
                    749: 
1.790     albertel  750: sub get_env_multiple {
                    751:     my ($name) = @_;
                    752:     my @values;
                    753:     if (defined($env{$name})) {
                    754:         # exists is it an array
                    755:         if (ref($env{$name})) {
                    756:             @values=@{ $env{$name} };
                    757:         } else {
                    758:             $values[0]=$env{$name};
                    759:         }
                    760:     }
                    761:     return(@values);
                    762: }
                    763: 
1.958     www       764: # ------------------------------------------------------------------- Locking
                    765: 
                    766: sub set_lock {
                    767:     my ($text)=@_;
                    768:     $locknum++;
                    769:     my $id=$$.'-'.$locknum;
                    770:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    771:              'session.lock.'.$id => $text});
                    772:     return $id;
                    773: }
                    774: 
                    775: sub get_locks {
                    776:     my $num=0;
                    777:     my %texts=();
                    778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    779:        if ($lock=~/\w/) {
                    780:           $num++;
                    781:           $texts{$lock}=$env{'session.lock.'.$lock};
                    782:        }
                    783:    }
                    784:    return ($num,%texts);
                    785: }
                    786: 
                    787: sub remove_lock {
                    788:     my ($id)=@_;
                    789:     my $newlocks='';
                    790:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    791:        if (($lock=~/\w/) && ($lock ne $id)) {
                    792:           $newlocks.=','.$lock;
                    793:        }
                    794:     }
                    795:     &appenv({'session.locks' => $newlocks});
                    796:     &delenv('session.lock.'.$id);
                    797: }
                    798: 
                    799: sub remove_all_locks {
                    800:     my $activelocks=$env{'session.locks'};
                    801:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    802:        if ($lock=~/\w/) {
                    803:           &remove_lock($lock);
                    804:        }
                    805:     }
                    806: }
                    807: 
                    808: 
1.369     albertel  809: # ------------------------------------------ Find out current server userload
                    810: sub userload {
                    811:     my $numusers=0;
                    812:     {
                    813: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    814: 	my $filename;
                    815: 	my $curtime=time;
                    816: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  817: 	    next if ($filename eq '.' || $filename eq '..');
                    818: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  819: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  820: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  821: 	}
                    822: 	closedir(LONIDS);
                    823:     }
                    824:     my $userloadpercent=0;
                    825:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    826:     if ($maxuserload) {
1.371     albertel  827: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  828:     }
1.372     albertel  829:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  830:     return $userloadpercent;
1.283     www       831: }
                    832: 
1.1       albertel  833: # ------------------------------ Find server with least workload from spare.tab
1.11      www       834: 
1.1       albertel  835: sub spareserver {
1.1083    raeburn   836:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  837:     my $spare_server;
1.370     albertel  838:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  839:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    840:                                                      :  $userloadpercent;
1.1083    raeburn   841:     my ($uint_dom,$remotesessions);
                    842:     if (($udom ne '') && (&domain($udom) ne '')) {
                    843:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    844:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    845:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    846:         $remotesessions = $udomdefaults{'remotesessions'};
                    847:     }
1.1123    raeburn   848:     my $spareshash = &this_host_spares($udom);
                    849:     if (ref($spareshash) eq 'HASH') {
                    850:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    851:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   852:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    853:                                              $try_server));
1.1123    raeburn   854: 	        ($spare_server, $lowest_load) =
                    855: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    856:             }
1.1083    raeburn   857:         }
1.784     albertel  858: 
1.1123    raeburn   859:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    860: 
                    861:         if (!$found_server) {
                    862:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    863: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   864:                     next unless (&spare_can_host($udom,$uint_dom,
                    865:                                                  $remotesessions,$try_server));
1.1123    raeburn   866: 	            ($spare_server, $lowest_load) =
                    867: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    868:                 }
                    869: 	    }
                    870:         }
1.784     albertel  871:     }
                    872: 
                    873:     if (!$want_server_name) {
1.968     raeburn   874:         my $protocol = 'http';
                    875:         if ($protocol{$spare_server} eq 'https') {
                    876:             $protocol = $protocol{$spare_server};
                    877:         }
1.1001    raeburn   878:         if (defined($spare_server)) {
                    879:             my $hostname = &hostname($spare_server);
1.1083    raeburn   880:             if (defined($hostname)) {
1.1001    raeburn   881: 	        $spare_server = $protocol.'://'.$hostname;
                    882:             }
                    883:         }
1.784     albertel  884:     }
                    885:     return $spare_server;
                    886: }
                    887: 
                    888: sub compare_server_load {
1.1253    raeburn   889:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    890: 
                    891:     if ($required) {
                    892:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    893:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    894:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    895:         if (($major eq '' && $minor eq '') ||
                    896:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    897:             return ($spare_server,$lowest_load);
                    898:         }
                    899:     }
1.784     albertel  900: 
                    901:     my $loadans     = &reply('load',    $try_server);
                    902:     my $userloadans = &reply('userload',$try_server);
                    903: 
                    904:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   905: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  906:     }
                    907: 
                    908:     my $load;
                    909:     if ($loadans =~ /\d/) {
                    910: 	if ($userloadans =~ /\d/) {
                    911: 	    #both are numbers, pick the bigger one
                    912: 	    $load = ($loadans > $userloadans) ? $loadans 
                    913: 		                              : $userloadans;
1.411     albertel  914: 	} else {
1.784     albertel  915: 	    $load = $loadans;
1.411     albertel  916: 	}
1.784     albertel  917:     } else {
                    918: 	$load = $userloadans;
                    919:     }
                    920: 
                    921:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    922: 	$spare_server = $try_server;
                    923: 	$lowest_load  = $load;
1.370     albertel  924:     }
1.784     albertel  925:     return ($spare_server,$lowest_load);
1.202     matthew   926: }
1.914     albertel  927: 
                    928: # --------------------------- ask offload servers if user already has a session
                    929: sub find_existing_session {
                    930:     my ($udom,$uname) = @_;
1.1123    raeburn   931:     my $spareshash = &this_host_spares($udom);
                    932:     if (ref($spareshash) eq 'HASH') {
                    933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    936:             }
                    937:         }
                    938:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    939:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    940:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    941:             }
                    942:         }
1.914     albertel  943:     }
                    944:     return;
                    945: }
                    946: 
                    947: # -------------------------------- ask if server already has a session for user
                    948: sub has_user_session {
                    949:     my ($lonid,$udom,$uname) = @_;
                    950:     my $result = &reply(join(':','userhassession',
                    951: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    952:     return 1 if ($result eq 'ok');
                    953: 
                    954:     return 0;
                    955: }
                    956: 
1.1076    raeburn   957: # --------- determine least loaded server in a user's domain which allows login
                    958: 
                    959: sub choose_server {
1.1259    raeburn   960:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   961:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   962:     my %servers = &get_servers($udom);
1.1076    raeburn   963:     my $lowest_load = 30000;
1.1259    raeburn   964:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    965:     if ($skiploadbal) {
                    966:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    967:         unless (defined($cached)) {
                    968:             my $cachetime = 60*60*24;
                    969:             my %domconfig =
                    970:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    971:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    972:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    973:                                            $cachetime);
                    974:             }
                    975:         }
                    976:     }
1.1076    raeburn   977:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn   978:         if ($skiploadbal) {
                    979:             if (ref($balancers) eq 'HASH') {
                    980:                 next if (exists($balancers->{$lonhost}));
                    981:             }
                    982:         }   
1.1115    raeburn   983:         my $loginvia;
                    984:         if ($checkloginvia) {
                    985:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   986:             if ($loginvia) {
                    987:                 my ($server,$path) = split(/:/,$loginvia);
                    988:                 ($login_host, $lowest_load) =
1.1253    raeburn   989:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   990:                 if ($login_host eq $server) {
                    991:                     $portal_path = $path;
1.1151    raeburn   992:                     $isredirect = 1;
1.1116    raeburn   993:                 }
                    994:             } else {
                    995:                 ($login_host, $lowest_load) =
1.1253    raeburn   996:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn   997:                 if ($login_host eq $lonhost) {
                    998:                     $portal_path = '';
1.1151    raeburn   999:                     $isredirect = ''; 
1.1116    raeburn  1000:                 }
                   1001:             }
                   1002:         } else {
1.1076    raeburn  1003:             ($login_host, $lowest_load) =
1.1253    raeburn  1004:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1005:         }
                   1006:     }
                   1007:     if ($login_host ne '') {
1.1116    raeburn  1008:         $hostname = &hostname($login_host);
1.1076    raeburn  1009:     }
1.1151    raeburn  1010:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn  1011: }
                   1012: 
1.202     matthew  1013: # --------------------------------------------- Try to change a user's password
                   1014: 
                   1015: sub changepass {
1.799     raeburn  1016:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1017:     $currentpass = &escape($currentpass);
                   1018:     $newpass     = &escape($newpass);
1.1030    raeburn  1019:     my $lonhost = $perlvar{'lonHostID'};
                   1020:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1021: 		       $server);
                   1022:     if (! $answer) {
                   1023: 	&logthis("No reply on password change request to $server ".
                   1024: 		 "by $uname in domain $udom.");
                   1025:     } elsif ($answer =~ "^ok") {
                   1026:         &logthis("$uname in $udom successfully changed their password ".
                   1027: 		 "on $server.");
                   1028:     } elsif ($answer =~ "^pwchange_failure") {
                   1029: 	&logthis("$uname in $udom was unable to change their password ".
                   1030: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1031: 		 "or pwchange");
                   1032:     } elsif ($answer =~ "^non_authorized") {
                   1033:         &logthis("$uname in $udom did not get their password correct when ".
                   1034: 		 "attempting to change it on $server.");
                   1035:     } elsif ($answer =~ "^auth_mode_error") {
                   1036:         &logthis("$uname in $udom attempted to change their password despite ".
                   1037: 		 "not being locally or internally authenticated on $server.");
                   1038:     } elsif ($answer =~ "^unknown_user") {
                   1039:         &logthis("$uname in $udom attempted to change their password ".
                   1040: 		 "on $server but were unable to because $server is not ".
                   1041: 		 "their home server.");
                   1042:     } elsif ($answer =~ "^refused") {
                   1043: 	&logthis("$server refused to change $uname in $udom password because ".
                   1044: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1045:     } elsif ($answer =~ "invalid_client") {
                   1046:         &logthis("$server refused to change $uname in $udom password because ".
                   1047:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1048:     }
                   1049:     return $answer;
1.1       albertel 1050: }
                   1051: 
1.169     harris41 1052: # ----------------------- Try to determine user's current authentication scheme
                   1053: 
                   1054: sub queryauthenticate {
                   1055:     my ($uname,$udom)=@_;
1.456     albertel 1056:     my $uhome=&homeserver($uname,$udom);
                   1057:     if (!$uhome) {
                   1058: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1059: 	return 'no_host';
                   1060:     }
                   1061:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1062:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1063: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1064:     }
1.456     albertel 1065:     return $answer;
1.169     harris41 1066: }
                   1067: 
1.1       albertel 1068: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1069: 
1.1       albertel 1070: sub authenticate {
1.1073    raeburn  1071:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1072:     $upass=&escape($upass);
                   1073:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1074:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1075:     my $newhome;
1.836     www      1076:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1077: # Maybe the machine was offline and only re-appeared again recently?
                   1078:         &reconlonc();
                   1079: # One more
1.952     raeburn  1080: 	$uhome=&homeserver($uname,$udom,1);
                   1081:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1082:             if (defined(&domain($udom,'primary'))) {
                   1083:                 $newhome=&domain($udom,'primary');
                   1084:             }
                   1085:             if ($newhome ne '') {
                   1086:                 $uhome = $newhome;
                   1087:             }
                   1088:         }
1.836     www      1089: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1090: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1091: 	    return 'no_host';
                   1092:         }
1.1       albertel 1093:     }
1.1073    raeburn  1094:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1095:     if ($answer eq 'authorized') {
1.952     raeburn  1096:         if ($newhome) {
                   1097:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1098:             return 'no_account_on_host'; 
                   1099:         } else {
                   1100:             &logthis("User $uname at $udom authorized by $uhome");
                   1101:             return $uhome;
                   1102:         }
1.471     albertel 1103:     }
                   1104:     if ($answer eq 'non_authorized') {
                   1105: 	&logthis("User $uname at $udom rejected by $uhome");
                   1106: 	return 'no_host'; 
1.9       www      1107:     }
1.471     albertel 1108:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1109:     return 'no_host';
                   1110: }
                   1111: 
1.1073    raeburn  1112: sub can_host_session {
1.1074    raeburn  1113:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1114:     my $canhost = 1;
1.1074    raeburn  1115:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1116:     if (ref($remotesessions) eq 'HASH') {
                   1117:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1118:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1119:                 $canhost = 0;
                   1120:             } else {
                   1121:                 $canhost = 1;
                   1122:             }
                   1123:         }
                   1124:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1125:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1126:                 $canhost = 1;
                   1127:             } else {
                   1128:                 $canhost = 0;
                   1129:             }
                   1130:         }
                   1131:         if ($canhost) {
                   1132:             if ($remotesessions->{'version'} ne '') {
                   1133:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1134:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1135:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1136:                         my $major = $1;
                   1137:                         my $minor = $2;
                   1138:                         if (($major < $reqmajor ) ||
                   1139:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1140:                             $canhost = 0;
                   1141:                         }
                   1142:                     } else {
                   1143:                         $canhost = 0;
                   1144:                     }
                   1145:                 }
                   1146:             }
                   1147:         }
                   1148:     }
                   1149:     if ($canhost) {
                   1150:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1151:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1152:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1153:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1154:                 if (($uint_dom ne '') && 
                   1155:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1156:                     $canhost = 0;
                   1157:                 } else {
                   1158:                     $canhost = 1;
                   1159:                 }
                   1160:             }
                   1161:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1162:                 if (($uint_dom ne '') && 
                   1163:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1164:                     $canhost = 1;
                   1165:                 } else {
                   1166:                     $canhost = 0;
                   1167:                 }
                   1168:             }
                   1169:         }
                   1170:     }
                   1171:     return $canhost;
                   1172: }
                   1173: 
1.1083    raeburn  1174: sub spare_can_host {
                   1175:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1176:     my $canhost=1;
1.1279    raeburn  1177:     my $try_server_hostname = &hostname($try_server);
                   1178:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1179:     my $serverhomedom = &host_domain($serverhomeID);
                   1180:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1181:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1182:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1183:             $canhost = 0;
                   1184:         }
                   1185:     }
                   1186:     if (($canhost) && ($uint_dom)) {
                   1187:         my @intdoms;
                   1188:         my $internet_names = &get_internet_names($try_server);
                   1189:         if (ref($internet_names) eq 'ARRAY') {
                   1190:             @intdoms = @{$internet_names};
                   1191:         }
                   1192:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1193:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1194:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1195:                                          $remotesessions,
                   1196:                                          $defdomdefaults{'hostedsessions'});
                   1197:         }
1.1083    raeburn  1198:     }
                   1199:     return $canhost;
                   1200: }
                   1201: 
1.1123    raeburn  1202: sub this_host_spares {
                   1203:     my ($dom) = @_;
1.1126    raeburn  1204:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1205:     my @hosts = &current_machine_ids();
                   1206:     foreach my $lonhost (@hosts) {
                   1207:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1208:             $dom_in_use = $dom;
                   1209:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1210:             last;
                   1211:         }
                   1212:     }
1.1126    raeburn  1213:     if ($dom_in_use ne '') {
                   1214:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1215:     }
                   1216:     if (ref($result) ne 'HASH') {
                   1217:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1218:         $dom_in_use = &host_domain($lonhost_in_use);
                   1219:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1220:         if (ref($result) ne 'HASH') {
                   1221:             $result = \%spareid;
                   1222:         }
                   1223:     }
                   1224:     return $result;
                   1225: }
                   1226: 
                   1227: sub spares_for_offload  {
                   1228:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1229:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1230:     if (defined($cached)) {
                   1231:         return $result;
                   1232:     } else {
1.1126    raeburn  1233:         my $cachetime = 60*60*24;
                   1234:         my %domconfig =
                   1235:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1236:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1237:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1238:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1239:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1240:                 }
                   1241:             }
                   1242:         }
                   1243:     }
1.1126    raeburn  1244:     return;
1.1123    raeburn  1245: }
                   1246: 
1.1129    raeburn  1247: sub get_lonbalancer_config {
                   1248:     my ($servers) = @_;
                   1249:     my ($currbalancer,$currtargets);
                   1250:     if (ref($servers) eq 'HASH') {
                   1251:         foreach my $server (keys(%{$servers})) {
                   1252:             my %what = (
                   1253:                          spareid => 1,
                   1254:                          perlvar => 1,
                   1255:                        );
                   1256:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1257:             if ($result eq 'ok') {
                   1258:                 if (ref($returnhash) eq 'HASH') {
                   1259:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1260:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1261:                             $currbalancer = $server;
                   1262:                             $currtargets = {};
                   1263:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1264:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1265:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1266:                                 }
                   1267:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1268:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1269:                                 }
                   1270:                             }
                   1271:                             last;
                   1272:                         }
                   1273:                     }
                   1274:                 }
                   1275:             }
                   1276:         }
                   1277:     }
                   1278:     return ($currbalancer,$currtargets);
                   1279: }
                   1280: 
                   1281: sub check_loadbalancing {
                   1282:     my ($uname,$udom) = @_;
1.1191    raeburn  1283:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1284:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1285:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1286:     my @hosts = &current_machine_ids();
1.1129    raeburn  1287:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1288:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1289:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1290:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1291:     my $domneedscache;
1.1129    raeburn  1292:     my $cachetime = 60*60*24;
                   1293: 
                   1294:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1295:         $dom_in_use = $udom;
                   1296:         $homeintdom = 1;
                   1297:     } else {
                   1298:         $dom_in_use = $serverhomedom;
                   1299:     }
                   1300:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1301:     unless (defined($cached)) {
                   1302:         my %domconfig =
                   1303:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1304:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1305:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1306:         } else {
                   1307:             $domneedscache = $dom_in_use;
1.1129    raeburn  1308:         }
                   1309:     }
                   1310:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1311:         ($is_balancer,$currtargets,$currrules) = 
                   1312:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1313:         if ($is_balancer) {
                   1314:             if (ref($currrules) eq 'HASH') {
                   1315:                 if ($homeintdom) {
                   1316:                     if ($uname ne '') {
                   1317:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1318:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1319:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1320:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1321:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1322:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1323:                             }
                   1324:                         }
                   1325:                         if ($rule_in_effect eq '') {
                   1326:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1327:                             if ($userenv{'inststatus'} ne '') {
                   1328:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1329:                                 my ($othertitle,$usertypes,$types) =
                   1330:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1331:                                 if (ref($types) eq 'ARRAY') {
                   1332:                                     foreach my $type (@{$types}) {
                   1333:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1334:                                             if (exists($currrules->{$type})) {
                   1335:                                                 $rule_in_effect = $currrules->{$type};
                   1336:                                             }
                   1337:                                         }
                   1338:                                     }
                   1339:                                 }
                   1340:                             } else {
                   1341:                                 if (exists($currrules->{'default'})) {
                   1342:                                     $rule_in_effect = $currrules->{'default'};
                   1343:                                 }
                   1344:                             }
                   1345:                         }
                   1346:                     } else {
                   1347:                         if (exists($currrules->{'default'})) {
                   1348:                             $rule_in_effect = $currrules->{'default'};
                   1349:                         }
                   1350:                     }
                   1351:                 } else {
                   1352:                     if ($currrules->{'_LC_external'} ne '') {
                   1353:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1354:                     }
                   1355:                 }
                   1356:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1357:                                                        $uname,$udom);
                   1358:             }
                   1359:         }
                   1360:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1361:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1362:         unless (defined($cached)) {
                   1363:             my %domconfig =
                   1364:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1365:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1366:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1367:             } else {
                   1368:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1369:             }
                   1370:         }
                   1371:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1372:             ($is_balancer,$currtargets,$currrules) = 
                   1373:                 &check_balancer_result($result,@hosts);
                   1374:             if ($is_balancer) {
1.1129    raeburn  1375:                 if (ref($currrules) eq 'HASH') {
                   1376:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1377:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1378:                     }
                   1379:                 }
                   1380:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1381:                                                        $uname,$udom);
                   1382:             }
                   1383:         } else {
                   1384:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1385:                 $is_balancer = 1;
                   1386:                 $offloadto = &this_host_spares($dom_in_use);
                   1387:             }
1.1307    raeburn  1388:             unless (defined($cached)) {
                   1389:                 $domneedscache = $serverhomedom;
                   1390:             }
1.1129    raeburn  1391:         }
                   1392:     } else {
                   1393:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1394:             $is_balancer = 1;
                   1395:             $offloadto = &this_host_spares($dom_in_use);
                   1396:         }
1.1307    raeburn  1397:         unless (defined($cached)) {
                   1398:             $domneedscache = $serverhomedom;
                   1399:         }
                   1400:     }
                   1401:     if ($domneedscache) {
                   1402:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1403:     }
1.1176    raeburn  1404:     if ($is_balancer) {
                   1405:         my $lowest_load = 30000;
                   1406:         if (ref($offloadto) eq 'HASH') {
                   1407:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1408:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1409:                     ($otherserver,$lowest_load) =
                   1410:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1411:                 }
1.1129    raeburn  1412:             }
1.1176    raeburn  1413:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1414: 
1.1176    raeburn  1415:             if (!$found_server) {
                   1416:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1417:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1418:                         ($otherserver,$lowest_load) =
                   1419:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1420:                     }
                   1421:                 }
                   1422:             }
                   1423:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1424:             if (@{$offloadto} == 1) {
                   1425:                 $otherserver = $offloadto->[0];
                   1426:             } elsif (@{$offloadto} > 1) {
                   1427:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1428:                     ($otherserver,$lowest_load) =
                   1429:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1430:                 }
                   1431:             }
                   1432:         }
1.1176    raeburn  1433:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1434:             $is_balancer = 0;
                   1435:             if ($uname ne '' && $udom ne '') {
                   1436:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1437:                     
                   1438:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1439:                              'user.loadbalcheck.time' => time});
                   1440:                 }
1.1129    raeburn  1441:             }
                   1442:         }
                   1443:     }
                   1444:     return ($is_balancer,$otherserver);
                   1445: }
                   1446: 
1.1191    raeburn  1447: sub check_balancer_result {
                   1448:     my ($result,@hosts) = @_;
                   1449:     my ($is_balancer,$currtargets,$currrules);
                   1450:     if (ref($result) eq 'HASH') {
                   1451:         if ($result->{'lonhost'} ne '') {
                   1452:             my $currbalancer = $result->{'lonhost'};
                   1453:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1454:                 $is_balancer = 1;
                   1455:                 $currtargets = $result->{'targets'};
                   1456:                 $currrules = $result->{'rules'};
                   1457:             }
                   1458:         } else {
                   1459:             foreach my $key (keys(%{$result})) {
                   1460:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1461:                     (ref($result->{$key}) eq 'HASH')) {
                   1462:                     $is_balancer = 1;
                   1463:                     $currrules = $result->{$key}{'rules'};
                   1464:                     $currtargets = $result->{$key}{'targets'};
                   1465:                     last;
                   1466:                 }
                   1467:             }
                   1468:         }
                   1469:     }
                   1470:     return ($is_balancer,$currtargets,$currrules);
                   1471: }
                   1472: 
1.1129    raeburn  1473: sub get_loadbalancer_targets {
                   1474:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1475:     my $offloadto;
1.1175    raeburn  1476:     if ($rule_in_effect eq 'none') {
                   1477:         return [$perlvar{'lonHostID'}];
                   1478:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1479:         $offloadto = $currtargets;
                   1480:     } else {
                   1481:         if ($rule_in_effect eq 'homeserver') {
                   1482:             my $homeserver = &homeserver($uname,$udom);
                   1483:             if ($homeserver ne 'no_host') {
                   1484:                 $offloadto = [$homeserver];
                   1485:             }
                   1486:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1487:             my %domconfig =
                   1488:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1489:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1490:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1491:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1492:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1493:                     }
                   1494:                 }
                   1495:             } else {
1.1178    raeburn  1496:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1497:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1498:                 if (&hostname($remotebalancer) ne '') {
                   1499:                     $offloadto = [$remotebalancer];
                   1500:                 }
                   1501:             }
                   1502:         } elsif (&hostname($rule_in_effect) ne '') {
                   1503:             $offloadto = [$rule_in_effect];
                   1504:         }
                   1505:     }
                   1506:     return $offloadto;
                   1507: }
                   1508: 
1.1127    raeburn  1509: sub internet_dom_servers {
                   1510:     my ($dom) = @_;
                   1511:     my (%uniqservers,%servers);
                   1512:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1513:     my @machinedoms = &machine_domains($primaryserver);
                   1514:     foreach my $mdom (@machinedoms) {
                   1515:         my %currservers = %servers;
                   1516:         my %server = &get_servers($mdom);
                   1517:         %servers = (%currservers,%server);
                   1518:     }
                   1519:     my %by_hostname;
                   1520:     foreach my $id (keys(%servers)) {
                   1521:         push(@{$by_hostname{$servers{$id}}},$id);
                   1522:     }
                   1523:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1524:         if (@{$by_hostname{$hostname}} > 1) {
                   1525:             my $match = 0;
                   1526:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1527:                 if (&host_domain($id) eq $dom) {
                   1528:                     $uniqservers{$id} = $hostname;
                   1529:                     $match = 1;
                   1530:                 }
                   1531:             }
                   1532:             unless ($match) {
                   1533:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1534:             }
                   1535:         } else {
                   1536:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1537:         }
                   1538:     }
                   1539:     return %uniqservers;
                   1540: }
                   1541: 
1.1       albertel 1542: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1543: 
1.599     albertel 1544: my %homecache;
1.1       albertel 1545: sub homeserver {
1.230     stredwic 1546:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1547:     my $index="$uname:$udom";
1.426     albertel 1548: 
1.599     albertel 1549:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1550: 
                   1551:     my %servers = &get_servers($udom,'library');
                   1552:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1553:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1554: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1555: 
                   1556: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1557: 	if ($answer eq 'found') {
                   1558: 	    delete($badServerCache{$tryserver}); 
                   1559: 	    return $homecache{$index}=$tryserver;
                   1560: 	} elsif ($answer eq 'no_host') {
                   1561: 	    $badServerCache{$tryserver}=1;
                   1562: 	}
1.1       albertel 1563:     }    
                   1564:     return 'no_host';
1.70      www      1565: }
                   1566: 
1.1300    raeburn  1567: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1568: 
                   1569: sub idget {
1.1300    raeburn  1570:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1571:     my %returnhash=();
1.1300    raeburn  1572:     my @ids=(); 
                   1573:     if (ref($idsref) eq 'ARRAY') {
                   1574:         @ids = @{$idsref};
                   1575:     } else {
                   1576:         return %returnhash; 
                   1577:     }
                   1578:     if ($namespace eq '') {
                   1579:         $namespace = 'ids';
                   1580:     }
1.70      www      1581:     
1.841     albertel 1582:     my %servers = &get_servers($udom,'library');
                   1583:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1584: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1585: 	if ($namespace eq 'ids') {
                   1586: 	    $idlist=~tr/A-Z/a-z/;
                   1587: 	}
                   1588: 	my $reply;
                   1589: 	if ($namespace eq 'ids') {
                   1590: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1591: 	} else {
                   1592: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1593: 	}
1.841     albertel 1594: 	my @answer=();
                   1595: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1596: 	    @answer=split(/\&/,$reply);
                   1597: 	}                    ;
                   1598: 	my $i;
                   1599: 	for ($i=0;$i<=$#ids;$i++) {
                   1600: 	    if ($answer[$i]) {
1.1299    raeburn  1601: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1602: 	    }
1.841     albertel 1603: 	}
1.1300    raeburn  1604:     }
1.70      www      1605:     return %returnhash;
                   1606: }
                   1607: 
                   1608: # ------------------------------------- Find the IDs behind a list of usernames
                   1609: 
                   1610: sub idrget {
                   1611:     my ($udom,@unames)=@_;
                   1612:     my %returnhash=();
1.800     albertel 1613:     foreach my $uname (@unames) {
                   1614:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1615:     }
1.70      www      1616:     return %returnhash;
                   1617: }
                   1618: 
1.1300    raeburn  1619: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1620: 
                   1621: sub idput {
1.1300    raeburn  1622:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1623:     my %servers=();
1.1300    raeburn  1624:     my %ids=();
                   1625:     my %byid = ();
                   1626:     if (ref($idsref) eq 'HASH') {
                   1627:         %ids=%{$idsref};
                   1628:     }
                   1629:     if ($namespace eq '') {
                   1630:         $namespace = 'ids'; 
                   1631:     }
1.800     albertel 1632:     foreach my $uname (keys(%ids)) {
                   1633: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1634:         if ($uhom eq '') {
                   1635:             $uhom=&homeserver($uname,$udom);
                   1636:         }
1.70      www      1637:         if ($uhom ne 'no_host') {
1.800     albertel 1638:             my $esc_unam=&escape($uname);
1.1300    raeburn  1639:             if ($namespace eq 'ids') {
                   1640:                 my $id=&escape($ids{$uname});
                   1641:                 $id=~tr/A-Z/a-z/;
                   1642:                 my $esc_unam=&escape($uname);
                   1643:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1644:             } else {
1.1300    raeburn  1645:                 my @currids = split(/,/,$ids{$uname});
                   1646:                 foreach my $id (@currids) {
                   1647:                     $byid{$uhom}{$id} .= $uname.',';
                   1648:                 }
                   1649:             }
                   1650:         }
                   1651:     }
                   1652:     if ($namespace eq 'clickers') {
                   1653:         foreach my $server (keys(%byid)) {
                   1654:             if (ref($byid{$server}) eq 'HASH') {
                   1655:                 foreach my $id (keys(%{$byid{$server}})) {
                   1656:                     $byid{$server} =~ s/,$//;
                   1657:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1658:                 }
1.70      www      1659:             }
                   1660:         }
1.191     harris41 1661:     }
1.800     albertel 1662:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1663:         $servers{$server} =~ s/\&$//;
                   1664:         if ($namespace eq 'ids') {     
                   1665:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1666:         } else {
                   1667:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1668:         }
1.191     harris41 1669:     }
1.344     www      1670: }
                   1671: 
1.1300    raeburn  1672: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1673: 
                   1674: sub iddel {
1.1300    raeburn  1675:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1676:     my %result=();
1.1300    raeburn  1677:     my %ids=();
                   1678:     my %byid = ();
                   1679:     if (ref($idshashref) eq 'HASH') {
                   1680:         %ids=%{$idshashref};
                   1681:     } else {
1.1231    raeburn  1682:         return %result;
                   1683:     }
1.1300    raeburn  1684:     if ($namespace eq '') {
                   1685:         $namespace = 'ids';
                   1686:     }
1.1231    raeburn  1687:     my %servers=();
1.1300    raeburn  1688:     while (my ($id,$unamestr) = each(%ids)) {
                   1689:         if ($namespace eq 'ids') {
                   1690:             my $uhom = $uhome;
                   1691:             if ($uhom eq '') { 
                   1692:                 $uhom=&homeserver($unamestr,$udom);
                   1693:             }
                   1694:             if ($uhom ne 'no_host') {
                   1695:                 $servers{$uhom}.='&'.&escape($id);
                   1696:             }
                   1697:          } else {
                   1698:             my @curritems = split(/,/,$ids{$id});
                   1699:             foreach my $uname (@curritems) {
                   1700:                 my $uhom = $uhome;
                   1701:                 if ($uhom eq '') {
                   1702:                     $uhom=&homeserver($uname,$udom);
                   1703:                 }
                   1704:                 if ($uhom ne 'no_host') { 
                   1705:                     $byid{$uhom}{$id} .= $uname.',';
                   1706:                 }
                   1707:             }
1.1231    raeburn  1708:         }
1.1300    raeburn  1709:     }
                   1710:     if ($namespace eq 'clickers') {
                   1711:         foreach my $server (keys(%byid)) {
                   1712:             if (ref($byid{$server}) eq 'HASH') {
                   1713:                 foreach my $id (keys(%{$byid{$server}})) {
                   1714:                     $byid{$server}{$id} =~ s/,$//;
                   1715:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1716:                 }
1.1231    raeburn  1717:             }
                   1718:         }
                   1719:     }
                   1720:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1721:         $servers{$server} =~ s/\&$//;
                   1722:         if ($namespace eq 'ids') {
                   1723:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1724:         } elsif ($namespace eq 'clickers') {
                   1725:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1726:         }
1.1231    raeburn  1727:     }
                   1728:     return %result;
                   1729: }
                   1730: 
1.1300    raeburn  1731: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1732: 
                   1733: sub updateclickers {
                   1734:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1735:     my %clickers;
                   1736:     if (ref($idshashref) eq 'HASH') {
                   1737:         %clickers=%{$idshashref};
                   1738:     } else {
                   1739:         return;
                   1740:     }
                   1741:     my $items='';
                   1742:     foreach my $item (keys(%clickers)) {
                   1743:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1744:     }
                   1745:     $items=~s/\&$//;
                   1746:     my $request = "updateclickers:$udom:$action:$items";
                   1747:     if ($critical) {
                   1748:         return &critical($request,$uhome);
                   1749:     } else {
                   1750:         return &reply($request,$uhome);
                   1751:     }
                   1752: }
                   1753: 
1.1023    raeburn  1754: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1755: sub dump_dom {
1.1165    droeschl 1756:     my ($namespace, $udom, $regexp) = @_;
                   1757: 
                   1758:     $udom ||= $env{'user.domain'};
                   1759: 
                   1760:     return () unless $udom;
                   1761: 
                   1762:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1763: }
                   1764: 
1.1023    raeburn  1765: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1766: 
                   1767: sub get_dom {
1.860     raeburn  1768:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1769:     return if ($udom eq 'public');
1.806     raeburn  1770:     my $items='';
                   1771:     foreach my $item (@$storearr) {
                   1772:         $items.=&escape($item).'&';
                   1773:     }
                   1774:     $items=~s/\&$//;
1.860     raeburn  1775:     if (!$udom) {
                   1776:         $udom=$env{'user.domain'};
1.1267    raeburn  1777:         return if ($udom eq 'public');
1.860     raeburn  1778:         if (defined(&domain($udom,'primary'))) {
                   1779:             $uhome=&domain($udom,'primary');
                   1780:         } else {
1.874     albertel 1781:             undef($uhome);
1.860     raeburn  1782:         }
                   1783:     } else {
                   1784:         if (!$uhome) {
                   1785:             if (defined(&domain($udom,'primary'))) {
                   1786:                 $uhome=&domain($udom,'primary');
                   1787:             }
                   1788:         }
                   1789:     }
                   1790:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1791:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1792:         my %returnhash;
1.875     albertel 1793:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1794:             return %returnhash;
                   1795:         }
1.806     raeburn  1796:         my @pairs=split(/\&/,$rep);
                   1797:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1798:             return @pairs;
                   1799:         }
                   1800:         my $i=0;
                   1801:         foreach my $item (@$storearr) {
                   1802:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1803:             $i++;
                   1804:         }
                   1805:         return %returnhash;
                   1806:     } else {
1.880     banghart 1807:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1808:     }
                   1809: }
                   1810: 
                   1811: # -------------------------------------------- put items in domain db files 
                   1812: 
                   1813: sub put_dom {
1.860     raeburn  1814:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1815:     if (!$udom) {
                   1816:         $udom=$env{'user.domain'};
                   1817:         if (defined(&domain($udom,'primary'))) {
                   1818:             $uhome=&domain($udom,'primary');
                   1819:         } else {
1.874     albertel 1820:             undef($uhome);
1.860     raeburn  1821:         }
                   1822:     } else {
                   1823:         if (!$uhome) {
                   1824:             if (defined(&domain($udom,'primary'))) {
                   1825:                 $uhome=&domain($udom,'primary');
                   1826:             }
                   1827:         }
                   1828:     } 
                   1829:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1830:         my $items='';
                   1831:         foreach my $item (keys(%$storehash)) {
                   1832:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1833:         }
                   1834:         $items=~s/\&$//;
                   1835:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1836:     } else {
1.860     raeburn  1837:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1838:     }
                   1839: }
                   1840: 
1.1023    raeburn  1841: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1842: sub newput_dom {
1.1023    raeburn  1843:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1844:     my $result;
                   1845:     if (!$udom) {
                   1846:         $udom=$env{'user.domain'};
                   1847:     }
1.1023    raeburn  1848:     if ($udom) {
                   1849:         my $uname = &get_domainconfiguser($udom);
                   1850:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1851:     }
                   1852:     return $result;
                   1853: }
                   1854: 
1.1023    raeburn  1855: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1856: sub del_dom {
1.1023    raeburn  1857:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1858:     if (ref($storearr) eq 'ARRAY') {
                   1859:         if (!$udom) {
                   1860:             $udom=$env{'user.domain'};
                   1861:         }
1.1023    raeburn  1862:         if ($udom) {
                   1863:             my $uname = &get_domainconfiguser($udom); 
                   1864:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1865:         }
                   1866:     }
                   1867: }
                   1868: 
1.1023    raeburn  1869: # ----------------------------------construct domainconfig user for a domain 
                   1870: sub get_domainconfiguser {
                   1871:     my ($udom) = @_;
                   1872:     return $udom.'-domainconfig';
                   1873: }
                   1874: 
1.837     raeburn  1875: sub retrieve_inst_usertypes {
                   1876:     my ($udom) = @_;
                   1877:     my (%returnhash,@order);
1.989     raeburn  1878:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1879:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1880:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  1881:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1882:     } else {
                   1883:         if (defined(&domain($udom,'primary'))) {
                   1884:             my $uhome=&domain($udom,'primary');
                   1885:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1886:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  1887:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1888:                 return (\%returnhash,\@order);
                   1889:             }
                   1890:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1891:             my @pairs=split(/\&/,$hashitems);
                   1892:             foreach my $item (@pairs) {
                   1893:                 my ($key,$value)=split(/=/,$item,2);
                   1894:                 $key = &unescape($key);
                   1895:                 next if ($key =~ /^error: 2 /);
                   1896:                 $returnhash{$key}=&thaw_unescape($value);
                   1897:             }
                   1898:             my @esc_order = split(/\&/,$orderitems);
                   1899:             foreach my $item (@esc_order) {
                   1900:                 push(@order,&unescape($item));
                   1901:             }
                   1902:         } else {
1.1256    raeburn  1903:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1904:         }
1.1256    raeburn  1905:         return (\%returnhash,\@order);
1.837     raeburn  1906:     }
                   1907: }
                   1908: 
1.868     raeburn  1909: sub is_domainimage {
                   1910:     my ($url) = @_;
1.1306    raeburn  1911:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1912:         if (&domain($1) ne '') {
                   1913:             return '1';
                   1914:         }
                   1915:     }
                   1916:     return;
                   1917: }
                   1918: 
1.899     raeburn  1919: sub inst_directory_query {
                   1920:     my ($srch) = @_;
                   1921:     my $udom = $srch->{'srchdomain'};
                   1922:     my %results;
                   1923:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1924:     my $outcome;
1.899     raeburn  1925:     if ($homeserver ne '') {
1.904     albertel 1926: 	my $queryid=&reply("querysend:instdirsearch:".
                   1927: 			   &escape($srch->{'srchby'}).':'.
                   1928: 			   &escape($srch->{'srchterm'}).':'.
                   1929: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1930: 	my $host=&hostname($homeserver);
                   1931: 	if ($queryid !~/^\Q$host\E\_/) {
                   1932: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1933: 	    return;
                   1934: 	}
                   1935: 	my $response = &get_query_reply($queryid);
                   1936: 	my $maxtries = 5;
                   1937: 	my $tries = 1;
                   1938: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1939: 	    $response = &get_query_reply($queryid);
                   1940: 	    $tries ++;
                   1941: 	}
                   1942: 
                   1943:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1944:             if ($response eq 'unavailable') {
                   1945:                 $outcome = $response;
                   1946:             } else {
                   1947:                 $outcome = 'ok';
                   1948:                 my @matches = split(/\n/,$response);
                   1949:                 foreach my $match (@matches) {
                   1950:                     my ($key,$value) = split(/=/,$match);
                   1951:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1952:                 }
1.899     raeburn  1953:             }
                   1954:         }
                   1955:     }
1.909     raeburn  1956:     return ($outcome,%results);
1.899     raeburn  1957: }
                   1958: 
                   1959: sub usersearch {
                   1960:     my ($srch) = @_;
                   1961:     my $dom = $srch->{'srchdomain'};
                   1962:     my %results;
                   1963:     my %libserv = &all_library();
                   1964:     my $query = 'usersearch';
                   1965:     foreach my $tryserver (keys(%libserv)) {
                   1966:         if (&host_domain($tryserver) eq $dom) {
                   1967:             my $host=&hostname($tryserver);
                   1968:             my $queryid=
1.911     raeburn  1969:                 &reply("querysend:".&escape($query).':'.
                   1970:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1971:                        &escape($srch->{'srchtype'}).':'.
                   1972:                        &escape($srch->{'srchterm'}),$tryserver);
                   1973:             if ($queryid !~/^\Q$host\E\_/) {
                   1974:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1975:                 next;
1.899     raeburn  1976:             }
                   1977:             my $reply = &get_query_reply($queryid);
                   1978:             my $maxtries = 1;
                   1979:             my $tries = 1;
                   1980:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1981:                 $reply = &get_query_reply($queryid);
                   1982:                 $tries ++;
                   1983:             }
                   1984:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1985:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1986:             } else {
1.911     raeburn  1987:                 my @matches;
                   1988:                 if ($reply =~ /\n/) {
                   1989:                     @matches = split(/\n/,$reply);
                   1990:                 } else {
                   1991:                     @matches = split(/\&/,$reply);
                   1992:                 }
1.899     raeburn  1993:                 foreach my $match (@matches) {
                   1994:                     my ($uname,$udom,%userhash);
1.911     raeburn  1995:                     foreach my $entry (split(/:/,$match)) {
                   1996:                         my ($key,$value) =
                   1997:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1998:                         $userhash{$key} = $value;
                   1999:                         if ($key eq 'username') {
                   2000:                             $uname = $value;
                   2001:                         } elsif ($key eq 'domain') {
                   2002:                             $udom = $value;
1.911     raeburn  2003:                         }
1.899     raeburn  2004:                     }
                   2005:                     $results{$uname.':'.$udom} = \%userhash;
                   2006:                 }
                   2007:             }
                   2008:         }
                   2009:     }
                   2010:     return %results;
                   2011: }
                   2012: 
1.912     raeburn  2013: sub get_instuser {
                   2014:     my ($udom,$uname,$id) = @_;
                   2015:     my $homeserver = &domain($udom,'primary');
                   2016:     my ($outcome,%results);
                   2017:     if ($homeserver ne '') {
                   2018:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2019:                            &escape($id).':'.&escape($udom),$homeserver);
                   2020:         my $host=&hostname($homeserver);
                   2021:         if ($queryid !~/^\Q$host\E\_/) {
                   2022:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2023:             return;
                   2024:         }
                   2025:         my $response = &get_query_reply($queryid);
                   2026:         my $maxtries = 5;
                   2027:         my $tries = 1;
                   2028:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2029:             $response = &get_query_reply($queryid);
                   2030:             $tries ++;
                   2031:         }
                   2032:         if (!&error($response) && $response ne 'refused') {
                   2033:             if ($response eq 'unavailable') {
                   2034:                 $outcome = $response;
                   2035:             } else {
                   2036:                 $outcome = 'ok';
                   2037:                 my @matches = split(/\n/,$response);
                   2038:                 foreach my $match (@matches) {
                   2039:                     my ($key,$value) = split(/=/,$match);
                   2040:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2041:                 }
                   2042:             }
                   2043:         }
                   2044:     }
                   2045:     my %userinfo;
                   2046:     if (ref($results{$uname}) eq 'HASH') {
                   2047:         %userinfo = %{$results{$uname}};
                   2048:     } 
                   2049:     return ($outcome,%userinfo);
                   2050: }
                   2051: 
1.1290    raeburn  2052: sub get_multiple_instusers {
                   2053:     my ($udom,$users,$caller) = @_;
                   2054:     my ($outcome,$results);
                   2055:     if (ref($users) eq 'HASH') {
                   2056:         my $count = keys(%{$users}); 
                   2057:         my $requested = &freeze_escape($users);
                   2058:         my $homeserver = &domain($udom,'primary');
                   2059:         if ($homeserver ne '') {
                   2060:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2061:             my $host=&hostname($homeserver);
                   2062:             if ($queryid !~/^\Q$host\E\_/) {
                   2063:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2064:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2065:                 return ($outcome,$results);
                   2066:             }
                   2067:             my $response = &get_query_reply($queryid);
                   2068:             my $maxtries = 5;
                   2069:             if ($count > 100) {
                   2070:                 $maxtries = 1+int($count/20);
                   2071:             }
                   2072:             my $tries = 1;
                   2073:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2074:                 $response = &get_query_reply($queryid);
                   2075:                 $tries ++;
                   2076:             }
                   2077:             if ($response eq '') {
                   2078:                 $results = {};
                   2079:                 foreach my $key (keys(%{$users})) {
                   2080:                     my ($uname,$id);
                   2081:                     if ($caller eq 'id') {
                   2082:                         $id = $key;
                   2083:                     } else {
                   2084:                         $uname = $key;
                   2085:                     }
                   2086:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2087:                     $outcome = $resp;
1.1290    raeburn  2088:                     if ($resp eq 'ok') {
                   2089:                         %{$results} = (%{$results}, %info);
                   2090:                     } else {
                   2091:                         last;
                   2092:                     }
                   2093:                 }
                   2094:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2095:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2096:                     $outcome = $response;
                   2097:                 } else {
1.1291    raeburn  2098:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2099:                     if ($outcome eq 'ok') {
                   2100:                         $results = &thaw_unescape($userdata); 
                   2101:                     }
                   2102:                 }
                   2103:             }
                   2104:         }
                   2105:     }
                   2106:     return ($outcome,$results);
                   2107: }
                   2108: 
1.912     raeburn  2109: sub inst_rulecheck {
1.923     raeburn  2110:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2111:     my %returnhash;
                   2112:     if ($udom ne '') {
                   2113:         if (ref($rules) eq 'ARRAY') {
                   2114:             @{$rules} = map {&escape($_);} (@{$rules});
                   2115:             my $rulestr = join(':',@{$rules});
                   2116:             my $homeserver=&domain($udom,'primary');
                   2117:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2118:                 my $response;
                   2119:                 if ($item eq 'username') {                
                   2120:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2121:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2122:                                               $homeserver));
1.923     raeburn  2123:                 } elsif ($item eq 'id') {
                   2124:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2125:                                               ':'.&escape($id).':'.$rulestr,
                   2126:                                               $homeserver));
1.945     raeburn  2127:                 } elsif ($item eq 'selfcreate') {
                   2128:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2129:                                                &escape($udom).':'.&escape($uname).
                   2130:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2131:                 }
1.912     raeburn  2132:                 if ($response ne 'refused') {
                   2133:                     my @pairs=split(/\&/,$response);
                   2134:                     foreach my $item (@pairs) {
                   2135:                         my ($key,$value)=split(/=/,$item,2);
                   2136:                         $key = &unescape($key);
                   2137:                         next if ($key =~ /^error: 2 /);
                   2138:                         $returnhash{$key}=&thaw_unescape($value);
                   2139:                     }
                   2140:                 }
                   2141:             }
                   2142:         }
                   2143:     }
                   2144:     return %returnhash;
                   2145: }
                   2146: 
                   2147: sub inst_userrules {
1.923     raeburn  2148:     my ($udom,$check) = @_;
1.912     raeburn  2149:     my (%ruleshash,@ruleorder);
                   2150:     if ($udom ne '') {
                   2151:         my $homeserver=&domain($udom,'primary');
                   2152:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2153:             my $response;
                   2154:             if ($check eq 'id') {
                   2155:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2156:                                  $homeserver);
1.943     raeburn  2157:             } elsif ($check eq 'email') {
                   2158:                 $response=&reply('instemailrules:'.&escape($udom),
                   2159:                                  $homeserver);
1.923     raeburn  2160:             } else {
                   2161:                 $response=&reply('instuserrules:'.&escape($udom),
                   2162:                                  $homeserver);
                   2163:             }
1.912     raeburn  2164:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2165:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2166:                 ($response ne 'no_such_host')) {
                   2167:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2168:                 my @pairs=split(/\&/,$hashitems);
                   2169:                 foreach my $item (@pairs) {
                   2170:                     my ($key,$value)=split(/=/,$item,2);
                   2171:                     $key = &unescape($key);
                   2172:                     next if ($key =~ /^error: 2 /);
                   2173:                     $ruleshash{$key}=&thaw_unescape($value);
                   2174:                 }
                   2175:                 my @esc_order = split(/\&/,$orderitems);
                   2176:                 foreach my $item (@esc_order) {
                   2177:                     push(@ruleorder,&unescape($item));
                   2178:                 }
                   2179:             }
                   2180:         }
                   2181:     }
                   2182:     return (\%ruleshash,\@ruleorder);
                   2183: }
                   2184: 
1.976     raeburn  2185: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2186: 
                   2187: sub get_domain_defaults {
1.1240    raeburn  2188:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2189:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2190:     my $cachetime = 60*60*24;
1.1240    raeburn  2191:     unless ($ignore_cache) {
                   2192:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2193:         if (defined($cached)) {
                   2194:             if (ref($result) eq 'HASH') {
                   2195:                 return %{$result};
                   2196:             }
1.943     raeburn  2197:         }
                   2198:     }
                   2199:     my %domdefaults;
                   2200:     my %domconfig =
1.989     raeburn  2201:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2202:                                   'requestcourses','inststatus',
1.1183    raeburn  2203:                                   'coursedefaults','usersessions',
1.1258    raeburn  2204:                                   'requestauthor','selfenrollment',
                   2205:                                   'coursecategories'],$domain);
1.1305    raeburn  2206:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2207:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2208:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2209:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2210:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2211:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2212:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2213:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2214:     } else {
                   2215:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2216:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2217:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2218:     }
1.976     raeburn  2219:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2220:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2221:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2222:         } else {
                   2223:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2224:         }
1.1177    raeburn  2225:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2226:         foreach my $item (@usertools) {
                   2227:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2228:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2229:             }
                   2230:         }
1.1229    raeburn  2231:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2232:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2233:         }
1.976     raeburn  2234:     }
1.985     raeburn  2235:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2236:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2237:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2238:         }
                   2239:     }
1.1183    raeburn  2240:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2241:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2242:     }
1.989     raeburn  2243:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2244:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2245:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2246:         }
                   2247:     }
1.1047    raeburn  2248:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2249:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2250:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2251:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2252:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2253:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2254:         }
1.1254    raeburn  2255:         foreach my $type (@coursetypes) {
                   2256:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2257:                 unless ($type eq 'community') {
                   2258:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2259:                 }
                   2260:             }
                   2261:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2262:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2263:             }
1.1277    raeburn  2264:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2265:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2266:                     $domdefaults{$type.'postsubtimeout'} = 
                   2267:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2268:                 }
                   2269:             }
1.1230    raeburn  2270:         }
1.1286    raeburn  2271:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2272:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2273:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2274:                 if (@clonecodes) {
                   2275:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2276:                 }
                   2277:             }
                   2278:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2279:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2280:         }
1.1047    raeburn  2281:     }
1.1073    raeburn  2282:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2283:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2284:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2285:         }
                   2286:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2287:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2288:         }
1.1279    raeburn  2289:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2290:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2291:         }
1.1073    raeburn  2292:     }
1.1254    raeburn  2293:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2294:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2295:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2296:                             'approval','limit');
                   2297:             foreach my $type (@coursetypes) {
                   2298:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2299:                     my @mgrdc = ();
                   2300:                     foreach my $item (@settings) {
                   2301:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2302:                             push(@mgrdc,$item);
                   2303:                         }
                   2304:                     }
                   2305:                     if (@mgrdc) {
                   2306:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2307:                     }
                   2308:                 }
                   2309:             }
                   2310:         }
                   2311:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2312:             foreach my $type (@coursetypes) {
                   2313:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2314:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2315:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2316:                     }
                   2317:                 }
                   2318:             }
                   2319:         }
                   2320:     }
1.1258    raeburn  2321:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2322:         $domdefaults{'catauth'} = 'std';
                   2323:         $domdefaults{'catunauth'} = 'std';
                   2324:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2325:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2326:         }
                   2327:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2328:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2329:         }
                   2330:     }
1.1219    raeburn  2331:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2332:     return %domdefaults;
                   2333: }
                   2334: 
1.1311    raeburn  2335: sub course_portal_url {
                   2336:     my ($cnum,$cdom) = @_;
                   2337:     my $chome = &homeserver($cnum,$cdom);
                   2338:     my $hostname = &hostname($chome);
                   2339:     my $protocol = $protocol{$chome};
                   2340:     $protocol = 'http' if ($protocol ne 'https');
                   2341:     my %domdefaults = &get_domain_defaults($cdom);
                   2342:     my $firsturl;
                   2343:     if ($domdefaults{'portal_def'}) {
                   2344:         $firsturl = $domdefaults{'portal_def'};
                   2345:     } else {
                   2346:         $firsturl = $protocol.'://'.$hostname;
                   2347:     }
                   2348:     return $firsturl;
                   2349: }
                   2350: 
1.344     www      2351: # --------------------------------------------------- Assign a key to a student
                   2352: 
                   2353: sub assign_access_key {
1.364     www      2354: #
                   2355: # a valid key looks like uname:udom#comments
                   2356: # comments are being appended
                   2357: #
1.498     www      2358:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2359:     $kdom=
1.620     albertel 2360:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2361:     $knum=
1.620     albertel 2362:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2363:     $cdom=
1.620     albertel 2364:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2365:     $cnum=
1.620     albertel 2366:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2367:     $udom=$env{'user.name'} unless (defined($udom));
                   2368:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2369:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2370:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2371:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2372:                                                   # assigned to this person
                   2373:                                                   # - this should not happen,
1.345     www      2374:                                                   # unless something went wrong
                   2375:                                                   # the first time around
                   2376: # ready to assign
1.364     www      2377:         $logentry=$1.'; '.$logentry;
1.496     www      2378:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2379:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2380: # key now belongs to user
1.346     www      2381: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2382:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2383:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2384:                 return 'ok';
                   2385:             } else {
                   2386:                 return 
                   2387:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2388: 	    }
                   2389:         } else {
                   2390:             return 'error: Could not assign key, try again later.';
                   2391:         }
1.364     www      2392:     } elsif (!$existing{$ckey}) {
1.345     www      2393: # the key does not exist
                   2394: 	return 'error: The key does not exist';
                   2395:     } else {
                   2396: # the key is somebody else's
                   2397: 	return 'error: The key is already in use';
                   2398:     }
1.344     www      2399: }
                   2400: 
1.364     www      2401: # ------------------------------------------ put an additional comment on a key
                   2402: 
                   2403: sub comment_access_key {
                   2404: #
                   2405: # a valid key looks like uname:udom#comments
                   2406: # comments are being appended
                   2407: #
                   2408:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2409:     $cdom=
1.620     albertel 2410:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2411:     $cnum=
1.620     albertel 2412:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2413:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2414:     if ($existing{$ckey}) {
                   2415:         $existing{$ckey}.='; '.$logentry;
                   2416: # ready to assign
1.367     www      2417:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2418:                                                  $cdom,$cnum) eq 'ok') {
                   2419: 	    return 'ok';
                   2420:         } else {
                   2421: 	    return 'error: Count not store comment.';
                   2422:         }
                   2423:     } else {
                   2424: # the key does not exist
                   2425: 	return 'error: The key does not exist';
                   2426:     }
                   2427: }
                   2428: 
1.344     www      2429: # ------------------------------------------------------ Generate a set of keys
                   2430: 
                   2431: sub generate_access_keys {
1.364     www      2432:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2433:     $cdom=
1.620     albertel 2434:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2435:     $cnum=
1.620     albertel 2436:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2437:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2438:     unless (($cdom) && ($cnum)) { return 0; }
                   2439:     if ($number>10000) { return 0; }
                   2440:     sleep(2); # make sure don't get same seed twice
                   2441:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2442:     my $total=0;
                   2443:     for (my $i=1;$i<=$number;$i++) {
                   2444:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2445:                   sprintf("%lx",int(100000*rand)).'-'.
                   2446:                   sprintf("%lx",int(100000*rand));
                   2447:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2448:        $newkey=~s/0/h/g; # and also 0 and O
                   2449:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2450:        if ($existing{$newkey}) {
                   2451:            $i--;
                   2452:        } else {
1.364     www      2453: 	  if (&put('accesskeys',
                   2454:               { $newkey => '# generated '.localtime().
1.620     albertel 2455:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2456:                            '; '.$logentry },
                   2457: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2458:               $total++;
                   2459: 	  }
                   2460:        }
                   2461:     }
1.620     albertel 2462:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2463:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2464:     return $total;
                   2465: }
                   2466: 
                   2467: # ------------------------------------------------------- Validate an accesskey
                   2468: 
                   2469: sub validate_access_key {
                   2470:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2471:     $cdom=
1.620     albertel 2472:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2473:     $cnum=
1.620     albertel 2474:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2475:     $udom=$env{'user.domain'} unless (defined($udom));
                   2476:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2477:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2478:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2479: }
                   2480: 
                   2481: # ------------------------------------- Find the section of student in a course
1.652     albertel 2482: sub devalidate_getsection_cache {
                   2483:     my ($udom,$unam,$courseid)=@_;
                   2484:     my $hashid="$udom:$unam:$courseid";
                   2485:     &devalidate_cache_new('getsection',$hashid);
                   2486: }
1.298     matthew  2487: 
1.815     albertel 2488: sub courseid_to_courseurl {
                   2489:     my ($courseid) = @_;
                   2490:     #already url style courseid
                   2491:     return $courseid if ($courseid =~ m{^/});
                   2492: 
                   2493:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2494: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2495: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2496: 	return "/$cdom/$cnum";
                   2497:     }
                   2498: 
                   2499:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2500:     if (exists($courseinfo{'num'})) {
                   2501: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2502:     }
                   2503: 
                   2504:     return undef;
                   2505: }
                   2506: 
1.298     matthew  2507: sub getsection {
                   2508:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2509:     my $cachetime=1800;
1.551     albertel 2510: 
                   2511:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2512:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2513:     if (defined($cached)) { return $result; }
                   2514: 
1.298     matthew  2515:     my %Pending; 
                   2516:     my %Expired;
                   2517:     #
                   2518:     # Each role can either have not started yet (pending), be active, 
                   2519:     #    or have expired.
                   2520:     #
                   2521:     # If there is an active role, we are done.
                   2522:     #
                   2523:     # If there is more than one role which has not started yet, 
                   2524:     #     choose the one which will start sooner
                   2525:     # If there is one role which has not started yet, return it.
                   2526:     #
                   2527:     # If there is more than one expired role, choose the one which ended last.
                   2528:     # If there is a role which has expired, return it.
                   2529:     #
1.815     albertel 2530:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2531:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2532:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2533:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2534:         my $section=$1;
                   2535:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2536:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2537:         my $now=time;
1.548     albertel 2538:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2539:             $Expired{$end}=$section;
                   2540:             next;
                   2541:         }
1.548     albertel 2542:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2543:             $Pending{$start}=$section;
                   2544:             next;
                   2545:         }
1.599     albertel 2546:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2547:     }
                   2548:     #
                   2549:     # Presumedly there will be few matching roles from the above
                   2550:     # loop and the sorting time will be negligible.
                   2551:     if (scalar(keys(%Pending))) {
                   2552:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2553:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2554:     } 
                   2555:     if (scalar(keys(%Expired))) {
                   2556:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2557:         my $time = pop(@sorted);
1.599     albertel 2558:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2559:     }
1.599     albertel 2560:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2561: }
1.70      www      2562: 
1.599     albertel 2563: sub save_cache {
                   2564:     &purge_remembered();
1.722     albertel 2565:     #&Apache::loncommon::validate_page();
1.620     albertel 2566:     undef(%env);
1.780     albertel 2567:     undef($env_loaded);
1.599     albertel 2568: }
1.452     albertel 2569: 
1.599     albertel 2570: my $to_remember=-1;
                   2571: my %remembered;
                   2572: my %accessed;
                   2573: my $kicks=0;
                   2574: my $hits=0;
1.849     albertel 2575: sub make_key {
                   2576:     my ($name,$id) = @_;
1.872     albertel 2577:     if (length($id) > 65 
                   2578: 	&& length(&escape($id)) > 200) {
                   2579: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2580:     }
1.849     albertel 2581:     return &escape($name.':'.$id);
                   2582: }
                   2583: 
1.599     albertel 2584: sub devalidate_cache_new {
                   2585:     my ($name,$id,$debug) = @_;
                   2586:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2587:     $id=&make_key($name,$id);
1.599     albertel 2588:     $memcache->delete($id);
                   2589:     delete($remembered{$id});
                   2590:     delete($accessed{$id});
                   2591: }
                   2592: 
                   2593: sub is_cached_new {
                   2594:     my ($name,$id,$debug) = @_;
1.849     albertel 2595:     $id=&make_key($name,$id);
1.599     albertel 2596:     if (exists($remembered{$id})) {
1.1133    foxr     2597: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2598: 	$accessed{$id}=[&gettimeofday()];
                   2599: 	$hits++;
                   2600: 	return ($remembered{$id},1);
                   2601:     }
                   2602:     my $value = $memcache->get($id);
                   2603:     if (!(defined($value))) {
                   2604: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2605: 	return (undef,undef);
1.416     albertel 2606:     }
1.599     albertel 2607:     if ($value eq '__undef__') {
                   2608: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2609: 	$value=undef;
                   2610:     }
                   2611:     &make_room($id,$value,$debug);
                   2612:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2613:     return ($value,1);
                   2614: }
                   2615: 
                   2616: sub do_cache_new {
                   2617:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2618:     $id=&make_key($name,$id);
1.599     albertel 2619:     my $setvalue=$value;
                   2620:     if (!defined($setvalue)) {
                   2621: 	$setvalue='__undef__';
                   2622:     }
1.623     albertel 2623:     if (!defined($time) ) {
                   2624: 	$time=600;
                   2625:     }
1.599     albertel 2626:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2627:     my $result = $memcache->set($id,$setvalue,$time);
                   2628:     if (! $result) {
1.872     albertel 2629: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2630: 	$memcache->disconnect_all();
1.872     albertel 2631:     }
1.600     albertel 2632:     # need to make a copy of $value
1.919     albertel 2633:     &make_room($id,$value,$debug);
1.599     albertel 2634:     return $value;
                   2635: }
                   2636: 
                   2637: sub make_room {
                   2638:     my ($id,$value,$debug)=@_;
1.919     albertel 2639: 
                   2640:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2641:                                     : $value;
1.599     albertel 2642:     if ($to_remember<0) { return; }
                   2643:     $accessed{$id}=[&gettimeofday()];
                   2644:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2645:     my $to_kick;
                   2646:     my $max_time=0;
                   2647:     foreach my $other (keys(%accessed)) {
                   2648: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2649: 	    $to_kick=$other;
                   2650: 	    $max_time=&tv_interval($accessed{$other});
                   2651: 	}
                   2652:     }
                   2653:     delete($remembered{$to_kick});
                   2654:     delete($accessed{$to_kick});
                   2655:     $kicks++;
                   2656:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2657:     return;
                   2658: }
                   2659: 
1.599     albertel 2660: sub purge_remembered {
1.604     albertel 2661:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2662:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2663:     undef(%remembered);
                   2664:     undef(%accessed);
1.428     albertel 2665: }
1.70      www      2666: # ------------------------------------- Read an entry from a user's environment
                   2667: 
                   2668: sub userenvironment {
                   2669:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2670:     my $items;
                   2671:     foreach my $item (@what) {
                   2672:         $items.=&escape($item).'&';
                   2673:     }
                   2674:     $items=~s/\&$//;
1.70      www      2675:     my %returnhash=();
1.1009    raeburn  2676:     my $uhome = &homeserver($unam,$udom);
                   2677:     unless ($uhome eq 'no_host') {
                   2678:         my @answer=split(/\&/, 
                   2679:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2680:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2681:             return %returnhash;
                   2682:         }
1.1009    raeburn  2683:         my $i;
                   2684:         for ($i=0;$i<=$#what;$i++) {
                   2685: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2686:         }
1.70      www      2687:     }
                   2688:     return %returnhash;
1.1       albertel 2689: }
                   2690: 
1.617     albertel 2691: # ---------------------------------------------------------- Get a studentphoto
                   2692: sub studentphoto {
                   2693:     my ($udom,$unam,$ext) = @_;
                   2694:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2695:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2696:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2697:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2698:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2699:             } else {
                   2700:                 my ($result,$perm_reqd)=
1.707     albertel 2701: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2702:                 if ($result eq 'ok') {
                   2703:                     if (!($perm_reqd eq 'yes')) {
                   2704:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2705:                     }
                   2706:                 }
                   2707:             }
                   2708:         }
                   2709:     } else {
                   2710:         my ($result,$perm_reqd) = 
1.707     albertel 2711: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2712:         if ($result eq 'ok') {
                   2713:             if (!($perm_reqd eq 'yes')) {
                   2714:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2715:             }
                   2716:         }
                   2717:     }
                   2718:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2719: }
                   2720: 
                   2721: sub retrievestudentphoto {
                   2722:     my ($udom,$unam,$ext,$type) = @_;
                   2723:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2724:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2725:     if ($ret eq 'ok') {
                   2726:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2727:         if ($type eq 'thumbnail') {
                   2728:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2729:         }
                   2730:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2731:         return $tokenurl;
                   2732:     } else {
                   2733:         if ($type eq 'thumbnail') {
                   2734:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2735:         } else { 
                   2736:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2737:         }
1.617     albertel 2738:     }
                   2739: }
                   2740: 
1.263     www      2741: # -------------------------------------------------------------------- New chat
                   2742: 
                   2743: sub chatsend {
1.724     raeburn  2744:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2745:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2746:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2747:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2748:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2749: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2750: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2751: }
                   2752: 
                   2753: # ------------------------------------------ Find current version of a resource
                   2754: 
                   2755: sub getversion {
                   2756:     my $fname=&clutter(shift);
1.1189    raeburn  2757:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2758:     return &currentversion(&filelocation('',$fname));
                   2759: }
                   2760: 
                   2761: sub currentversion {
                   2762:     my $fname=shift;
                   2763:     my $author=$fname;
                   2764:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2765:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2766:     my $home=&homeserver($uname,$udom);
1.292     www      2767:     if ($home eq 'no_host') { 
                   2768:         return -1; 
                   2769:     }
1.1112    www      2770:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2771:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2772: 	return -1;
                   2773:     }
1.1112    www      2774:     return $answer;
1.263     www      2775: }
                   2776: 
1.1111    www      2777: #
                   2778: # Return special version number of resource if set by override, empty otherwise
                   2779: #
                   2780: sub usedversion {
                   2781:     my $fname=shift;
                   2782:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2783:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2784:     if ($urlversion) { return $urlversion; }
                   2785:     return '';
                   2786: }
                   2787: 
1.1       albertel 2788: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2789: 
1.1       albertel 2790: sub subscribe {
                   2791:     my $fname=shift;
1.761     raeburn  2792:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2793:     $fname=~s/[\n\r]//g;
1.1       albertel 2794:     my $author=$fname;
                   2795:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2796:     my ($udom,$uname)=split(/\//,$author);
                   2797:     my $home=homeserver($uname,$udom);
1.335     albertel 2798:     if ($home eq 'no_host') {
                   2799:         return 'not_found';
1.1       albertel 2800:     }
                   2801:     my $answer=reply("sub:$fname",$home);
1.64      www      2802:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2803: 	$answer.=' by '.$home;
                   2804:     }
1.1       albertel 2805:     return $answer;
                   2806: }
                   2807:     
1.8       www      2808: # -------------------------------------------------------------- Replicate file
                   2809: 
                   2810: sub repcopy {
                   2811:     my $filename=shift;
1.23      www      2812:     $filename=~s/\/+/\//g;
1.1142    raeburn  2813:     my $londocroot = $perlvar{'lonDocRoot'};
                   2814:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2815:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2816:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2817: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2818: 	return &repcopy_userfile($filename);
                   2819:     }
1.532     albertel 2820:     $filename=~s/[\n\r]//g;
1.8       www      2821:     my $transname="$filename.in.transfer";
1.828     www      2822: # FIXME: this should flock
1.607     raeburn  2823:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2824:     my $remoteurl=subscribe($filename);
1.64      www      2825:     if ($remoteurl =~ /^con_lost by/) {
                   2826: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2827:            return 'unavailable';
1.8       www      2828:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2829: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2830: 	   return 'not_found';
1.64      www      2831:     } elsif ($remoteurl =~ /^rejected by/) {
                   2832: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2833:            return 'forbidden';
1.20      www      2834:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2835:            return 'ok';
1.8       www      2836:     } else {
1.290     www      2837:         my $author=$filename;
                   2838:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2839:         my ($udom,$uname)=split(/\//,$author);
                   2840:         my $home=homeserver($uname,$udom);
                   2841:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2842:            my @parts=split(/\//,$filename);
                   2843:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2844:            if ($path ne "$londocroot/res") {
1.8       www      2845:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2846: 	       return 'bad_request';
1.8       www      2847:            }
                   2848:            my $count;
                   2849:            for ($count=5;$count<$#parts;$count++) {
                   2850:                $path.="/$parts[$count]";
                   2851:                if ((-e $path)!=1) {
                   2852: 		   mkdir($path,0777);
                   2853:                }
                   2854:            }
                   2855:            my $ua=new LWP::UserAgent;
                   2856:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2857:            my $response=$ua->request($request,$transname);
                   2858:            if ($response->is_error()) {
                   2859: 	       unlink($transname);
                   2860:                my $message=$response->status_line;
1.672     albertel 2861:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2862:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2863:                return 'unavailable';
1.8       www      2864:            } else {
1.16      www      2865: 	       if ($remoteurl!~/\.meta$/) {
                   2866:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2867:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2868:                   if ($mresponse->is_error()) {
                   2869: 		      unlink($filename.'.meta');
                   2870:                       &logthis(
1.672     albertel 2871:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2872:                   }
                   2873: 	       }
1.8       www      2874:                rename($transname,$filename);
1.607     raeburn  2875:                return 'ok';
1.8       www      2876:            }
1.290     www      2877:        }
1.8       www      2878:     }
1.330     www      2879: }
                   2880: 
                   2881: # ------------------------------------------------ Get server side include body
                   2882: sub ssi_body {
1.381     albertel 2883:     my ($filelink,%form)=@_;
1.606     matthew  2884:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2885:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2886:     }
1.953     www      2887:     my $output='';
                   2888:     my $response;
1.980     raeburn  2889:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2890:        ($output,$response)=&externalssi($filelink);
1.953     www      2891:     } else {
1.1004    droeschl 2892:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2893:        $filelink .= 'inhibitmenu=yes';
1.953     www      2894:        ($output,$response)=&ssi($filelink,%form);
                   2895:     }
1.778     albertel 2896:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2897:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2898:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2899:     if (wantarray) {
                   2900:         return ($output, $response);
                   2901:     } else {
                   2902:         return $output;
                   2903:     }
1.8       www      2904: }
                   2905: 
1.15      www      2906: # --------------------------------------------------------- Server Side Include
                   2907: 
1.782     albertel 2908: sub absolute_url {
                   2909:     my ($host_name) = @_;
                   2910:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2911:     if ($host_name eq '') {
                   2912: 	$host_name = $ENV{'SERVER_NAME'};
                   2913:     }
                   2914:     return $protocol.$host_name;
                   2915: }
                   2916: 
1.942     foxr     2917: #
                   2918: #   Server side include.
                   2919: # Parameters:
                   2920: #  fn     Possibly encrypted resource name/id.
                   2921: #  form   Hash that describes how the rendering should be done
                   2922: #         and other things.
1.944     foxr     2923: # Returns:
1.950     raeburn  2924: #   Scalar context: The content of the response.
                   2925: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2926: #     
1.15      www      2927: sub ssi {
                   2928: 
1.944     foxr     2929:     my ($fn,%form)=@_;
1.15      www      2930:     my $ua=new LWP::UserAgent;
1.23      www      2931:     my $request;
1.711     albertel 2932: 
                   2933:     $form{'no_update_last_known'}=1;
1.895     albertel 2934:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2935:     if (%form) {
1.782     albertel 2936:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 2937:       $request->content(join('&',map { 
                   2938:             my $name = escape($_);
                   2939:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   2940:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   2941:             : &escape($form{$_}) );    
                   2942:         } keys(%form)));
1.23      www      2943:     } else {
1.782     albertel 2944:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2945:     }
                   2946: 
1.15      www      2947:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2948:     my $response= $ua->request($request);
1.1182    foxr     2949:     my $content = $response->content;
                   2950: 
                   2951: 
1.944     foxr     2952:     if (wantarray) {
1.1173    foxr     2953: 	return ($content, $response);
1.944     foxr     2954:     } else {
1.1173    foxr     2955: 	return $content;
1.942     foxr     2956:     }
1.324     www      2957: }
                   2958: 
                   2959: sub externalssi {
                   2960:     my ($url)=@_;
                   2961:     my $ua=new LWP::UserAgent;
                   2962:     my $request=new HTTP::Request('GET',$url);
                   2963:     my $response=$ua->request($request);
1.954     raeburn  2964:     if (wantarray) {
                   2965:         return ($response->content, $response);
                   2966:     } else {
                   2967:         return $response->content;
                   2968:     }
1.15      www      2969: }
1.254     www      2970: 
1.492     albertel 2971: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2972: 
                   2973: sub allowuploaded {
                   2974:     my ($srcurl,$url)=@_;
                   2975:     $url=&clutter(&declutter($url));
                   2976:     my $dir=$url;
                   2977:     $dir=~s/\/[^\/]+$//;
                   2978:     my %httpref=();
                   2979:     my $httpurl=&hreflocation('',$url);
                   2980:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2981:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2982: }
1.477     raeburn  2983: 
1.1193    raeburn  2984: #
                   2985: # Determine if the current user should be able to edit a particular resource,
                   2986: # when viewing in course context.
                   2987: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2988: #     Functions.
                   2989: # (b) When displaying folder contents in course editor, used to determine if
                   2990: #     "Edit" link will be displayed alongside resource.
                   2991: #
1.1196    raeburn  2992: #  input: six args -- filename (decluttered), course number, course domain,
                   2993: #                   url, symb (if registered) and group (if this is a group
                   2994: #                   item -- e.g., bulletin board, group page etc.).
                   2995: #  output: array of five scalars -- 
1.1193    raeburn  2996: #          $cfile -- url for file editing if editable on current server
                   2997: #          $home -- homeserver of resource (i.e., for author if published,
                   2998: #                                           or course if uploaded.).
                   2999: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3000: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3001: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3002: #
                   3003: 
                   3004: sub can_edit_resource {
1.1194    raeburn  3005:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3006:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3007: #
                   3008: # For aboutme pages user can only edit his/her own.
                   3009: #
1.1199    raeburn  3010:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3011:         my ($sdom,$sname) = ($1,$2);
                   3012:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3013:             $home = $env{'user.home'};
                   3014:             $cfile = $resurl;
                   3015:             if ($env{'form.forceedit'}) {
                   3016:                 $forceview = 1;
                   3017:             } else {
                   3018:                 $forceedit = 1;
                   3019:             }
                   3020:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3021:         } else {
                   3022:             return;
                   3023:         }
                   3024:     }
                   3025: 
                   3026:     if ($env{'request.course.id'}) {
                   3027:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3028:         if ($group ne '') {
                   3029: # if this is a group homepage or group bulletin board, check group privs
                   3030:             my $allowed = 0;
1.1197    raeburn  3031:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3032:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3033:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3034:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3035:                     $allowed = 1;
                   3036:                 }
1.1197    raeburn  3037:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3038:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3039:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3040:                     $allowed = 1;
                   3041:                 }
                   3042:             }
                   3043:             if ($allowed) {
                   3044:                 $home=&homeserver($cnum,$cdom);
                   3045:                 if ($env{'form.forceedit'}) {
                   3046:                     $forceview = 1;
                   3047:                 } else {
                   3048:                     $forceedit = 1;
                   3049:                 }
                   3050:                 $cfile = $resurl;
                   3051:             } else {
                   3052:                 return;
                   3053:             }
                   3054:         } else {
1.1208    raeburn  3055:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3056:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3057:                     return;
                   3058:                 }
                   3059:             } elsif (!$crsedit) {
1.1194    raeburn  3060: #
                   3061: # No edit allowed where CC has switched to student role.
                   3062: #
                   3063:                 return;
                   3064:             }
                   3065:         }
                   3066:     }
                   3067: 
1.1193    raeburn  3068:     if ($file ne '') {
                   3069:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3070:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3071:                 $uploaded = 1;
                   3072:                 $incourse = 1;
1.1193    raeburn  3073:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3074:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3075:                     if ($env{'form.forceedit'}) {
                   3076:                         $forceview = 1;
                   3077:                     } else {
                   3078:                         $forceedit = 1;
                   3079:                     }
1.1194    raeburn  3080:                 }
                   3081:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3082:                 $incourse = 1;
                   3083:                 if ($env{'form.forceedit'}) {
                   3084:                     $forceview = 1;
                   3085:                 } else {
                   3086:                     $forceedit = 1;
                   3087:                 }
                   3088:                 $cfile = $resurl;
                   3089:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3090:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3091:                     $incourse = 1;
                   3092:                     if ($env{'form.forceedit'}) {
                   3093:                         $forceview = 1;
                   3094:                     } else {
                   3095:                         $forceedit = 1;
                   3096:                     }
                   3097:                     $cfile = $resurl;
1.1199    raeburn  3098:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3099:                     $incourse = 1;
                   3100:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3101:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3102:                     $incourse = 1;
1.1199    raeburn  3103:                     if ($env{'form.forceedit'}) {
                   3104:                         $forceview = 1;
                   3105:                     } else {
                   3106:                         $forceedit = 1;
                   3107:                     }
                   3108:                     $cfile = $resurl;
1.1298    raeburn  3109:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3110:                     $incourse = 1;
                   3111:                     if ($env{'form.forceedit'}) {
                   3112:                         $forceview = 1;
                   3113:                     } else {
                   3114:                         $forceedit = 1;
                   3115:                     }
                   3116:                     $cfile = $resurl;
1.1208    raeburn  3117:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3118:                     $incourse = 1;
                   3119:                     if ($env{'form.forceedit'}) {
                   3120:                         $forceview = 1;
                   3121:                     } else {
                   3122:                         $forceedit = 1;
                   3123:                     }
                   3124:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3125:                 }
                   3126:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3127:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3128:                 if (&is_on_map($template)) { 
                   3129:                     $incourse = 1;
                   3130:                     $forceview = 1;
                   3131:                     $cfile = $template;
1.1193    raeburn  3132:                 }
1.1199    raeburn  3133:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3134:                     $incourse = 1;
                   3135:                     if ($env{'form.forceedit'}) {
                   3136:                         $forceview = 1;
                   3137:                     } else {
                   3138:                         $forceedit = 1;
                   3139:                     }
                   3140:                     $cfile = $resurl;
1.1298    raeburn  3141:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3142:                 $incourse = 1;
                   3143:                 if ($env{'form.forceedit'}) {
                   3144:                     $forceview = 1;
                   3145:                 } else {
                   3146:                     $forceedit = 1;
                   3147:                 }
                   3148:                 $cfile = $resurl;
1.1199    raeburn  3149:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3150:                 $incourse = 1;
                   3151:                 $forceview = 1;
                   3152:                 if ($symb) {
                   3153:                     my ($map,$id,$res)=&decode_symb($symb);
                   3154:                     $env{'request.symb'} = $symb;
                   3155:                     $cfile = &clutter($res);
                   3156:                 } else {
                   3157:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3158:                     my $escfile = &unescape($cfile);
                   3159:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3160:                         $cfile = '/adm/wrapper'.$escfile;
                   3161:                     } else {
                   3162:                         $escfile =~ s{^http://}{};
                   3163:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3164:                     }
1.1199    raeburn  3165:                 }
1.1234    raeburn  3166:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3167:                 if ($env{'form.forceedit'}) {
                   3168:                     $forceview = 1;
                   3169:                 } else {
                   3170:                     $forceedit = 1;
                   3171:                 }
                   3172:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3173:             }
                   3174:         }
1.1194    raeburn  3175:         if ($uploaded || $incourse) {
                   3176:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3177:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3178:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3179:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3180:             # Check that the user has permission to edit this resource
                   3181:             my $setpriv = 1;
                   3182:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3183:             if (defined($cfudom)) {
                   3184:                 $home=&homeserver($cfuname,$cfudom);
                   3185:                 $cfile=$file;
                   3186:             }
                   3187:         }
1.1194    raeburn  3188:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3189:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3190:             my @ids=&current_machine_ids();
                   3191:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3192:                 $switchserver=1;
                   3193:             }
                   3194:         }
                   3195:     }
1.1194    raeburn  3196:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3197: }
                   3198: 
                   3199: sub is_course_upload {
                   3200:     my ($file,$cnum,$cdom) = @_;
                   3201:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3202:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3203:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3204:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3205:         return 1;
                   3206:     }
                   3207:     return;
                   3208: }
                   3209: 
1.1194    raeburn  3210: sub in_course {
1.1195    raeburn  3211:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3212:     if ($hideprivileged) {
                   3213:         my $skipuser;
1.1219    raeburn  3214:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3215:         my @possdoms = ($cdom);  
                   3216:         if ($coursehash{'checkforpriv'}) { 
                   3217:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3218:         }
                   3219:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3220:             $skipuser = 1;
                   3221:             if ($coursehash{'nothideprivileged'}) {
                   3222:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3223:                     my $user;
                   3224:                     if ($item =~ /:/) {
                   3225:                         $user = $item;
                   3226:                     } else {
                   3227:                         $user = join(':',split(/[\@]/,$item));
                   3228:                     }
                   3229:                     if ($user eq $uname.':'.$udom) {
                   3230:                         undef($skipuser);
                   3231:                         last;
                   3232:                     }
                   3233:                 }
                   3234:             }
                   3235:             if ($skipuser) {
                   3236:                 return 0;
                   3237:             }
                   3238:         }
                   3239:     }
1.1194    raeburn  3240:     $type ||= 'any';
                   3241:     if (!defined($cdom) || !defined($cnum)) {
                   3242:         my $cid  = $env{'request.course.id'};
                   3243:         $cdom = $env{'course.'.$cid.'.domain'};
                   3244:         $cnum = $env{'course.'.$cid.'.num'};
                   3245:     }
                   3246:     my $typesref;
1.1195    raeburn  3247:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3248:         $typesref = ['active','previous','future'];
                   3249:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3250:         $typesref = [$type];
                   3251:     }
                   3252:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3253:                               $typesref,undef,[$cdom]);
                   3254:     my ($tmp) = keys(%roles);
                   3255:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3256:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3257:     if (@course_roles > 0) {
                   3258:         return 1;
                   3259:     }
                   3260:     return 0;
                   3261: }
                   3262: 
1.478     albertel 3263: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3264: # input: action, courseID, current domain, intended
1.637     raeburn  3265: #        path to file, source of file, instruction to parse file for objects,
                   3266: #        ref to hash for embedded objects,
                   3267: #        ref to hash for codebase of java objects.
1.1095    raeburn  3268: #        reference to scalar to accommodate mime type determined
                   3269: #          from File::MMagic if $parser = parse.
1.637     raeburn  3270: #
1.485     raeburn  3271: # output: url to file (if action was uploaddoc), 
                   3272: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3273: #
1.478     albertel 3274: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3275: # course.
1.477     raeburn  3276: #
1.478     albertel 3277: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3278: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3279: #          course's home server.
1.477     raeburn  3280: #
1.478     albertel 3281: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3282: #          be copied from $source (current location) to 
                   3283: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3284: #         and will then be copied to
                   3285: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3286: #         course's home server.
1.485     raeburn  3287: #
1.481     raeburn  3288: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3289: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3290: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3291: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3292: #         in course's home server.
1.637     raeburn  3293: #
1.477     raeburn  3294: 
                   3295: sub process_coursefile {
1.1095    raeburn  3296:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3297:         $mimetype)=@_;
1.477     raeburn  3298:     my $fetchresult;
1.638     albertel 3299:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3300:     if ($action eq 'propagate') {
1.638     albertel 3301:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3302: 			     $home);
1.481     raeburn  3303:     } else {
1.477     raeburn  3304:         my $fpath = '';
                   3305:         my $fname = $file;
1.478     albertel 3306:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3307:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3308:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3309:         if ($action eq 'copy') {
                   3310:             if ($source eq '') {
                   3311:                 $fetchresult = 'no source file';
                   3312:                 return $fetchresult;
                   3313:             } else {
                   3314:                 my $destination = $filepath.'/'.$fname;
                   3315:                 rename($source,$destination);
                   3316:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3317:                                  $home);
1.481     raeburn  3318:             }
                   3319:         } elsif ($action eq 'uploaddoc') {
                   3320:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3321:             print $fh $env{'form.'.$source};
1.481     raeburn  3322:             close($fh);
1.637     raeburn  3323:             if ($parser eq 'parse') {
1.1024    raeburn  3324:                 my $mm = new File::MMagic;
1.1095    raeburn  3325:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3326:                 if ($type eq 'text/html') {
1.1024    raeburn  3327:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3328:                     unless ($parse_result eq 'ok') {
                   3329:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3330:                     }
1.637     raeburn  3331:                 }
1.1095    raeburn  3332:                 if (ref($mimetype)) {
                   3333:                     $$mimetype = $type;
                   3334:                 } 
1.637     raeburn  3335:             }
1.477     raeburn  3336:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3337:                                  $home);
1.481     raeburn  3338:             if ($fetchresult eq 'ok') {
                   3339:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3340:             } else {
                   3341:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3342:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3343:                 return '/adm/notfound.html';
                   3344:             }
1.477     raeburn  3345:         }
                   3346:     }
1.485     raeburn  3347:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3348:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3349:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3350:     }
                   3351:     return $fetchresult;
                   3352: }
                   3353: 
1.637     raeburn  3354: sub build_filepath {
                   3355:     my ($fpath) = @_;
                   3356:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3357:     unless ($fpath eq '') {
                   3358:         my @parts=split('/',$fpath);
                   3359:         foreach my $part (@parts) {
                   3360:             $filepath.= '/'.$part;
                   3361:             if ((-e $filepath)!=1) {
                   3362:                 mkdir($filepath,0777);
                   3363:             }
                   3364:         }
                   3365:     }
                   3366:     return $filepath;
                   3367: }
                   3368: 
                   3369: sub store_edited_file {
1.638     albertel 3370:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3371:     my $file = $primary_url;
                   3372:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3373:     my $fpath = '';
                   3374:     my $fname = $file;
                   3375:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3376:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3377:     my $filepath = &build_filepath($fpath);
                   3378:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3379:     print $fh $content;
                   3380:     close($fh);
1.638     albertel 3381:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3382:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3383: 			  $home);
1.637     raeburn  3384:     if ($$fetchresult eq 'ok') {
                   3385:         return '/uploaded/'.$fpath.'/'.$fname;
                   3386:     } else {
1.638     albertel 3387:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3388: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3389:         return '/adm/notfound.html';
                   3390:     }
                   3391: }
                   3392: 
1.531     albertel 3393: sub clean_filename {
1.831     albertel 3394:     my ($fname,$args)=@_;
1.315     www      3395: # Replace Windows backslashes by forward slashes
1.257     www      3396:     $fname=~s/\\/\//g;
1.831     albertel 3397:     if (!$args->{'keep_path'}) {
                   3398:         # Get rid of everything but the actual filename
                   3399: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3400:     }
1.315     www      3401: # Replace spaces by underscores
                   3402:     $fname=~s/\s+/\_/g;
                   3403: # Replace all other weird characters by nothing
1.831     albertel 3404:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3405: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3406: # numbers
                   3407:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3408:     return $fname;
                   3409: }
1.1051    raeburn  3410: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3411: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3412: # image with the same aspect ratio as the original, but with dimensions which do 
                   3413: # not exceed $resizewidth and $resizeheight.
                   3414:  
1.984     neumanie 3415: sub resizeImage {
1.1051    raeburn  3416:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3417:     my $ima = Image::Magick->new;
                   3418:     my $resized;
                   3419:     if (-e $img_path) {
                   3420:         $ima->Read($img_path);
                   3421:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3422:             my $width = $ima->Get('width');
                   3423:             my $height = $ima->Get('height');
                   3424:             if ($width > $resizewidth) {
                   3425: 	        my $factor = $width/$resizewidth;
                   3426:                 my $newheight = $height/$factor;
                   3427:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3428:                 $resized = 1;
                   3429:             }
                   3430:         }
                   3431:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3432:             my $width = $ima->Get('width');
                   3433:             my $height = $ima->Get('height');
                   3434:             if ($height > $resizeheight) {
                   3435:                 my $factor = $height/$resizeheight;
                   3436:                 my $newwidth = $width/$factor;
                   3437:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3438:                 $resized = 1;
                   3439:             }
                   3440:         }
                   3441:         if ($resized) {
                   3442:             $ima->Write($img_path);
                   3443:         }
                   3444:     }
                   3445:     return;
1.977     amueller 3446: }
                   3447: 
1.608     albertel 3448: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3449: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3450: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3451: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3452: #                                    canceloverwrite, or ''. 
                   3453: #                   if 'coursedoc': upload to the current course
                   3454: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3455: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3456: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3457: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3458: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3459: #        $allfiles - reference to hash for embedded objects
                   3460: #        $codebase - reference to hash for codebase of java objects
                   3461: #        $desuname - username for permanent storage of uploaded file
                   3462: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3463: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3464: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3465: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3466: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3467: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3468: #                    from File::MMagic.
1.858     raeburn  3469: # 
1.686     albertel 3470: # output: url of file in userspace, or error: <message> 
                   3471: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3472: 
1.531     albertel 3473: sub userfileupload {
1.1090    raeburn  3474:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3475:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3476:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3477:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3478:     $fname=&clean_filename($fname);
1.1090    raeburn  3479:     # See if there is anything left
1.257     www      3480:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3481:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3482:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3483:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3484:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3485:         my $now = time;
1.1090    raeburn  3486:         my $filepath;
1.1095    raeburn  3487:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3488:              $filepath = 'tmp/helprequests/'.$now;
                   3489:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3490:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3491:                          '_'.$env{'user.domain'}.'/pending';
                   3492:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3493:             my ($docuname,$docudom);
                   3494:             if ($destudom) {
                   3495:                 $docudom = $destudom;
                   3496:             } else {
                   3497:                 $docudom = $env{'user.domain'};
                   3498:             }
                   3499:             if ($destuname) {
                   3500:                 $docuname = $destuname;
                   3501:             } else {
                   3502:                 $docuname = $env{'user.name'};
                   3503:             }
                   3504:             if (exists($env{'form.group'})) {
                   3505:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3506:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3507:             }
                   3508:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3509:             if ($context eq 'canceloverwrite') {
                   3510:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3511:                 if (-e  $tempfile) {
                   3512:                     my @info = stat($tempfile);
                   3513:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3514:                         unlink($tempfile);
                   3515:                     }
                   3516:                 }
                   3517:                 return;
1.523     raeburn  3518:             }
                   3519:         }
1.1090    raeburn  3520:         # Create the directory if not present
1.741     raeburn  3521:         my @parts=split(/\//,$filepath);
                   3522:         my $fullpath = $perlvar{'lonDaemons'};
                   3523:         for (my $i=0;$i<@parts;$i++) {
                   3524:             $fullpath .= '/'.$parts[$i];
                   3525:             if ((-e $fullpath)!=1) {
                   3526:                 mkdir($fullpath,0777);
                   3527:             }
                   3528:         }
                   3529:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3530:         print $fh $env{'form.'.$formname};
                   3531:         close($fh);
1.1090    raeburn  3532:         if ($context eq 'existingfile') {
                   3533:             my @info = stat($fullpath.'/'.$fname);
                   3534:             return ($fullpath.'/'.$fname,$info[9]);
                   3535:         } else {
                   3536:             return $fullpath.'/'.$fname;
                   3537:         }
1.523     raeburn  3538:     }
1.995     raeburn  3539:     if ($subdir eq 'scantron') {
                   3540:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3541:     } else {
1.995     raeburn  3542:         $fname="$subdir/$fname";
                   3543:     }
1.1090    raeburn  3544:     if ($context eq 'coursedoc') {
1.638     albertel 3545: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3546: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3547:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3548:             return &finishuserfileupload($docuname,$docudom,
                   3549: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3550: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3551:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3552:         } else {
1.1218    raeburn  3553:             if ($env{'form.folder'}) {
                   3554:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3555:             }
1.638     albertel 3556:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3557: 				       $fname,$formname,$parser,
1.1095    raeburn  3558: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3559:         }
1.719     banghart 3560:     } elsif (defined($destuname)) {
                   3561:         my $docuname=$destuname;
                   3562:         my $docudom=$destudom;
1.860     raeburn  3563: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3564: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3565:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3566:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3567:     } else {
1.638     albertel 3568:         my $docuname=$env{'user.name'};
                   3569:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3570:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3571:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3572:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3573:         }
1.860     raeburn  3574: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3575: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3576:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3577:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3578:     }
1.271     www      3579: }
                   3580: 
                   3581: sub finishuserfileupload {
1.860     raeburn  3582:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3583:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3584:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3585:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3586:   
1.860     raeburn  3587:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3588:     $file=$fname;
                   3589:     if ($fname=~m|/|) {
                   3590:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3591: 	$path.=$fnamepath.'/';
                   3592:     }
1.259     www      3593:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3594:     my $count;
                   3595:     for ($count=4;$count<=$#parts;$count++) {
                   3596:         $filepath.="/$parts[$count]";
                   3597:         if ((-e $filepath)!=1) {
                   3598: 	    mkdir($filepath,0777);
                   3599:         }
                   3600:     }
1.984     neumanie 3601: 
1.258     www      3602: # Save the file
                   3603:     {
1.701     albertel 3604: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3605: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3606: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3607: 	    return '/adm/notfound.html';
                   3608: 	}
1.1090    raeburn  3609:         if ($context eq 'overwrite') {
1.1117    foxr     3610:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3611:             my $target = $filepath.'/'.$file;
                   3612:             if (-e $source) {
                   3613:                 my @info = stat($source);
                   3614:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3615:                     unless (&File::Copy::move($source,$target)) {
                   3616:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3617:                         return "Moving from $source failed";
                   3618:                     }
                   3619:                 } else {
                   3620:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3621:                 }
                   3622:             } else {
                   3623:                 return "Temporary file: $source missing";
                   3624:             }
                   3625:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3626: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3627: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3628: 	    return '/adm/notfound.html';
                   3629: 	}
1.570     albertel 3630: 	close(FH);
1.1051    raeburn  3631:         if ($resizewidth && $resizeheight) {
                   3632:             my $mm = new File::MMagic;
                   3633:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3634:             if ($mime_type =~ m{^image/}) {
                   3635: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3636:             }  
1.977     amueller 3637: 	}
1.258     www      3638:     }
1.1152    raeburn  3639:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3640:         if (ref($mimetype)) {
                   3641:             if ($$mimetype eq '') {
                   3642:                 my $mm = new File::MMagic;
                   3643:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3644:                 $$mimetype = $type;
                   3645:             }
                   3646:         }
                   3647:     }
1.637     raeburn  3648:     if ($parser eq 'parse') {
1.1152    raeburn  3649:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3650:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3651:                                                        $allfiles,$codebase);
                   3652:             unless ($parse_result eq 'ok') {
                   3653:                 &logthis('Failed to parse '.$filepath.$file.
                   3654: 	   	         ' for embedded media: '.$parse_result); 
                   3655:             }
1.637     raeburn  3656:         }
                   3657:     }
1.860     raeburn  3658:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3659:         my $input = $filepath.'/'.$file;
                   3660:         my $output = $filepath.'/'.'tn-'.$file;
                   3661:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3662:         system("convert -sample $thumbsize $input $output");
                   3663:         if (-e $filepath.'/'.'tn-'.$file) {
                   3664:             $fetchthumb  = 1; 
                   3665:         }
                   3666:     }
1.858     raeburn  3667:  
1.259     www      3668: # Notify homeserver to grep it
                   3669: #
1.984     neumanie 3670:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3671:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3672:     if ($fetchresult eq 'ok') {
1.860     raeburn  3673:         if ($fetchthumb) {
                   3674:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3675:             if ($thumbresult ne 'ok') {
                   3676:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3677:                          $docuhome.': '.$thumbresult);
                   3678:             }
                   3679:         }
1.259     www      3680: #
1.258     www      3681: # Return the URL to it
1.494     albertel 3682:         return '/uploaded/'.$path.$file;
1.263     www      3683:     } else {
1.494     albertel 3684:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3685: 		 ': '.$fetchresult);
1.263     www      3686:         return '/adm/notfound.html';
1.858     raeburn  3687:     }
1.493     albertel 3688: }
                   3689: 
1.637     raeburn  3690: sub extract_embedded_items {
1.961     raeburn  3691:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3692:     my @state = ();
1.1164    raeburn  3693:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3694:     my %javafiles = (
                   3695:                       codebase => '',
                   3696:                       code => '',
                   3697:                       archive => ''
                   3698:                     );
                   3699:     my %mediafiles = (
                   3700:                       src => '',
                   3701:                       movie => '',
                   3702:                      );
1.648     raeburn  3703:     my $p;
                   3704:     if ($content) {
                   3705:         $p = HTML::LCParser->new($content);
                   3706:     } else {
1.961     raeburn  3707:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3708:     }
1.641     albertel 3709:     while (my $t=$p->get_token()) {
1.640     albertel 3710: 	if ($t->[0] eq 'S') {
                   3711: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3712: 	    push(@state, $tagname);
1.648     raeburn  3713:             if (lc($tagname) eq 'allow') {
                   3714:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3715:             }
1.640     albertel 3716: 	    if (lc($tagname) eq 'img') {
                   3717: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3718: 	    }
1.886     albertel 3719: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3720:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3721:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3722:                 }
1.886     albertel 3723: 	    }
1.645     raeburn  3724:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3725:                 my $src;
1.645     raeburn  3726:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3727:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3728:                 } else {
1.1164    raeburn  3729:                     if ($attr->{'src'} ne '') {
                   3730:                         $src = $attr->{'src'};
                   3731:                         &add_filetype($allfiles,$src,'src');
                   3732:                     }
                   3733:                 }
                   3734:                 my $text = $p->get_trimmed_text();
                   3735:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3736:                     my @swfargs = split(/,/,$1);
                   3737:                     foreach my $item (@swfargs) {
                   3738:                         $item =~ s/["']//g;
                   3739:                         $item =~ s/^\s+//;
                   3740:                         $item =~ s/\s+$//;
                   3741:                     }
                   3742:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3743:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3744:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3745:                         } else {
                   3746:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3747:                         }
                   3748:                     }
1.645     raeburn  3749:                 }
                   3750:             }
                   3751:             if (lc($tagname) eq 'link') {
                   3752:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3753:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3754:                 }
                   3755:             }
1.640     albertel 3756: 	    if (lc($tagname) eq 'object' ||
                   3757: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3758: 		foreach my $item (keys(%javafiles)) {
                   3759: 		    $javafiles{$item} = '';
                   3760: 		}
1.1164    raeburn  3761:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3762:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3763:                 }
1.640     albertel 3764: 	    }
                   3765: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3766: 		my $name = lc($attr->{'name'});
                   3767: 		foreach my $item (keys(%javafiles)) {
                   3768: 		    if ($name eq $item) {
                   3769: 			$javafiles{$item} = $attr->{'value'};
                   3770: 			last;
                   3771: 		    }
                   3772: 		}
1.1164    raeburn  3773:                 my $pathfrom;
1.640     albertel 3774: 		foreach my $item (keys(%mediafiles)) {
                   3775: 		    if ($name eq $item) {
1.1164    raeburn  3776:                         $pathfrom = $attr->{'value'};
                   3777:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3778: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3779: 			last;
                   3780: 		    }
                   3781: 		}
1.1164    raeburn  3782:                 if ($name eq 'flashvars') {
                   3783:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3784:                 }
                   3785:                 if ($pathfrom ne '') {
                   3786:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3787:                                          $pathfrom);
                   3788:                 }
1.640     albertel 3789: 	    }
                   3790: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3791: 		foreach my $item (keys(%javafiles)) {
                   3792: 		    if ($attr->{$item}) {
                   3793: 			$javafiles{$item} = $attr->{$item};
                   3794: 			last;
                   3795: 		    }
                   3796: 		}
                   3797: 		foreach my $item (keys(%mediafiles)) {
                   3798: 		    if ($attr->{$item}) {
                   3799: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3800: 			last;
                   3801: 		    }
                   3802: 		}
1.1164    raeburn  3803:                 if (lc($tagname) eq 'embed') {
                   3804:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3805:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3806:                                              $attr->{'src'});
                   3807:                     }
                   3808:                 }
1.640     albertel 3809: 	    }
1.1243    raeburn  3810:             if (lc($tagname) eq 'iframe') {
                   3811:                 my $src = $attr->{'src'} ;
                   3812:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3813:                     &add_filetype($allfiles,$src,'src');
                   3814:                 } elsif ($src =~ m{^/}) {
                   3815:                     if ($env{'request.course.id'}) {
                   3816:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3817:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3818:                         my $url = &hreflocation('',$fullpath);
                   3819:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3820:                             my $relpath = $1;
                   3821:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3822:                                 &add_filetype($allfiles,$1,'src');
                   3823:                             }
                   3824:                         }
                   3825:                     }
                   3826:                 }
                   3827:             }
1.1164    raeburn  3828:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3829:                 pop(@state);
1.1164    raeburn  3830:             }
1.640     albertel 3831: 	} elsif ($t->[0] eq 'E') {
                   3832: 	    my ($tagname) = ($t->[1]);
                   3833: 	    if ($javafiles{'codebase'} ne '') {
                   3834: 		$javafiles{'codebase'} .= '/';
                   3835: 	    }  
                   3836: 	    if (lc($tagname) eq 'applet' ||
                   3837: 		lc($tagname) eq 'object' ||
                   3838: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3839: 		) {
                   3840: 		foreach my $item (keys(%javafiles)) {
                   3841: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3842: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3843: 			&add_filetype($allfiles,$file,$item);
                   3844: 		    }
                   3845: 		}
                   3846: 	    } 
                   3847: 	    pop @state;
                   3848: 	}
                   3849:     }
1.1164    raeburn  3850:     foreach my $id (sort(keys(%flashvars))) {
                   3851:         if ($shockwave{$id} ne '') {
                   3852:             my @pairs = split(/\&/,$flashvars{$id});
                   3853:             foreach my $pair (@pairs) {
                   3854:                 my ($key,$value) = split(/\=/,$pair);
                   3855:                 if ($key eq 'thumb') {
                   3856:                     &add_filetype($allfiles,$value,$key);
                   3857:                 } elsif ($key eq 'content') {
                   3858:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3859:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3860:                     if ($ext ne '') {
                   3861:                         &add_filetype($allfiles,$path.$value,$ext);
                   3862:                     }
                   3863:                 }
                   3864:             }
                   3865:         }
                   3866:     }
1.637     raeburn  3867:     return 'ok';
                   3868: }
                   3869: 
1.639     albertel 3870: sub add_filetype {
                   3871:     my ($allfiles,$file,$type)=@_;
                   3872:     if (exists($allfiles->{$file})) {
                   3873: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3874: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3875: 	}
                   3876:     } else {
                   3877: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3878:     }
                   3879: }
                   3880: 
1.1164    raeburn  3881: sub embedded_dependency {
                   3882:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3883:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3884:         if (($identifier ne '') &&
                   3885:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3886:             ($pathfrom ne '')) {
                   3887:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3888:             foreach my $dep (@{$related->{$identifier}}) {
                   3889:                 &add_filetype($allfiles,$path.$dep,'object');
                   3890:             }
                   3891:         }
                   3892:     }
                   3893:     return;
                   3894: }
                   3895: 
1.493     albertel 3896: sub removeuploadedurl {
1.984     neumanie 3897:     my ($url)=@_;	
                   3898:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3899:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3900: }
                   3901: 
                   3902: sub removeuserfile {
                   3903:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3904:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3905:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3906:     if ($result eq 'ok') {	
1.798     raeburn  3907:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3908:             my $metafile = $fname.'.meta';
                   3909:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3910: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3911:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3912:             my $sqlresult = 
1.823     albertel 3913:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3914:                                         'portfolio_metadata',$group,
                   3915:                                         'delete');
1.798     raeburn  3916:         }
                   3917:     }
                   3918:     return $result;
1.257     www      3919: }
1.15      www      3920: 
1.530     albertel 3921: sub mkdiruserfile {
                   3922:     my ($docuname,$docudom,$dir)=@_;
                   3923:     my $home=&homeserver($docuname,$docudom);
                   3924:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3925: }
                   3926: 
1.531     albertel 3927: sub renameuserfile {
                   3928:     my ($docuname,$docudom,$old,$new)=@_;
                   3929:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3930:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3931:                         &escape("$old").':'.&escape("$new"),$home);
                   3932:     if ($result eq 'ok') {
                   3933:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3934:             my $oldmeta = $old.'.meta';
                   3935:             my $newmeta = $new.'.meta';
                   3936:             my $metaresult = 
                   3937:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3938: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3939:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3940:             my $sqlresult = 
1.823     albertel 3941:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3942:                                         'portfolio_metadata',$group,
                   3943:                                         'delete');
1.798     raeburn  3944:         }
                   3945:     }
                   3946:     return $result;
1.531     albertel 3947: }
                   3948: 
1.14      www      3949: # ------------------------------------------------------------------------- Log
                   3950: 
                   3951: sub log {
                   3952:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3953:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3954: }
                   3955: 
                   3956: # ------------------------------------------------------------------ Course Log
1.352     www      3957: #
                   3958: # This routine flushes several buffers of non-mission-critical nature
                   3959: #
1.157     www      3960: 
                   3961: sub flushcourselogs {
1.352     www      3962:     &logthis('Flushing log buffers');
                   3963: #
                   3964: # course logs
                   3965: # This is a log of all transactions in a course, which can be used
                   3966: # for data mining purposes
                   3967: #
                   3968: # It also collects the courseid database, which lists last transaction
                   3969: # times and course titles for all courseids
                   3970: #
                   3971:     my %courseidbuffer=();
1.921     raeburn  3972:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3973:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3974: 		          &escape($courselogs{$crsid}),
                   3975: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3976: 	    delete $courselogs{$crsid};
                   3977:         } else {
                   3978:             &logthis('Failed to flush log buffer for '.$crsid);
                   3979:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3980:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3981:                         " exceeded maximum size, deleting.</font>");
                   3982:                delete $courselogs{$crsid};
                   3983:             }
1.352     www      3984:         }
1.920     raeburn  3985:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3986:             'description' => $coursedescrbuf{$crsid},
                   3987:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3988:             'type'        => $coursetypebuf{$crsid},
                   3989:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3990:         };
1.191     harris41 3991:     }
1.352     www      3992: #
                   3993: # Write course id database (reverse lookup) to homeserver of courses 
                   3994: # Is used in pickcourse
                   3995: #
1.840     albertel 3996:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3997:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3998:                                     $courseidbuffer{$crs_home},
                   3999:                                     $crs_home,'timeonly');
1.352     www      4000:     }
                   4001: #
                   4002: # File accesses
                   4003: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4004: #
1.449     matthew  4005:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4006:         if ($entry =~ /___count$/) {
                   4007:             my ($dom,$name);
1.807     albertel 4008:             ($dom,$name,undef)=
1.811     albertel 4009: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4010:             if (! defined($dom) || $dom eq '' || 
                   4011:                 ! defined($name) || $name eq '') {
1.620     albertel 4012:                 my $cid = $env{'request.course.id'};
                   4013:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4014:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4015:             }
1.450     matthew  4016:             my $value = $accesshash{$entry};
                   4017:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4018:             my %temphash=($url => $value);
1.449     matthew  4019:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4020:             if ($result eq 'ok') {
                   4021:                 delete $accesshash{$entry};
                   4022:             }
                   4023:         } else {
1.811     albertel 4024:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4025:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4026:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4027:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4028:                 delete $accesshash{$entry};
                   4029:             }
1.185     www      4030:         }
1.191     harris41 4031:     }
1.352     www      4032: #
                   4033: # Roles
                   4034: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4035: #
1.800     albertel 4036:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4037:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4038: 	    split(/\:/,$entry);
                   4039:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4040:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4041:                 $rudom,$runame) eq 'ok') {
                   4042: 	    delete $userrolehash{$entry};
                   4043:         }
                   4044:     }
1.662     raeburn  4045: #
                   4046: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   4047: #
                   4048:     my %domrolebuffer = ();
1.1000    raeburn  4049:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4050:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4051:         if ($domrolebuffer{$rudom}) {
                   4052:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4053:                       '='.&escape($domainrolehash{$entry});
                   4054:         } else {
                   4055:             $domrolebuffer{$rudom}.=&escape($entry).
                   4056:                       '='.&escape($domainrolehash{$entry});
                   4057:         }
                   4058:         delete $domainrolehash{$entry};
                   4059:     }
                   4060:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 4061: 	my %servers = &get_servers($dom,'library');
                   4062: 	foreach my $tryserver (keys(%servers)) {
                   4063: 	    unless (&reply('domroleput:'.$dom.':'.
                   4064: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4065: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4066: 	    }
1.662     raeburn  4067:         }
                   4068:     }
1.186     www      4069:     $dumpcount++;
1.157     www      4070: }
                   4071: 
                   4072: sub courselog {
                   4073:     my $what=shift;
1.158     www      4074:     $what=time.':'.$what;
1.620     albertel 4075:     unless ($env{'request.course.id'}) { return ''; }
                   4076:     $coursedombuf{$env{'request.course.id'}}=
                   4077:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4078:     $coursenumbuf{$env{'request.course.id'}}=
                   4079:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4080:     $coursehombuf{$env{'request.course.id'}}=
                   4081:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4082:     $coursedescrbuf{$env{'request.course.id'}}=
                   4083:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4084:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4085:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4086:     $courseownerbuf{$env{'request.course.id'}}=
                   4087:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4088:     $coursetypebuf{$env{'request.course.id'}}=
                   4089:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4090:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4091: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4092:     } else {
1.620     albertel 4093: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4094:     }
1.620     albertel 4095:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4096: 	&flushcourselogs();
                   4097:     }
1.158     www      4098: }
                   4099: 
                   4100: sub courseacclog {
                   4101:     my $fnsymb=shift;
1.620     albertel 4102:     unless ($env{'request.course.id'}) { return ''; }
                   4103:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4104:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4105:         $what.=':POST';
1.583     matthew  4106:         # FIXME: Probably ought to escape things....
1.800     albertel 4107: 	foreach my $key (keys(%env)) {
                   4108:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4109:                 my $formitem = $1;
                   4110:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4111:                     $what.=':'.$formitem.'='.$env{$key};
                   4112:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4113:                     $what.=':'.$formitem.'='.$env{$key};
                   4114:                 }
1.158     www      4115:             }
1.191     harris41 4116:         }
1.583     matthew  4117:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4118:         # FIXME: We should not be depending on a form parameter that someone
                   4119:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4120:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4121:             $what.= ':POST';
                   4122:             # FIXME: Probably ought to escape things....
                   4123:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4124:                                  'crsdiscuss') {
1.620     albertel 4125:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4126:             }
                   4127:         }
1.158     www      4128:     }
                   4129:     &courselog($what);
1.149     www      4130: }
                   4131: 
1.185     www      4132: sub countacc {
                   4133:     my $url=&declutter(shift);
1.458     matthew  4134:     return if (! defined($url) || $url eq '');
1.620     albertel 4135:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4136: #
                   4137: # Mark that this url was used in this course
                   4138: #
1.620     albertel 4139:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4140: #
                   4141: # Increase the access count for this resource in this child process
                   4142: #
1.281     www      4143:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4144:     $accesshash{$key}++;
1.185     www      4145: }
1.349     www      4146: 
1.361     www      4147: sub linklog {
                   4148:     my ($from,$to)=@_;
                   4149:     $from=&declutter($from);
                   4150:     $to=&declutter($to);
                   4151:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4152:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4153: }
1.1160    www      4154: 
                   4155: sub statslog {
                   4156:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4157:     if ($users<2) { return; }
                   4158:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4159:             'course'       => $env{'request.course.id'},
                   4160:             'sections'     => '"all"',
                   4161:             'num_students' => $users,
                   4162:             'part'         => $part,
                   4163:             'symb'         => $symb,
                   4164:             'mean_tries'   => $av_attempts,
                   4165:             'deg_of_diff'  => $degdiff});
                   4166:     foreach my $key (keys(%dynstore)) {
                   4167:         $accesshash{$key}=$dynstore{$key};
                   4168:     }
                   4169: }
1.361     www      4170:   
1.349     www      4171: sub userrolelog {
                   4172:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4173:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4174:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4175:        $userrolehash
                   4176:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4177:                     =$tend.':'.$tstart;
1.662     raeburn  4178:     }
1.1169    droeschl 4179:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4180:        $userrolehash
                   4181:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4182:                     =$tend.':'.$tstart;
                   4183:     }
1.1169    droeschl 4184:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  4185:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4186:        $domainrolehash
                   4187:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4188:                     = $tend.':'.$tstart;
                   4189:     }
1.351     www      4190: }
                   4191: 
1.957     raeburn  4192: sub courserolelog {
                   4193:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4194:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4195:         my $cdom = $1;
                   4196:         my $cnum = $2;
                   4197:         my $sec = $3;
                   4198:         my $namespace = 'rolelog';
                   4199:         my %storehash = (
                   4200:                            role    => $trole,
                   4201:                            start   => $tstart,
                   4202:                            end     => $tend,
                   4203:                            selfenroll => $selfenroll,
                   4204:                            context    => $context,
                   4205:                         );
                   4206:         if ($trole eq 'gr') {
                   4207:             $namespace = 'groupslog';
                   4208:             $storehash{'group'} = $sec;
                   4209:         } else {
                   4210:             $storehash{'section'} = $sec;
                   4211:         }
1.1188    raeburn  4212:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4213:                    $domain,$cnum,$cdom);
1.1184    raeburn  4214:         if (($trole ne 'st') || ($sec ne '')) {
                   4215:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4216:         }
                   4217:     }
                   4218:     return;
                   4219: }
                   4220: 
1.1184    raeburn  4221: sub domainrolelog {
                   4222:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4223:     if ($area =~ m{^/($match_domain)/$}) {
                   4224:         my $cdom = $1;
                   4225:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4226:         my $namespace = 'rolelog';
                   4227:         my %storehash = (
                   4228:                            role    => $trole,
                   4229:                            start   => $tstart,
                   4230:                            end     => $tend,
                   4231:                            context => $context,
                   4232:                         );
1.1188    raeburn  4233:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4234:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4235:     }
                   4236:     return;
                   4237: 
                   4238: }
                   4239: 
                   4240: sub coauthorrolelog {
                   4241:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4242:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4243:         my $audom = $1;
                   4244:         my $auname = $2;
                   4245:         my $namespace = 'rolelog';
                   4246:         my %storehash = (
                   4247:                            role    => $trole,
                   4248:                            start   => $tstart,
                   4249:                            end     => $tend,
                   4250:                            context => $context,
                   4251:                         );
1.1188    raeburn  4252:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4253:                    $domain,$auname,$audom);
1.1184    raeburn  4254:     }
                   4255:     return;
                   4256: }
                   4257: 
1.351     www      4258: sub get_course_adv_roles {
1.948     raeburn  4259:     my ($cid,$codes) = @_;
1.620     albertel 4260:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4261:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4262:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4263:     my %nothide=();
1.800     albertel 4264:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4265:         if ($user !~ /:/) {
                   4266: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4267:         } else {
                   4268:             $nothide{$user}=1;
                   4269:         }
1.470     www      4270:     }
1.1219    raeburn  4271:     my @possdoms = ($coursehash{'domain'});
                   4272:     if ($coursehash{'checkforpriv'}) {
                   4273:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4274:     }
1.351     www      4275:     my %returnhash=();
                   4276:     my %dumphash=
                   4277:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4278:     my $now=time;
1.997     raeburn  4279:     my %privileged;
1.1000    raeburn  4280:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4281: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4282:         if (($tstart) && ($tstart<0)) { next; }
                   4283:         if (($tend) && ($tend<$now)) { next; }
                   4284:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4285:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4286: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4287:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4288:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4289: 	if ($role eq 'cr') { next; }
1.948     raeburn  4290:         if ($codes) {
                   4291:             if ($section) { $role .= ':'.$section; }
                   4292:             if ($returnhash{$role}) {
                   4293:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4294:             } else {
                   4295:                 $returnhash{$role}=$username.':'.$domain;
                   4296:             }
1.351     www      4297:         } else {
1.988     raeburn  4298:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4299:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4300:             if ($returnhash{$key}) {
                   4301: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4302:             } else {
                   4303:                 $returnhash{$key}=$username.':'.$domain;
                   4304:             }
1.351     www      4305:         }
1.948     raeburn  4306:     }
1.400     www      4307:     return %returnhash;
                   4308: }
                   4309: 
                   4310: sub get_my_roles {
1.937     raeburn  4311:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4312:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4313:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4314:     my (%dumphash,%nothide);
1.1086    raeburn  4315:     if ($context eq 'userroles') {
1.1166    raeburn  4316:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4317:     } else {
1.1219    raeburn  4318:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4319:         if ($hidepriv) {
                   4320:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4321:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4322:                 if ($user !~ /:/) {
                   4323:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4324:                 } else {
                   4325:                     $nothide{$user} = 1;
                   4326:                 }
                   4327:             }
                   4328:         }
1.858     raeburn  4329:     }
1.400     www      4330:     my %returnhash=();
                   4331:     my $now=time;
1.999     raeburn  4332:     my %privileged;
1.800     albertel 4333:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4334:         my ($role,$tend,$tstart);
                   4335:         if ($context eq 'userroles') {
1.1149    raeburn  4336:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4337: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4338:         } else {
                   4339:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4340:         }
1.400     www      4341:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4342:         my $status = 'active';
1.939     raeburn  4343:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4344:             $status = 'previous';
                   4345:         } 
                   4346:         if (($tstart) && ($now<$tstart)) {
                   4347:             $status = 'future';
                   4348:         }
                   4349:         if (ref($types) eq 'ARRAY') {
                   4350:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4351:                 next;
                   4352:             } 
                   4353:         } else {
                   4354:             if ($status ne 'active') {
                   4355:                 next;
                   4356:             }
                   4357:         }
1.867     raeburn  4358:         my ($rolecode,$username,$domain,$section,$area);
                   4359:         if ($context eq 'userroles') {
1.1186    raeburn  4360:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4361:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4362:         } else {
                   4363:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4364:         }
1.832     raeburn  4365:         if (ref($roledoms) eq 'ARRAY') {
                   4366:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4367:                 next;
                   4368:             }
                   4369:         }
                   4370:         if (ref($roles) eq 'ARRAY') {
                   4371:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4372:                 if ($role =~ /^cr\//) {
                   4373:                     if (!grep(/^cr$/,@{$roles})) {
                   4374:                         next;
                   4375:                     }
1.1104    raeburn  4376:                 } elsif ($role =~ /^gr\//) {
                   4377:                     if (!grep(/^gr$/,@{$roles})) {
                   4378:                         next;
                   4379:                     }
1.922     raeburn  4380:                 } else {
                   4381:                     next;
                   4382:                 }
1.832     raeburn  4383:             }
1.867     raeburn  4384:         }
1.937     raeburn  4385:         if ($hidepriv) {
1.1219    raeburn  4386:             my @privroles = ('dc','su');
1.999     raeburn  4387:             if ($context eq 'userroles') {
1.1219    raeburn  4388:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4389:             } else {
1.1219    raeburn  4390:                 my $possdoms = [$domain];
                   4391:                 if (ref($roledoms) eq 'ARRAY') {
                   4392:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4393:                 }
1.1219    raeburn  4394:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4395:                     if (!$nothide{$username.':'.$domain}) {
                   4396:                         next;
                   4397:                     }
                   4398:                 }
1.937     raeburn  4399:             }
                   4400:         }
1.933     raeburn  4401:         if ($withsec) {
                   4402:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4403:                 $tstart.':'.$tend;
                   4404:         } else {
                   4405:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4406:         }
1.832     raeburn  4407:     }
1.373     www      4408:     return %returnhash;
1.399     www      4409: }
                   4410: 
                   4411: # ----------------------------------------------------- Frontpage Announcements
                   4412: #
                   4413: #
                   4414: 
                   4415: sub postannounce {
                   4416:     my ($server,$text)=@_;
1.844     albertel 4417:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4418:     unless ($text=~/\w/) { $text=''; }
                   4419:     return &reply('setannounce:'.&escape($text),$server);
                   4420: }
                   4421: 
                   4422: sub getannounce {
1.448     albertel 4423: 
                   4424:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4425: 	my $announcement='';
1.800     albertel 4426: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4427: 	close($fh);
1.399     www      4428: 	if ($announcement=~/\w/) { 
                   4429: 	    return 
                   4430:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4431:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4432: 	} else {
                   4433: 	    return '';
                   4434: 	}
                   4435:     } else {
                   4436: 	return '';
                   4437:     }
1.351     www      4438: }
1.353     www      4439: 
                   4440: # ---------------------------------------------------------- Course ID routines
                   4441: # Deal with domain's nohist_courseid.db files
                   4442: #
                   4443: 
                   4444: sub courseidput {
1.921     raeburn  4445:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4446:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4447:     my $outcome;
                   4448:     if ($caller eq 'timeonly') {
                   4449:         my $cids = '';
                   4450:         foreach my $item (keys(%$storehash)) {
                   4451:             $cids.=&escape($item).'&';
                   4452:         }
                   4453:         $cids=~s/\&$//;
                   4454:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4455:                           $coursehome);       
                   4456:     } else {
                   4457:         my $items = '';
                   4458:         foreach my $item (keys(%$storehash)) {
                   4459:             $items.= &escape($item).'='.
                   4460:                      &freeze_escape($$storehash{$item}).'&';
                   4461:         }
                   4462:         $items=~s/\&$//;
                   4463:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4464:                           $coursehome);
1.918     raeburn  4465:     }
                   4466:     if ($outcome eq 'unknown_cmd') {
                   4467:         my $what;
                   4468:         foreach my $cid (keys(%$storehash)) {
                   4469:             $what .= &escape($cid).'=';
1.921     raeburn  4470:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4471:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4472:             }
                   4473:             $what =~ s/\:$/&/;
                   4474:         }
                   4475:         $what =~ s/\&$//;  
                   4476:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4477:     } else {
                   4478:         return $outcome;
                   4479:     }
1.353     www      4480: }
                   4481: 
                   4482: sub courseiddump {
1.921     raeburn  4483:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4484:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4485:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4486:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4487:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4488:     my $as_hash = 1;
                   4489:     my %returnhash;
                   4490:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4491:     my %libserv = &all_library();
                   4492:     foreach my $tryserver (keys(%libserv)) {
                   4493:         if ( (  $hostidflag == 1 
                   4494: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4495: 	     || (!defined($hostidflag)) ) {
                   4496: 
1.918     raeburn  4497: 	    if (($domfilter eq '') ||
                   4498: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4499:                 my $rep;
                   4500:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4501:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4502:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4503:                                 &escape($descfilter), &escape($instcodefilter), 
                   4504:                                 &escape($ownerfilter), &escape($coursefilter),
                   4505:                                 &escape($typefilter), &escape($regexp_ok), 
                   4506:                                 $as_hash, &escape($selfenrollonly), 
                   4507:                                 &escape($catfilter), $showhidden, $caller, 
                   4508:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4509:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  4510:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4511:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 4512:                 } else {
                   4513:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4514:                              $sincefilter.':'.&escape($descfilter).':'.
                   4515:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4516:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4517:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4518:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4519:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4520:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4521:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  4522:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4523:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 4524:                 }
                   4525:                      
1.918     raeburn  4526:                 my @pairs=split(/\&/,$rep);
                   4527:                 foreach my $item (@pairs) {
                   4528:                     my ($key,$value)=split(/\=/,$item,2);
                   4529:                     $key = &unescape($key);
                   4530:                     next if ($key =~ /^error: 2 /);
                   4531:                     my $result = &thaw_unescape($value);
                   4532:                     if (ref($result) eq 'HASH') {
                   4533:                         $returnhash{$key}=$result;
                   4534:                     } else {
1.921     raeburn  4535:                         my @responses = split(/:/,$value);
                   4536:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4537:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4538:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4539:                         }
1.1008    raeburn  4540:                     }
1.353     www      4541:                 }
                   4542:             }
                   4543:         }
                   4544:     }
                   4545:     return %returnhash;
                   4546: }
                   4547: 
1.1055    raeburn  4548: sub courselastaccess {
                   4549:     my ($cdom,$cnum,$hostidref) = @_;
                   4550:     my %returnhash;
                   4551:     if ($cdom && $cnum) {
                   4552:         my $chome = &homeserver($cnum,$cdom);
                   4553:         if ($chome ne 'no_host') {
                   4554:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4555:             &extract_lastaccess(\%returnhash,$rep);
                   4556:         }
                   4557:     } else {
                   4558:         if (!$cdom) { $cdom=''; }
                   4559:         my %libserv = &all_library();
                   4560:         foreach my $tryserver (keys(%libserv)) {
                   4561:             if (ref($hostidref) eq 'ARRAY') {
                   4562:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4563:             } 
                   4564:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4565:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4566:                 &extract_lastaccess(\%returnhash,$rep);
                   4567:             }
                   4568:         }
                   4569:     }
                   4570:     return %returnhash;
                   4571: }
                   4572: 
                   4573: sub extract_lastaccess {
                   4574:     my ($returnhash,$rep) = @_;
                   4575:     if (ref($returnhash) eq 'HASH') {
                   4576:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4577:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4578:                  $rep eq '') {
                   4579:             my @pairs=split(/\&/,$rep);
                   4580:             foreach my $item (@pairs) {
                   4581:                 my ($key,$value)=split(/\=/,$item,2);
                   4582:                 $key = &unescape($key);
                   4583:                 next if ($key =~ /^error: 2 /);
                   4584:                 $returnhash->{$key} = &thaw_unescape($value);
                   4585:             }
                   4586:         }
                   4587:     }
                   4588:     return;
                   4589: }
                   4590: 
1.658     raeburn  4591: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4592: 
                   4593: sub dcmailput {
1.685     raeburn  4594:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4595:     my $status = &Apache::lonnet::critical(
1.740     www      4596:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4597:        &escape($message),$server);
1.662     raeburn  4598:     return $status;
                   4599: }
                   4600: 
1.658     raeburn  4601: sub dcmaildump {
                   4602:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4603:     my %returnhash=();
1.846     albertel 4604: 
                   4605:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4606:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4607:                                                          &escape($enddate).':';
                   4608: 	my @esc_senders=map { &escape($_)} @$senders;
                   4609: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4610: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4611:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4612:             if (($key) && ($value)) {
                   4613:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4614:             }
                   4615:         }
                   4616:     }
                   4617:     return %returnhash;
                   4618: }
1.662     raeburn  4619: # ---------------------------------------------------------- Domain roles
                   4620: 
                   4621: sub get_domain_roles {
                   4622:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4623:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4624:         $startdate = '.';
                   4625:     }
1.1018    raeburn  4626:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4627:         $enddate = '.';
                   4628:     }
1.922     raeburn  4629:     my $rolelist;
                   4630:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4631:         $rolelist = join('&',@{$roles});
1.922     raeburn  4632:     }
1.662     raeburn  4633:     my %personnel = ();
1.841     albertel 4634: 
                   4635:     my %servers = &get_servers($dom,'library');
                   4636:     foreach my $tryserver (keys(%servers)) {
                   4637: 	%{$personnel{$tryserver}}=();
                   4638: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4639: 					    &escape($startdate).':'.
                   4640: 					    &escape($enddate).':'.
                   4641: 					    &escape($rolelist), $tryserver))) {
                   4642: 	    my ($key,$value) = split(/\=/,$line,2);
                   4643: 	    if (($key) && ($value)) {
                   4644: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4645: 	    }
                   4646: 	}
1.662     raeburn  4647:     }
                   4648:     return %personnel;
                   4649: }
1.658     raeburn  4650: 
1.1057    www      4651: # ----------------------------------------------------------- Interval timing 
1.149     www      4652: 
1.1153    www      4653: {
                   4654: # Caches needed for speedup of navmaps
                   4655: # We don't want to cache this for very long at all (5 seconds at most)
                   4656: # 
                   4657: # The user for whom we cache
                   4658: my $cachedkey='';
                   4659: # The cached times for this user
                   4660: my %cachedtimes=();
                   4661: # When this was last done
1.1282    raeburn  4662: my $cachedtime='';
1.1153    www      4663: 
                   4664: sub load_all_first_access {
1.1308    raeburn  4665:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      4666:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  4667:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   4668:         (!$ignorecache)) {
1.1154    raeburn  4669:         return;
                   4670:     }
                   4671:     $cachedtime=time;
                   4672:     $cachedkey=$uname.':'.$udom;
                   4673:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4674: }
                   4675: 
1.504     albertel 4676: sub get_first_access {
1.1308    raeburn  4677:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 4678:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4679:     if ($argsymb) { $symb=$argsymb; }
                   4680:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4681:     if ($argmap) { $map = $argmap; }
1.926     albertel 4682:     if ($type eq 'course') {
                   4683: 	$res='course';
                   4684:     } elsif ($type eq 'map') {
1.588     albertel 4685: 	$res=&symbread($map);
                   4686:     } else {
                   4687: 	$res=$symb;
                   4688:     }
1.1308    raeburn  4689:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      4690:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4691: }
                   4692: 
                   4693: sub set_first_access {
1.1162    raeburn  4694:     my ($type,$interval)=@_;
1.790     albertel 4695:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4696:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4697:     if ($type eq 'course') {
                   4698: 	$res='course';
                   4699:     } elsif ($type eq 'map') {
1.588     albertel 4700: 	$res=&symbread($map);
                   4701:     } else {
                   4702: 	$res=$symb;
                   4703:     }
1.1153    www      4704:     $cachedkey='';
1.1162    raeburn  4705:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4706:     if (!$firstaccess) {
1.1162    raeburn  4707:         my $start = time;
                   4708: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4709:                           $udom,$uname);
                   4710:         if ($putres eq 'ok') {
                   4711:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4712:                  $udom,$uname); 
                   4713:             &appenv(
                   4714:                      {
                   4715:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4716:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4717:                      }
                   4718:                   );
                   4719:         }
                   4720:         return $putres;
1.505     albertel 4721:     }
                   4722:     return 'already_set';
1.504     albertel 4723: }
1.1153    www      4724: }
1.1282    raeburn  4725: 
1.110     www      4726: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4727: 
                   4728: sub expirespread {
                   4729:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4730:     my $cid=$env{'request.course.id'}; 
1.110     www      4731:     if ($cid) {
                   4732:        my $now=time;
                   4733:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4734:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4735:                             $env{'course.'.$cid.'.num'}.
1.110     www      4736: 	        	    ':nohist_expirationdates:'.
                   4737:                             &escape($key).'='.$now,
1.620     albertel 4738:                             $env{'course.'.$cid.'.home'})
1.110     www      4739:     }
                   4740:     return 'ok';
1.14      www      4741: }
                   4742: 
1.109     www      4743: # ----------------------------------------------------- Devalidate Spreadsheets
                   4744: 
                   4745: sub devalidate {
1.325     www      4746:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4747:     my $cid=$env{'request.course.id'}; 
1.109     www      4748:     if ($cid) {
1.391     matthew  4749:         # delete the stored spreadsheets for
                   4750:         # - the student level sheet of this user in course's homespace
                   4751:         # - the assessment level sheet for this resource 
                   4752:         #   for this user in user's homespace
1.553     albertel 4753: 	# - current conditional state info
1.325     www      4754: 	my $key=$uname.':'.$udom.':';
1.109     www      4755:         my $status=
1.299     matthew  4756: 	    &del('nohist_calculatedsheets',
1.391     matthew  4757: 		 [$key.'studentcalc:'],
1.620     albertel 4758: 		 $env{'course.'.$cid.'.domain'},
                   4759: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4760: 		.' '.
                   4761: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4762: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4763:         unless ($status eq 'ok ok') {
                   4764:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4765:                     $uname.' at '.$udom.' for '.
1.109     www      4766: 		    $symb.': '.$status);
1.133     albertel 4767:         }
1.553     albertel 4768: 	&delenv('user.state.'.$cid);
1.109     www      4769:     }
                   4770: }
                   4771: 
1.265     albertel 4772: sub get_scalar {
                   4773:     my ($string,$end) = @_;
                   4774:     my $value;
                   4775:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4776: 	$value = $1;
                   4777:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4778: 	$value = $1;
                   4779:     }
                   4780:     return &unescape($value);
                   4781: }
                   4782: 
                   4783: sub array2str {
                   4784:   my (@array) = @_;
                   4785:   my $result=&arrayref2str(\@array);
                   4786:   $result=~s/^__ARRAY_REF__//;
                   4787:   $result=~s/__END_ARRAY_REF__$//;
                   4788:   return $result;
                   4789: }
                   4790: 
1.204     albertel 4791: sub arrayref2str {
                   4792:   my ($arrayref) = @_;
1.265     albertel 4793:   my $result='__ARRAY_REF__';
1.204     albertel 4794:   foreach my $elem (@$arrayref) {
1.265     albertel 4795:     if(ref($elem) eq 'ARRAY') {
                   4796:       $result.=&arrayref2str($elem).'&';
                   4797:     } elsif(ref($elem) eq 'HASH') {
                   4798:       $result.=&hashref2str($elem).'&';
                   4799:     } elsif(ref($elem)) {
                   4800:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4801:     } else {
                   4802:       $result.=&escape($elem).'&';
                   4803:     }
                   4804:   }
                   4805:   $result=~s/\&$//;
1.265     albertel 4806:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4807:   return $result;
                   4808: }
                   4809: 
1.168     albertel 4810: sub hash2str {
1.204     albertel 4811:   my (%hash) = @_;
                   4812:   my $result=&hashref2str(\%hash);
1.265     albertel 4813:   $result=~s/^__HASH_REF__//;
                   4814:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4815:   return $result;
                   4816: }
                   4817: 
                   4818: sub hashref2str {
                   4819:   my ($hashref)=@_;
1.265     albertel 4820:   my $result='__HASH_REF__';
1.800     albertel 4821:   foreach my $key (sort(keys(%$hashref))) {
                   4822:     if (ref($key) eq 'ARRAY') {
                   4823:       $result.=&arrayref2str($key).'=';
                   4824:     } elsif (ref($key) eq 'HASH') {
                   4825:       $result.=&hashref2str($key).'=';
                   4826:     } elsif (ref($key)) {
1.265     albertel 4827:       $result.='=';
1.800     albertel 4828:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4829:     } else {
1.1132    raeburn  4830: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4831:     }
                   4832: 
1.800     albertel 4833:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4834:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4835:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4836:       $result.=&hashref2str($hashref->{$key}).'&';
                   4837:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4838:        $result.='&';
1.800     albertel 4839:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4840:     } else {
1.800     albertel 4841:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4842:     }
                   4843:   }
1.168     albertel 4844:   $result=~s/\&$//;
1.265     albertel 4845:   $result .= '__END_HASH_REF__';
1.168     albertel 4846:   return $result;
                   4847: }
                   4848: 
                   4849: sub str2hash {
1.265     albertel 4850:     my ($string)=@_;
                   4851:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4852:     return %$hash;
                   4853: }
                   4854: 
                   4855: sub str2hashref {
1.168     albertel 4856:   my ($string) = @_;
1.265     albertel 4857: 
                   4858:   my %hash;
                   4859: 
                   4860:   if($string !~ /^__HASH_REF__/) {
                   4861:       if (! ($string eq '' || !defined($string))) {
                   4862: 	  $hash{'error'}='Not hash reference';
                   4863:       }
                   4864:       return (\%hash, $string);
                   4865:   }
                   4866: 
                   4867:   $string =~ s/^__HASH_REF__//;
                   4868: 
                   4869:   while($string !~ /^__END_HASH_REF__/) {
                   4870:       #key
                   4871:       my $key='';
                   4872:       if($string =~ /^__HASH_REF__/) {
                   4873:           ($key, $string)=&str2hashref($string);
                   4874:           if(defined($key->{'error'})) {
                   4875:               $hash{'error'}='Bad data';
                   4876:               return (\%hash, $string);
                   4877:           }
                   4878:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4879:           ($key, $string)=&str2arrayref($string);
                   4880:           if($key->[0] eq 'Array reference error') {
                   4881:               $hash{'error'}='Bad data';
                   4882:               return (\%hash, $string);
                   4883:           }
                   4884:       } else {
                   4885:           $string =~ s/^(.*?)=//;
1.267     albertel 4886: 	  $key=&unescape($1);
1.265     albertel 4887:       }
                   4888:       $string =~ s/^=//;
                   4889: 
                   4890:       #value
                   4891:       my $value='';
                   4892:       if($string =~ /^__HASH_REF__/) {
                   4893:           ($value, $string)=&str2hashref($string);
                   4894:           if(defined($value->{'error'})) {
                   4895:               $hash{'error'}='Bad data';
                   4896:               return (\%hash, $string);
                   4897:           }
                   4898:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4899:           ($value, $string)=&str2arrayref($string);
                   4900:           if($value->[0] eq 'Array reference error') {
                   4901:               $hash{'error'}='Bad data';
                   4902:               return (\%hash, $string);
                   4903:           }
                   4904:       } else {
                   4905: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4906:       }
                   4907:       $string =~ s/^&//;
                   4908: 
                   4909:       $hash{$key}=$value;
1.204     albertel 4910:   }
1.265     albertel 4911: 
                   4912:   $string =~ s/^__END_HASH_REF__//;
                   4913: 
                   4914:   return (\%hash, $string);
1.204     albertel 4915: }
                   4916: 
                   4917: sub str2array {
1.265     albertel 4918:     my ($string)=@_;
                   4919:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4920:     return @$array;
                   4921: }
                   4922: 
                   4923: sub str2arrayref {
1.204     albertel 4924:   my ($string) = @_;
1.265     albertel 4925:   my @array;
                   4926: 
                   4927:   if($string !~ /^__ARRAY_REF__/) {
                   4928:       if (! ($string eq '' || !defined($string))) {
                   4929: 	  $array[0]='Array reference error';
                   4930:       }
                   4931:       return (\@array, $string);
                   4932:   }
                   4933: 
                   4934:   $string =~ s/^__ARRAY_REF__//;
                   4935: 
                   4936:   while($string !~ /^__END_ARRAY_REF__/) {
                   4937:       my $value='';
                   4938:       if($string =~ /^__HASH_REF__/) {
                   4939:           ($value, $string)=&str2hashref($string);
                   4940:           if(defined($value->{'error'})) {
                   4941:               $array[0] ='Array reference error';
                   4942:               return (\@array, $string);
                   4943:           }
                   4944:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4945:           ($value, $string)=&str2arrayref($string);
                   4946:           if($value->[0] eq 'Array reference error') {
                   4947:               $array[0] ='Array reference error';
                   4948:               return (\@array, $string);
                   4949:           }
                   4950:       } else {
                   4951: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4952:       }
                   4953:       $string =~ s/^&//;
                   4954: 
                   4955:       push(@array, $value);
1.191     harris41 4956:   }
1.265     albertel 4957: 
                   4958:   $string =~ s/^__END_ARRAY_REF__//;
                   4959: 
                   4960:   return (\@array, $string);
1.168     albertel 4961: }
                   4962: 
1.167     albertel 4963: # -------------------------------------------------------------------Temp Store
                   4964: 
1.168     albertel 4965: sub tmpreset {
                   4966:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4967:   if (!$symb) {
                   4968:     $symb=&symbread();
1.620     albertel 4969:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4970:   }
                   4971:   $symb=escape($symb);
                   4972: 
1.620     albertel 4973:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4974:   $namespace=~s/\//\_/g;
                   4975:   $namespace=~s/\W//g;
                   4976: 
1.620     albertel 4977:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4978:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4979:   if ($domain eq 'public' && $stuname eq 'public') {
                   4980:       $stuname=$ENV{'REMOTE_ADDR'};
                   4981:   }
1.1117    foxr     4982:   my $path=LONCAPA::tempdir();
1.168     albertel 4983:   my %hash;
                   4984:   if (tie(%hash,'GDBM_File',
                   4985: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4986: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4987:     foreach my $key (keys(%hash)) {
1.180     albertel 4988:       if ($key=~ /:$symb/) {
1.168     albertel 4989: 	delete($hash{$key});
                   4990:       }
                   4991:     }
                   4992:   }
                   4993: }
                   4994: 
1.167     albertel 4995: sub tmpstore {
1.168     albertel 4996:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4997: 
                   4998:   if (!$symb) {
                   4999:     $symb=&symbread();
1.620     albertel 5000:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5001:   }
                   5002:   $symb=escape($symb);
                   5003: 
                   5004:   if (!$namespace) {
                   5005:     # I don't think we would ever want to store this for a course.
                   5006:     # it seems this will only be used if we don't have a course.
1.620     albertel 5007:     #$namespace=$env{'request.course.id'};
1.168     albertel 5008:     #if (!$namespace) {
1.620     albertel 5009:       $namespace=$env{'request.state'};
1.168     albertel 5010:     #}
                   5011:   }
                   5012:   $namespace=~s/\//\_/g;
                   5013:   $namespace=~s/\W//g;
1.620     albertel 5014:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5015:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5016:   if ($domain eq 'public' && $stuname eq 'public') {
                   5017:       $stuname=$ENV{'REMOTE_ADDR'};
                   5018:   }
1.168     albertel 5019:   my $now=time;
                   5020:   my %hash;
1.1117    foxr     5021:   my $path=LONCAPA::tempdir();
1.168     albertel 5022:   if (tie(%hash,'GDBM_File',
                   5023: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5024: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5025:     $hash{"version:$symb"}++;
                   5026:     my $version=$hash{"version:$symb"};
                   5027:     my $allkeys=''; 
                   5028:     foreach my $key (keys(%$storehash)) {
                   5029:       $allkeys.=$key.':';
1.591     albertel 5030:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5031:     }
                   5032:     $hash{"$version:$symb:timestamp"}=$now;
                   5033:     $allkeys.='timestamp';
                   5034:     $hash{"$version:keys:$symb"}=$allkeys;
                   5035:     if (untie(%hash)) {
                   5036:       return 'ok';
                   5037:     } else {
                   5038:       return "error:$!";
                   5039:     }
                   5040:   } else {
                   5041:     return "error:$!";
                   5042:   }
                   5043: }
1.167     albertel 5044: 
1.168     albertel 5045: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5046: 
1.168     albertel 5047: sub tmprestore {
                   5048:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5049: 
1.168     albertel 5050:   if (!$symb) {
                   5051:     $symb=&symbread();
1.620     albertel 5052:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5053:   }
                   5054:   $symb=escape($symb);
                   5055: 
1.620     albertel 5056:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5057: 
1.620     albertel 5058:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5059:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5060:   if ($domain eq 'public' && $stuname eq 'public') {
                   5061:       $stuname=$ENV{'REMOTE_ADDR'};
                   5062:   }
1.168     albertel 5063:   my %returnhash;
                   5064:   $namespace=~s/\//\_/g;
                   5065:   $namespace=~s/\W//g;
                   5066:   my %hash;
1.1117    foxr     5067:   my $path=LONCAPA::tempdir();
1.168     albertel 5068:   if (tie(%hash,'GDBM_File',
                   5069: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5070: 	  &GDBM_READER(),0640)) {
1.168     albertel 5071:     my $version=$hash{"version:$symb"};
                   5072:     $returnhash{'version'}=$version;
                   5073:     my $scope;
                   5074:     for ($scope=1;$scope<=$version;$scope++) {
                   5075:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5076:       my @keys=split(/:/,$vkeys);
                   5077:       my $key;
                   5078:       $returnhash{"$scope:keys"}=$vkeys;
                   5079:       foreach $key (@keys) {
1.591     albertel 5080: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5081: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5082:       }
                   5083:     }
1.168     albertel 5084:     if (!(untie(%hash))) {
                   5085:       return "error:$!";
                   5086:     }
                   5087:   } else {
                   5088:     return "error:$!";
                   5089:   }
                   5090:   return %returnhash;
1.167     albertel 5091: }
                   5092: 
1.9       www      5093: # ----------------------------------------------------------------------- Store
                   5094: 
                   5095: sub store {
1.1269    raeburn  5096:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5097:     my $home='';
                   5098: 
1.168     albertel 5099:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5100: 
1.213     www      5101:     $symb=&symbclean($symb);
1.122     albertel 5102:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5103: 
1.620     albertel 5104:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5105:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5106: 
                   5107:     &devalidate($symb,$stuname,$domain);
1.109     www      5108: 
                   5109:     $symb=escape($symb);
1.187     www      5110:     if (!$namespace) { 
1.620     albertel 5111:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5112:           return ''; 
                   5113:        } 
                   5114:     }
1.620     albertel 5115:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5116: 
                   5117:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5118:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5119: 
1.12      www      5120:     my $namevalue='';
1.800     albertel 5121:     foreach my $key (keys(%$storehash)) {
                   5122:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5123:     }
1.12      www      5124:     $namevalue=~s/\&$//;
1.187     www      5125:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5126:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5127: }
                   5128: 
1.47      www      5129: # -------------------------------------------------------------- Critical Store
                   5130: 
                   5131: sub cstore {
1.1269    raeburn  5132:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5133:     my $home='';
                   5134: 
1.168     albertel 5135:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5136: 
1.213     www      5137:     $symb=&symbclean($symb);
1.122     albertel 5138:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5139: 
1.620     albertel 5140:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5141:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5142: 
                   5143:     &devalidate($symb,$stuname,$domain);
1.109     www      5144: 
                   5145:     $symb=escape($symb);
1.187     www      5146:     if (!$namespace) { 
1.620     albertel 5147:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5148:           return ''; 
                   5149:        } 
                   5150:     }
1.620     albertel 5151:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5152: 
                   5153:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5154:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5155: 
1.47      www      5156:     my $namevalue='';
1.800     albertel 5157:     foreach my $key (keys(%$storehash)) {
                   5158:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5159:     }
1.47      www      5160:     $namevalue=~s/\&$//;
1.187     www      5161:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5162:     return critical
1.1269    raeburn  5163:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5164: }
                   5165: 
1.9       www      5166: # --------------------------------------------------------------------- Restore
                   5167: 
                   5168: sub restore {
1.124     www      5169:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5170:     my $home='';
                   5171: 
1.168     albertel 5172:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5173: 
1.122     albertel 5174:     if (!$symb) {
1.1224    raeburn  5175:         return if ($namespace eq 'courserequests');
                   5176:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5177:     } else {
1.1224    raeburn  5178:         unless ($namespace eq 'courserequests') {
                   5179:             $symb=&escape(&symbclean($symb));
                   5180:         }
1.122     albertel 5181:     }
1.188     www      5182:     if (!$namespace) { 
1.620     albertel 5183:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5184:           return ''; 
                   5185:        } 
                   5186:     }
1.620     albertel 5187:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5188:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5189:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5190:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5191: 
1.12      www      5192:     my %returnhash=();
1.800     albertel 5193:     foreach my $line (split(/\&/,$answer)) {
                   5194: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5195:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5196:     }
1.75      www      5197:     my $version;
                   5198:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5199:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5200:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5201:        }
1.75      www      5202:     }
1.13      www      5203:     return %returnhash;
1.34      www      5204: }
                   5205: 
                   5206: # ---------------------------------------------------------- Course Description
1.1118    foxr     5207: #
                   5208: #  
1.34      www      5209: 
                   5210: sub coursedescription {
1.731     albertel 5211:     my ($courseid,$args)=@_;
1.34      www      5212:     $courseid=~s/^\///;
1.49      www      5213:     $courseid=~s/\_/\//g;
1.34      www      5214:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5215:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5216:     my $normalid=$cdomain.'_'.$cnum;
                   5217:     # need to always cache even if we get errors otherwise we keep 
                   5218:     # trying and trying and trying to get the course description.
                   5219:     my %envhash=();
                   5220:     my %returnhash=();
1.731     albertel 5221:     
                   5222:     my $expiretime=600;
                   5223:     if ($env{'request.course.id'} eq $normalid) {
                   5224: 	$expiretime=120;
                   5225:     }
                   5226: 
                   5227:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5228:     if (!$args->{'freshen_cache'}
                   5229: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5230: 	foreach my $key (keys(%env)) {
                   5231: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5232: 	    my ($setting) = $1;
                   5233: 	    $returnhash{$setting} = $env{$key};
                   5234: 	}
                   5235: 	return %returnhash;
                   5236:     }
                   5237: 
1.1118    foxr     5238:     # get the data again
                   5239: 
1.731     albertel 5240:     if (!$args->{'one_time'}) {
                   5241: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5242:     }
1.811     albertel 5243: 
1.34      www      5244:     if ($chome ne 'no_host') {
1.302     albertel 5245:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5246:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5247: 	   my $username = $env{'user.name'}; # Defult username
                   5248: 	   if(defined $args->{'user'}) {
                   5249: 	       $username = $args->{'user'};
                   5250: 	   }
1.129     albertel 5251:            $returnhash{'home'}= $chome;
                   5252: 	   $returnhash{'domain'} = $cdomain;
                   5253: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5254:            if (!defined($returnhash{'type'})) {
                   5255:                $returnhash{'type'} = 'Course';
                   5256:            }
1.130     albertel 5257:            while (my ($name,$value) = each %returnhash) {
1.53      www      5258:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5259:            }
1.270     www      5260:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5261:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5262: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5263:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5264:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5265:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5266:        }
                   5267:     }
1.731     albertel 5268:     if (!$args->{'one_time'}) {
1.949     raeburn  5269: 	&appenv(\%envhash);
1.731     albertel 5270:     }
1.302     albertel 5271:     return %returnhash;
1.461     www      5272: }
                   5273: 
1.1080    raeburn  5274: sub update_released_required {
                   5275:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5276:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5277:         $cid = $env{'request.course.id'};
                   5278:         $cdom = $env{'course.'.$cid.'.domain'};
                   5279:         $cnum = $env{'course.'.$cid.'.num'};
                   5280:         $chome = $env{'course.'.$cid.'.home'};
                   5281:     }
                   5282:     if ($needsrelease) {
                   5283:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5284:         my $needsupdate;
                   5285:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5286:             $needsupdate = 1;
                   5287:         } else {
                   5288:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5289:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5290:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5291:                 $needsupdate = 1;
                   5292:             }
                   5293:         }
                   5294:         if ($needsupdate) {
                   5295:             my %needshash = (
                   5296:                              'internal.releaserequired' => $needsrelease,
                   5297:                             );
                   5298:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5299:             if ($putresult eq 'ok') {
                   5300:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5301:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5302:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5303:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5304:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5305:                 }
                   5306:             }
                   5307:         }
                   5308:     }
                   5309:     return;
                   5310: }
                   5311: 
1.461     www      5312: # -------------------------------------------------See if a user is privileged
                   5313: 
                   5314: sub privileged {
1.1219    raeburn  5315:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5316:     my $now = time;
1.1219    raeburn  5317:     my $roles;
                   5318:     if (ref($possroles) eq 'ARRAY') {
                   5319:         $roles = $possroles; 
                   5320:     } else {
                   5321:         $roles = ['dc','su'];
                   5322:     }
                   5323:     if (ref($possdomains) eq 'ARRAY') {
                   5324:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5325:         foreach my $dom (@{$possdomains}) {
                   5326:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5327:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5328:                 foreach my $role (@{$roles}) {
                   5329:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5330:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5331:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5332:                             return 1 unless (($end && $end < $now) ||
                   5333:                                              ($start && $start > $now));
                   5334:                         }
                   5335:                     }
                   5336:                 }
                   5337:             }
                   5338:         }
                   5339:     } else {
                   5340:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5341:         my $now = time;
1.1170    droeschl 5342: 
1.1275    musolffc 5343:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5344:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5345:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5346:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5347:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5348:             }
1.1219    raeburn  5349:         }
                   5350:     }
                   5351:     return 0;
                   5352: }
1.1170    droeschl 5353: 
1.1219    raeburn  5354: sub privileged_by_domain {
                   5355:     my ($domains,$roles) = @_;
                   5356:     my %privileged = ();
                   5357:     my $cachetime = 60*60*24;
                   5358:     my $now = time;
                   5359:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5360:         return %privileged;
                   5361:     }
                   5362:     foreach my $dom (@{$domains}) {
                   5363:         next if (ref($privileged{$dom}) eq 'HASH');
                   5364:         my $needroles;
                   5365:         foreach my $role (@{$roles}) {
                   5366:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5367:             if (defined($cached)) {
                   5368:                 if (ref($result) eq 'HASH') {
                   5369:                     $privileged{$dom}{$role} = $result;
                   5370:                 }
                   5371:             } else {
                   5372:                 $needroles = 1;
                   5373:             }
                   5374:         }
                   5375:         if ($needroles) {
                   5376:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5377:             $privileged{$dom} = {};
                   5378:             foreach my $server (keys(%dompersonnel)) {
                   5379:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5380:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5381:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5382:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5383:                         next if ($end && $end < $now);
                   5384:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5385:                             $dompersonnel{$server}{$item};
                   5386:                     }
                   5387:                 }
                   5388:             }
                   5389:             if (ref($privileged{$dom}) eq 'HASH') {
                   5390:                 foreach my $role (@{$roles}) {
                   5391:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5392:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5393:                     } else {
                   5394:                         my %hash = ();
                   5395:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5396:                     }
                   5397:                 }
                   5398:             }
                   5399:         }
                   5400:     }
                   5401:     return %privileged;
1.9       www      5402: }
1.1       albertel 5403: 
1.103     harris41 5404: # -------------------------------------------------------- Get user privileges
1.11      www      5405: 
                   5406: sub rolesinit {
1.1169    droeschl 5407:     my ($domain, $username) = @_;
                   5408:     my %userroles = ('user.login.time' => time);
                   5409:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5410: 
                   5411:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5412:     # also, blocking can be triggered by an activating timer
                   5413:     # it's saved in the user's %env.
                   5414:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5415:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5416:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5417:         %timerintchk, %timerintenv);
                   5418: 
1.1162    raeburn  5419:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5420:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5421:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5422:     }
1.1169    droeschl 5423: 
1.1162    raeburn  5424:     foreach my $key (keys(%timerinterval)) {
                   5425:         my ($cid,$rest) = split(/\0/,$key);
                   5426:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5427:     }
1.1169    droeschl 5428: 
1.11      www      5429:     my %allroles=();
1.1162    raeburn  5430:     my %allgroups=();
1.11      www      5431: 
1.1274    raeburn  5432:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5433:         my $role = $rolesdump{$area};
                   5434:         $area =~ s/\_\w\w$//;
                   5435: 
                   5436:         my ($trole, $tend, $tstart, $group_privs);
                   5437: 
                   5438:         if ($role =~ /^cr/) {
                   5439:         # Custom role, defined by a user 
                   5440:         # e.g., user.role.cr/msu/smith/mynewrole
                   5441:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5442:                 $trole = $1;
                   5443:                 ($tend, $tstart) = split('_', $2);
                   5444:             } else {
                   5445:                 $trole = $role;
                   5446:             }
                   5447:         } elsif ($role =~ m|^gr/|) {
                   5448:         # Role of member in a group, defined within a course/community
                   5449:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5450:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5451:             next if $tstart eq '-1';
                   5452:             ($trole, $group_privs) = split(/\//, $trole);
                   5453:             $group_privs = &unescape($group_privs);
                   5454:         } else {
                   5455:         # Just a normal role, defined in roles.tab
                   5456:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5457:         }
                   5458: 
                   5459:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5460:                  $username);
                   5461:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5462: 
                   5463:         # role expired or not available yet?
                   5464:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5465:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5466: 
                   5467:         next if $area eq '' or $trole eq '';
                   5468: 
                   5469:         my $spec = "$trole.$area";
                   5470:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5471: 
                   5472:         if ($trole =~ /^cr\//) {
                   5473:         # Custom role, defined by a user
                   5474:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5475:         } elsif ($trole eq 'gr') {
                   5476:         # Role of a member in a group, defined within a course/community
                   5477:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5478:             next;
                   5479:         } else {
                   5480:         # Normal role, defined in roles.tab
                   5481:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5482:         }
                   5483: 
                   5484:         my $cid = $tdomain.'_'.$trest;
                   5485:         unless ($firstaccchk{$cid}) {
                   5486:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5487:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5488:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5489:                         $coursetimerstarts{$cid}{$item}; 
                   5490:                 }
                   5491:             }
                   5492:             $firstaccchk{$cid} = 1;
                   5493:         }
                   5494:         unless ($timerintchk{$cid}) {
                   5495:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5496:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5497:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5498:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5499:                 }
1.12      www      5500:             }
1.1169    droeschl 5501:             $timerintchk{$cid} = 1;
1.191     harris41 5502:         }
1.11      www      5503:     }
1.1169    droeschl 5504: 
                   5505:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5506:         \%allroles, \%allgroups);
                   5507:     $env{'user.adv'} = $userroles{'user.adv'};
                   5508: 
1.1162    raeburn  5509:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5510: }
                   5511: 
1.567     raeburn  5512: sub set_arearole {
1.1215    raeburn  5513:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5514:     unless ($nolog) {
1.567     raeburn  5515: # log the associated role with the area
1.1215    raeburn  5516:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5517:     }
1.743     albertel 5518:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5519: }
                   5520: 
                   5521: sub custom_roleprivs {
                   5522:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5523:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5524:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5525:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5526:         my ($rdummy,$roledef)=
                   5527:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5528:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5529:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5530:             if (defined($syspriv)) {
1.1043    raeburn  5531:                 if ($trest =~ /^$match_community$/) {
                   5532:                     $syspriv =~ s/bre\&S//; 
                   5533:                 }
1.567     raeburn  5534:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5535:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5536:             }
                   5537:             if ($tdomain ne '') {
                   5538:                 if (defined($dompriv)) {
                   5539:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5540:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5541:                 }
                   5542:                 if (($trest ne '') && (defined($coursepriv))) {
                   5543:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5544:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5545:                 }
                   5546:             }
                   5547:         }
                   5548:     }
                   5549: }
                   5550: 
1.678     raeburn  5551: sub group_roleprivs {
                   5552:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5553:     my $access = 1;
                   5554:     my $now = time;
                   5555:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5556:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5557:     if ($access) {
1.811     albertel 5558:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5559:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5560:     }
                   5561: }
1.567     raeburn  5562: 
                   5563: sub standard_roleprivs {
                   5564:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5565:     if (defined($pr{$trole.':s'})) {
                   5566:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5567:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5568:     }
                   5569:     if ($tdomain ne '') {
                   5570:         if (defined($pr{$trole.':d'})) {
                   5571:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5572:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5573:         }
                   5574:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5575:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5576:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5577:         }
                   5578:     }
                   5579: }
                   5580: 
                   5581: sub set_userprivs {
1.1064    raeburn  5582:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5583:     my $author=0;
                   5584:     my $adv=0;
1.678     raeburn  5585:     my %grouproles = ();
                   5586:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5587:         my @groupkeys; 
1.1000    raeburn  5588:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5589:             push(@groupkeys,$role);
                   5590:         }
                   5591:         if (ref($groups_roles) eq 'HASH') {
                   5592:             foreach my $key (keys(%{$groups_roles})) {
                   5593:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5594:                     push(@groupkeys,$key);
                   5595:                 }
                   5596:             }
                   5597:         }
                   5598:         if (@groupkeys > 0) {
                   5599:             foreach my $role (@groupkeys) {
                   5600:                 my ($trole,$area,$sec,$extendedarea);
                   5601:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5602:                     $trole = $1;
                   5603:                     $area = $2;
                   5604:                     $sec = $3;
                   5605:                     $extendedarea = $area.$sec;
                   5606:                     if (exists($$allgroups{$area})) {
                   5607:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5608:                             my $spec = $trole.'.'.$extendedarea;
                   5609:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5610:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5611:                         }
1.678     raeburn  5612:                     }
                   5613:                 }
                   5614:             }
                   5615:         }
                   5616:     }
1.800     albertel 5617:     foreach my $group (keys(%grouproles)) {
                   5618:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5619:     }
1.800     albertel 5620:     foreach my $role (keys(%{$allroles})) {
                   5621:         my %thesepriv;
1.941     raeburn  5622:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5623:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5624:             if ($item ne '') {
                   5625:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5626:                 if ($restrictions eq '') {
                   5627:                     $thesepriv{$privilege}='F';
                   5628:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5629:                     $thesepriv{$privilege}.=$restrictions;
                   5630:                 }
                   5631:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5632:             }
                   5633:         }
                   5634:         my $thesestr='';
1.1104    raeburn  5635:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5636: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5637: 	}
                   5638:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5639:     }
                   5640:     return ($author,$adv);
                   5641: }
                   5642: 
1.994     raeburn  5643: sub role_status {
1.1104    raeburn  5644:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5645:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5646:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5647:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5648:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5649:             $$where = '/'.$two;
1.994     raeburn  5650:             $$trolecode=$$role.'.'.$$where;
                   5651:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5652:             $$tstatus='is';
1.1104    raeburn  5653:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5654:                 $$tstatus='future';
1.1034    raeburn  5655:                 if ($$tstart<$now) {
                   5656:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5657:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5658:                             my (%allroles,%allgroups,$group_privs,
                   5659:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5660:                             my %userroles = (
                   5661:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5662:                             );
1.1064    raeburn  5663:                             @rolecodes = ('cm'); 
1.1002    raeburn  5664:                             my $spec=$$role.'.'.$$where;
                   5665:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5666:                             if ($$role =~ /^cr\//) {
                   5667:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5668:                                 push(@rolecodes,'cr');
1.1002    raeburn  5669:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5670:                                 push(@rolecodes,$$role);
1.1002    raeburn  5671:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5672:                                                     $env{'user.name'});
1.1064    raeburn  5673:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5674:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5675:                                 $group_privs = &unescape($group_privs);
                   5676:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5677:                                 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  5678:                                 &get_groups_roles($tdomain,$trest,
                   5679:                                                   \%course_roles,\@rolecodes,
                   5680:                                                   \%groups_roles);
1.1002    raeburn  5681:                             } else {
1.1064    raeburn  5682:                                 push(@rolecodes,$$role);
1.1002    raeburn  5683:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5684:                             }
1.1064    raeburn  5685:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5686:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5687:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5688:                         }
                   5689:                     }
1.1034    raeburn  5690:                     $$tstatus = 'is';
1.1002    raeburn  5691:                 }
1.994     raeburn  5692:             }
                   5693:             if ($$tend) {
1.1104    raeburn  5694:                 if ($$tend<$update) {
1.994     raeburn  5695:                     $$tstatus='expired';
                   5696:                 } elsif ($$tend<$now) {
                   5697:                     $$tstatus='will_not';
                   5698:                 }
                   5699:             }
                   5700:         }
                   5701:     }
                   5702: }
                   5703: 
1.1104    raeburn  5704: sub get_groups_roles {
                   5705:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5706:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5707:                   (ref($rolecodes) eq 'ARRAY') && 
                   5708:                   (ref($groups_roles) eq 'HASH')); 
                   5709:     if (keys(%{$cdom_courseroles}) > 0) {
                   5710:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5711:         if ($cdom ne '' && $cnum ne '') {
                   5712:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5713:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5714:                     my $crsrole = $1;
                   5715:                     my $crssec = $2;
                   5716:                     if ($crsrole =~ /^cr/) {
                   5717:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5718:                             push(@{$rolecodes},'cr');
                   5719:                         }
                   5720:                     } else {
                   5721:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5722:                             push(@{$rolecodes},$crsrole);
                   5723:                         }
                   5724:                     }
                   5725:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5726:                     if ($crssec ne '') {
                   5727:                         $rolekey .= "/$crssec";
                   5728:                     }
                   5729:                     $rolekey .= './';
                   5730:                     $groups_roles->{$rolekey} = $rolecodes;
                   5731:                 }
                   5732:             }
                   5733:         }
                   5734:     }
                   5735:     return;
                   5736: }
                   5737: 
                   5738: sub delete_env_groupprivs {
                   5739:     my ($where,$courseroles,$possroles) = @_;
                   5740:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5741:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5742:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5743:         %{$courseroles->{$udom}} =
                   5744:             &get_my_roles('','','userroles',['active'],
                   5745:                           $possroles,[$udom],1);
                   5746:     }
                   5747:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5748:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5749:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5750:             my $area = '/'.$cdom.'/'.$cnum;
                   5751:             my $privkey = "user.priv.$crsrole.$area";
                   5752:             if ($crssec ne '') {
                   5753:                 $privkey .= '/'.$crssec;
                   5754:             }
                   5755:             $privkey .= ".$area/$group";
                   5756:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5757:         }
                   5758:     }
                   5759:     return;
                   5760: }
                   5761: 
1.994     raeburn  5762: sub check_adhoc_privs {
1.1104    raeburn  5763:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5764:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5765:     my $setprivs;
1.994     raeburn  5766:     if ($env{$cckey}) {
                   5767:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5768:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5769:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5770:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5771:             $setprivs = 1;
1.994     raeburn  5772:         }
                   5773:     } else {
1.1088    raeburn  5774:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5775:         $setprivs = 1;
1.994     raeburn  5776:     }
1.1185    raeburn  5777:     return $setprivs;
1.994     raeburn  5778: }
                   5779: 
                   5780: sub set_adhoc_privileges {
                   5781: # role can be cc or ca
1.1088    raeburn  5782:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5783:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5784:     my $spec = $role.'.'.$area;
                   5785:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5786:                                   $env{'user.name'},1);
1.994     raeburn  5787:     my %ccrole = ();
                   5788:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5789:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5790:     &appenv(\%userroles,[$role,'cm']);
                   5791:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5792:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5793:         &appenv( {'request.role'        => $spec,
                   5794:                   'request.role.domain' => $dcdom,
                   5795:                   'request.course.sec'  => ''
                   5796:                  }
                   5797:                );
                   5798:         my $tadv=0;
                   5799:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5800:         &appenv({'request.role.adv'    => $tadv});
                   5801:     }
1.994     raeburn  5802: }
                   5803: 
1.12      www      5804: # --------------------------------------------------------------- get interface
                   5805: 
                   5806: sub get {
1.131     albertel 5807:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5808:    my $items='';
1.800     albertel 5809:    foreach my $item (@$storearr) {
                   5810:        $items.=&escape($item).'&';
1.191     harris41 5811:    }
1.12      www      5812:    $items=~s/\&$//;
1.620     albertel 5813:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5814:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5815:    my $uhome=&homeserver($uname,$udomain);
                   5816: 
1.133     albertel 5817:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5818:    my @pairs=split(/\&/,$rep);
1.273     albertel 5819:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5820:      return @pairs;
                   5821:    }
1.15      www      5822:    my %returnhash=();
1.42      www      5823:    my $i=0;
1.800     albertel 5824:    foreach my $item (@$storearr) {
                   5825:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5826:       $i++;
1.191     harris41 5827:    }
1.15      www      5828:    return %returnhash;
1.27      www      5829: }
                   5830: 
                   5831: # --------------------------------------------------------------- del interface
                   5832: 
                   5833: sub del {
1.133     albertel 5834:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5835:    my $items='';
1.800     albertel 5836:    foreach my $item (@$storearr) {
                   5837:        $items.=&escape($item).'&';
1.191     harris41 5838:    }
1.984     neumanie 5839: 
1.27      www      5840:    $items=~s/\&$//;
1.620     albertel 5841:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5842:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5843:    my $uhome=&homeserver($uname,$udomain);
                   5844:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5845: }
                   5846: 
                   5847: # -------------------------------------------------------------- dump interface
                   5848: 
1.1180    droeschl 5849: sub unserialize {
                   5850:     my ($rep, $escapedkeys) = @_;
                   5851: 
                   5852:     return {} if $rep =~ /^error/;
                   5853: 
                   5854:     my %returnhash=();
1.1252    raeburn  5855: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 5856: 	    my ($key, $value) = split(/=/, $item, 2);
                   5857: 	    $key = unescape($key) unless $escapedkeys;
                   5858: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  5859: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 5860: 	}
                   5861:     #return %returnhash;
                   5862:     return \%returnhash;
                   5863: }        
                   5864: 
                   5865: # see Lond::dump_with_regexp
                   5866: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5867: sub dump {
1.1180    droeschl 5868:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5869:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5870:     if (!$uname) { $uname=$env{'user.name'}; }
                   5871:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5872: 
1.1266    raeburn  5873:     if ($regexp) {
                   5874:         $regexp=&escape($regexp);
                   5875:     } else {
                   5876:         $regexp='.';
                   5877:     }
1.1180    droeschl 5878:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5879:         # user is hosted on this machine
1.1266    raeburn  5880:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5881:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5882:         return %{unserialize($reply, $escapedkeys)};
                   5883:     }
1.1166    raeburn  5884:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5885:     my @pairs=split(/\&/,$rep);
                   5886:     my %returnhash=();
1.1098    foxr     5887:     if (!($rep =~ /^error/ )) {
                   5888: 	foreach my $item (@pairs) {
                   5889: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5890:         $key = unescape($key) unless $escapedkeys;
                   5891:         #$key = &unescape($key);
1.1098    foxr     5892: 	    next if ($key =~ /^error: 2 /);
                   5893: 	    $returnhash{$key}=&thaw_unescape($value);
                   5894: 	}
1.755     albertel 5895:     }
                   5896:     return %returnhash;
1.407     www      5897: }
                   5898: 
1.1098    foxr     5899: 
1.717     albertel 5900: # --------------------------------------------------------- dumpstore interface
                   5901: 
                   5902: sub dumpstore {
                   5903:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5904:    # same as dump but keys must be escaped. They may contain colon separated
                   5905:    # lists of values that may themself contain colons (e.g. symbs).
                   5906:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5907: }
                   5908: 
1.407     www      5909: # -------------------------------------------------------------- keys interface
                   5910: 
                   5911: sub getkeys {
                   5912:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5913:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5914:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5915:    my $uhome=&homeserver($uname,$udomain);
                   5916:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5917:    my @keyarray=();
1.800     albertel 5918:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5919:       next if ($key =~ /^error: 2 /);
1.800     albertel 5920:       push(@keyarray,&unescape($key));
1.407     www      5921:    }
                   5922:    return @keyarray;
1.318     matthew  5923: }
                   5924: 
1.319     matthew  5925: # --------------------------------------------------------------- currentdump
                   5926: sub currentdump {
1.328     matthew  5927:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5928:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5929:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5930:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5931:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5932:    my $rep;
                   5933: 
                   5934:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5935:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5936:                    $courseid)));
                   5937:    } else {
                   5938:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5939:    }
                   5940: 
1.318     matthew  5941:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5942:    #
1.318     matthew  5943:    my %returnhash=();
1.319     matthew  5944:    #
                   5945:    if ($rep eq "unknown_cmd") { 
                   5946:        # an old lond will not know currentdump
                   5947:        # Do a dump and make it look like a currentdump
1.822     albertel 5948:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5949:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5950:        my %hash = @tmp;
                   5951:        @tmp=();
1.424     matthew  5952:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5953:    } else {
                   5954:        my @pairs=split(/\&/,$rep);
1.800     albertel 5955:        foreach my $pair (@pairs) {
                   5956:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5957:            my ($symb,$param) = split(/:/,$key);
                   5958:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5959:                                                         &thaw_unescape($value);
1.319     matthew  5960:        }
1.191     harris41 5961:    }
1.12      www      5962:    return %returnhash;
1.424     matthew  5963: }
                   5964: 
                   5965: sub convert_dump_to_currentdump{
                   5966:     my %hash = %{shift()};
                   5967:     my %returnhash;
                   5968:     # Code ripped from lond, essentially.  The only difference
                   5969:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5970:     # we might run in to problems with parameter names =~ /^v\./
                   5971:     while (my ($key,$value) = each(%hash)) {
                   5972:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5973: 	$symb  = &unescape($symb);
                   5974: 	$param = &unescape($param);
1.424     matthew  5975:         next if ($v eq 'version' || $symb eq 'keys');
                   5976:         next if (exists($returnhash{$symb}) &&
                   5977:                  exists($returnhash{$symb}->{$param}) &&
                   5978:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5979:         $returnhash{$symb}->{$param}=$value;
                   5980:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5981:     }
                   5982:     #
                   5983:     # Remove all of the keys in the hashes which keep track of
                   5984:     # the version of the parameter.
                   5985:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5986:         # use a foreach because we are going to delete from the hash.
                   5987:         foreach my $key (keys(%$param_hash)) {
                   5988:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5989:         }
                   5990:     }
                   5991:     return \%returnhash;
1.12      www      5992: }
                   5993: 
1.627     albertel 5994: # ------------------------------------------------------ critical inc interface
                   5995: 
                   5996: sub cinc {
                   5997:     return &inc(@_,'critical');
                   5998: }
                   5999: 
1.449     matthew  6000: # --------------------------------------------------------------- inc interface
                   6001: 
                   6002: sub inc {
1.627     albertel 6003:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6004:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6005:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6006:     my $uhome=&homeserver($uname,$udomain);
                   6007:     my $items='';
                   6008:     if (! ref($store)) {
                   6009:         # got a single value, so use that instead
                   6010:         $items = &escape($store).'=&';
                   6011:     } elsif (ref($store) eq 'SCALAR') {
                   6012:         $items = &escape($$store).'=&';        
                   6013:     } elsif (ref($store) eq 'ARRAY') {
                   6014:         $items = join('=&',map {&escape($_);} @{$store});
                   6015:     } elsif (ref($store) eq 'HASH') {
                   6016:         while (my($key,$value) = each(%{$store})) {
                   6017:             $items.= &escape($key).'='.&escape($value).'&';
                   6018:         }
                   6019:     }
                   6020:     $items=~s/\&$//;
1.627     albertel 6021:     if ($critical) {
                   6022: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6023:     } else {
                   6024: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6025:     }
1.449     matthew  6026: }
                   6027: 
1.12      www      6028: # --------------------------------------------------------------- put interface
                   6029: 
                   6030: sub put {
1.134     albertel 6031:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6032:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6033:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6034:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6035:    my $items='';
1.800     albertel 6036:    foreach my $item (keys(%$storehash)) {
                   6037:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6038:    }
1.12      www      6039:    $items=~s/\&$//;
1.134     albertel 6040:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6041: }
                   6042: 
1.631     albertel 6043: # ------------------------------------------------------------ newput interface
                   6044: 
                   6045: sub newput {
                   6046:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6047:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6048:    if (!$uname) { $uname=$env{'user.name'}; }
                   6049:    my $uhome=&homeserver($uname,$udomain);
                   6050:    my $items='';
                   6051:    foreach my $key (keys(%$storehash)) {
                   6052:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6053:    }
                   6054:    $items=~s/\&$//;
                   6055:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6056: }
                   6057: 
                   6058: # ---------------------------------------------------------  putstore interface
                   6059: 
1.524     raeburn  6060: sub putstore {
1.1269    raeburn  6061:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6062:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6063:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6064:    my $uhome=&homeserver($uname,$udomain);
                   6065:    my $items='';
1.715     albertel 6066:    foreach my $key (keys(%$storehash)) {
                   6067:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6068:    }
1.715     albertel 6069:    $items=~s/\&$//;
1.716     albertel 6070:    my $esc_symb=&escape($symb);
                   6071:    my $esc_v=&escape($version);
1.715     albertel 6072:    my $reply =
1.716     albertel 6073:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6074: 	      $uhome);
1.1269    raeburn  6075:    if (($tolog) && ($reply eq 'ok')) {
                   6076:        my $namevalue='';
                   6077:        foreach my $key (keys(%{$storehash})) {
                   6078:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6079:        }
                   6080:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6081:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6082:                      '&version='.$esc_v.
                   6083:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6084:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6085:    }
1.715     albertel 6086:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6087:        # gfall back to way things use to be done
1.715     albertel 6088:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6089: 			    $uname);
1.524     raeburn  6090:    }
1.715     albertel 6091:    return $reply;
                   6092: }
                   6093: 
                   6094: sub old_putstore {
1.716     albertel 6095:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6096:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6097:     if (!$uname) { $uname=$env{'user.name'}; }
                   6098:     my $uhome=&homeserver($uname,$udomain);
                   6099:     my %newstorehash;
1.800     albertel 6100:     foreach my $item (keys(%$storehash)) {
                   6101: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6102: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6103:     }
                   6104:     my $items='';
                   6105:     my %allitems = ();
1.800     albertel 6106:     foreach my $item (keys(%newstorehash)) {
                   6107: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6108: 	    my $key = $1.':keys:'.$2;
                   6109: 	    $allitems{$key} .= $3.':';
                   6110: 	}
1.800     albertel 6111: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6112:     }
1.800     albertel 6113:     foreach my $item (keys(%allitems)) {
                   6114: 	$allitems{$item} =~ s/\:$//;
                   6115: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6116:     }
                   6117:     $items=~s/\&$//;
                   6118:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6119: }
                   6120: 
1.47      www      6121: # ------------------------------------------------------ critical put interface
                   6122: 
                   6123: sub cput {
1.134     albertel 6124:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6125:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6126:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6127:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6128:    my $items='';
1.800     albertel 6129:    foreach my $item (keys(%$storehash)) {
                   6130:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6131:    }
1.47      www      6132:    $items=~s/\&$//;
1.134     albertel 6133:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6134: }
                   6135: 
                   6136: # -------------------------------------------------------------- eget interface
                   6137: 
                   6138: sub eget {
1.133     albertel 6139:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6140:    my $items='';
1.800     albertel 6141:    foreach my $item (@$storearr) {
                   6142:        $items.=&escape($item).'&';
1.191     harris41 6143:    }
1.12      www      6144:    $items=~s/\&$//;
1.620     albertel 6145:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6146:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6147:    my $uhome=&homeserver($uname,$udomain);
                   6148:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6149:    my @pairs=split(/\&/,$rep);
                   6150:    my %returnhash=();
1.42      www      6151:    my $i=0;
1.800     albertel 6152:    foreach my $item (@$storearr) {
                   6153:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6154:       $i++;
1.191     harris41 6155:    }
1.12      www      6156:    return %returnhash;
                   6157: }
                   6158: 
1.667     albertel 6159: # ------------------------------------------------------------ tmpput interface
                   6160: sub tmpput {
1.802     raeburn  6161:     my ($storehash,$server,$context)=@_;
1.667     albertel 6162:     my $items='';
1.800     albertel 6163:     foreach my $item (keys(%$storehash)) {
                   6164: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6165:     }
                   6166:     $items=~s/\&$//;
1.802     raeburn  6167:     if (defined($context)) {
                   6168:         $items .= ':'.&escape($context);
                   6169:     }
1.667     albertel 6170:     return &reply("tmpput:$items",$server);
                   6171: }
                   6172: 
                   6173: # ------------------------------------------------------------ tmpget interface
                   6174: sub tmpget {
1.688     albertel 6175:     my ($token,$server)=@_;
                   6176:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6177:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6178:     my %returnhash;
                   6179:     foreach my $item (split(/\&/,$rep)) {
                   6180: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6181:         next if ($key =~ /^error: 2 /);
1.667     albertel 6182: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6183:     }
                   6184:     return %returnhash;
                   6185: }
                   6186: 
1.1113    raeburn  6187: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6188: sub tmpdel {
                   6189:     my ($token,$server)=@_;
                   6190:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6191:     return &reply("tmpdel:$token",$server);
                   6192: }
                   6193: 
1.1198    raeburn  6194: # ------------------------------------------------------------ get_timebased_id 
                   6195: 
                   6196: sub get_timebased_id {
                   6197:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6198:         $maxtries) = @_;
                   6199:     my ($newid,$error,$dellock);
                   6200:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6201:         return ('','ok','invalid call to get suffix');
                   6202:     }
                   6203: 
                   6204: # set defaults for any optional args for which values were not supplied
                   6205:     if ($who eq '') {
                   6206:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6207:     }
                   6208:     if (!$locktries) {
                   6209:         $locktries = 3;
                   6210:     }
                   6211:     if (!$maxtries) {
                   6212:         $maxtries = 10;
                   6213:     }
                   6214:     
                   6215:     if (($cdom eq '') || ($cnum eq '')) {
                   6216:         if ($env{'request.course.id'}) {
                   6217:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6218:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6219:         }
                   6220:         if (($cdom eq '') || ($cnum eq '')) {
                   6221:             return ('','ok','call to get suffix not in course context');
                   6222:         }
                   6223:     }
                   6224: 
                   6225: # construct locking item
                   6226:     my $lockhash = {
                   6227:                       $prefix."\0".'locked_'.$keyid => $who,
                   6228:                    };
                   6229:     my $tries = 0;
                   6230: 
                   6231: # attempt to get lock on nohist_$namespace file
                   6232:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6233:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6234:         $tries ++;
                   6235:         sleep 1;
                   6236:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6237:     }
                   6238: 
                   6239: # attempt to get unique identifier, based on current timestamp
                   6240:     if ($gotlock eq 'ok') {
                   6241:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6242:         my $id = time;
                   6243:         $newid = $id;
1.1268    raeburn  6244:         if ($idtype eq 'addcode') {
                   6245:             $newid .= &sixnum_code();
                   6246:         }
1.1198    raeburn  6247:         my $idtries = 0;
                   6248:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6249:             if ($idtype eq 'concat') {
                   6250:                 $newid = $id.$idtries;
1.1268    raeburn  6251:             } elsif ($idtype eq 'addcode') {
                   6252:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6253:             } else {
                   6254:                 $newid ++;
                   6255:             }
                   6256:             $idtries ++;
                   6257:         }
                   6258:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6259:             my %new_item =  (
                   6260:                               $prefix."\0".$newid => $who,
                   6261:                             );
                   6262:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6263:                                                  $cdom,$cnum);
                   6264:             if ($putresult ne 'ok') {
                   6265:                 undef($newid);
                   6266:                 $error = 'error saving new item: '.$putresult;
                   6267:             }
                   6268:         } else {
1.1268    raeburn  6269:              undef($newid);
1.1198    raeburn  6270:              $error = ('error: no unique suffix available for the new item ');
                   6271:         }
                   6272: #  remove lock
                   6273:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6274:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6275:     } else {
                   6276:         $error = "error: could not obtain lockfile\n";
                   6277:         $dellock = 'ok';
1.1276    raeburn  6278:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6279:             $dellock = 'nolock';
                   6280:         }
1.1198    raeburn  6281:     }
                   6282:     return ($newid,$dellock,$error);
                   6283: }
                   6284: 
1.1268    raeburn  6285: sub sixnum_code {
                   6286:     my $code;
                   6287:     for (0..6) {
                   6288:         $code .= int( rand(9) );
                   6289:     }
                   6290:     return $code;
                   6291: }
                   6292: 
1.765     albertel 6293: # -------------------------------------------------- portfolio access checking
                   6294: 
                   6295: sub portfolio_access {
1.1270    raeburn  6296:     my ($requrl,$clientip) = @_;
1.765     albertel 6297:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6298:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6299:     if ($result) {
                   6300:         my %setters;
                   6301:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6302:             my ($startblock,$endblock) =
                   6303:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6304:             if ($startblock && $endblock) {
                   6305:                 return 'B';
                   6306:             }
                   6307:         } else {
                   6308:             my ($startblock,$endblock) =
                   6309:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6310:             if ($startblock && $endblock) {
                   6311:                 return 'B';
                   6312:             }
                   6313:         }
                   6314:     }
1.765     albertel 6315:     if ($result eq 'ok') {
1.766     albertel 6316:        return 'F';
1.765     albertel 6317:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6318:        return 'A';
1.765     albertel 6319:     }
1.766     albertel 6320:     return '';
1.765     albertel 6321: }
                   6322: 
                   6323: sub get_portfolio_access {
1.1270    raeburn  6324:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6325: 
                   6326:     if (!ref($access_hash)) {
                   6327: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6328: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6329: 						   $file_name);
                   6330: 	$access_hash = $access_controls{$file_name};
                   6331:     }
                   6332: 
1.1270    raeburn  6333:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6334:     my $now = time;
                   6335:     if (ref($access_hash) eq 'HASH') {
                   6336:         foreach my $key (keys(%{$access_hash})) {
                   6337:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6338:             if ($start > $now) {
                   6339:                 next;
                   6340:             }
                   6341:             if ($end && $end<$now) {
                   6342:                 next;
                   6343:             }
                   6344:             if ($scope eq 'public') {
                   6345:                 $public = $key;
                   6346:                 last;
                   6347:             } elsif ($scope eq 'guest') {
                   6348:                 $guest = $key;
                   6349:             } elsif ($scope eq 'domains') {
                   6350:                 push(@domains,$key);
                   6351:             } elsif ($scope eq 'users') {
                   6352:                 push(@users,$key);
                   6353:             } elsif ($scope eq 'course') {
                   6354:                 push(@courses,$key);
                   6355:             } elsif ($scope eq 'group') {
                   6356:                 push(@groups,$key);
1.1270    raeburn  6357:             } elsif ($scope eq 'ip') {
                   6358:                 push(@ips,$key);
1.765     albertel 6359:             }
                   6360:         }
                   6361:         if ($public) {
                   6362:             return 'ok';
1.1270    raeburn  6363:         } elsif (@ips > 0) {
                   6364:             my $allowed;
                   6365:             foreach my $ipkey (@ips) {
                   6366:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6367:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6368:                         $allowed = 1;
                   6369:                         last; 
                   6370:                     }
                   6371:                 }
                   6372:             }
                   6373:             if ($allowed) {
                   6374:                 return 'ok';
                   6375:             }
1.765     albertel 6376:         }
                   6377:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6378:             if ($guest) {
                   6379:                 return $guest;
                   6380:             }
                   6381:         } else {
                   6382:             if (@domains > 0) {
                   6383:                 foreach my $domkey (@domains) {
                   6384:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6385:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6386:                             return 'ok';
                   6387:                         }
                   6388:                     }
                   6389:                 }
                   6390:             }
                   6391:             if (@users > 0) {
                   6392:                 foreach my $userkey (@users) {
1.865     raeburn  6393:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6394:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6395:                             if (ref($item) eq 'HASH') {
                   6396:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6397:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6398:                                     return 'ok';
                   6399:                                 }
                   6400:                             }
                   6401:                         }
                   6402:                     } 
1.765     albertel 6403:                 }
                   6404:             }
                   6405:             my %roleshash;
                   6406:             my @courses_and_groups = @courses;
                   6407:             push(@courses_and_groups,@groups); 
                   6408:             if (@courses_and_groups > 0) {
                   6409:                 my (%allgroups,%allroles); 
                   6410:                 my ($start,$end,$role,$sec,$group);
                   6411:                 foreach my $envkey (%env) {
1.1060    raeburn  6412:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6413:                         my $cid = $2.'_'.$3; 
                   6414:                         if ($1 eq 'gr') {
                   6415:                             $group = $4;
                   6416:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6417:                         } else {
                   6418:                             if ($4 eq '') {
                   6419:                                 $sec = 'none';
                   6420:                             } else {
                   6421:                                 $sec = $4;
                   6422:                             }
                   6423:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6424:                         }
1.811     albertel 6425:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6426:                         my $cid = $2.'_'.$3;
                   6427:                         if ($4 eq '') {
                   6428:                             $sec = 'none';
                   6429:                         } else {
                   6430:                             $sec = $4;
                   6431:                         }
                   6432:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6433:                     }
                   6434:                 }
                   6435:                 if (keys(%allroles) == 0) {
                   6436:                     return;
                   6437:                 }
                   6438:                 foreach my $key (@courses_and_groups) {
                   6439:                     my %content = %{$$access_hash{$key}};
                   6440:                     my $cnum = $content{'number'};
                   6441:                     my $cdom = $content{'domain'};
                   6442:                     my $cid = $cdom.'_'.$cnum;
                   6443:                     if (!exists($allroles{$cid})) {
                   6444:                         next;
                   6445:                     }    
                   6446:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6447:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6448:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6449:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6450:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6451:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6452:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6453:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6454:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6455:                                         if (grep/^all$/,@sections) {
                   6456:                                             return 'ok';
                   6457:                                         } else {
                   6458:                                             if (grep/^$sec$/,@sections) {
                   6459:                                                 return 'ok';
                   6460:                                             }
                   6461:                                         }
                   6462:                                     }
                   6463:                                 }
                   6464:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6465:                                     if (grep/^none$/,@groups) {
                   6466:                                         return 'ok';
                   6467:                                     }
                   6468:                                 } else {
                   6469:                                     if (grep/^all$/,@groups) {
                   6470:                                         return 'ok';
                   6471:                                     } 
                   6472:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6473:                                         if (grep/^$group$/,@groups) {
                   6474:                                             return 'ok';
                   6475:                                         }
                   6476:                                     }
                   6477:                                 } 
                   6478:                             }
                   6479:                         }
                   6480:                     }
                   6481:                 }
                   6482:             }
                   6483:             if ($guest) {
                   6484:                 return $guest;
                   6485:             }
                   6486:         }
                   6487:     }
                   6488:     return;
                   6489: }
                   6490: 
                   6491: sub course_group_datechecker {
                   6492:     my ($dates,$now,$status) = @_;
                   6493:     my ($start,$end) = split(/\./,$dates);
                   6494:     if (!$start && !$end) {
                   6495:         return 'ok';
                   6496:     }
                   6497:     if (grep/^active$/,@{$status}) {
                   6498:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6499:             return 'ok';
                   6500:         }
                   6501:     }
                   6502:     if (grep/^previous$/,@{$status}) {
                   6503:         if ($end > $now ) {
                   6504:             return 'ok';
                   6505:         }
                   6506:     }
                   6507:     if (grep/^future$/,@{$status}) {
                   6508:         if ($start > $now) {
                   6509:             return 'ok';
                   6510:         }
                   6511:     }
                   6512:     return; 
                   6513: }
                   6514: 
                   6515: sub parse_portfolio_url {
                   6516:     my ($url) = @_;
                   6517: 
                   6518:     my ($type,$udom,$unum,$group,$file_name);
                   6519:     
1.823     albertel 6520:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6521: 	$type = 1;
                   6522:         $udom = $1;
                   6523:         $unum = $2;
                   6524:         $file_name = $3;
1.823     albertel 6525:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6526: 	$type = 2;
                   6527:         $udom = $1;
                   6528:         $unum = $2;
                   6529:         $group = $3;
                   6530:         $file_name = $3.'/'.$4;
                   6531:     }
                   6532:     if (wantarray) {
                   6533: 	return ($type,$udom,$unum,$file_name,$group);
                   6534:     }
                   6535:     return $type;
                   6536: }
                   6537: 
                   6538: sub is_portfolio_url {
                   6539:     my ($url) = @_;
                   6540:     return scalar(&parse_portfolio_url($url));
                   6541: }
                   6542: 
1.798     raeburn  6543: sub is_portfolio_file {
                   6544:     my ($file) = @_;
1.820     raeburn  6545:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6546:         return 1;
                   6547:     }
                   6548:     return;
                   6549: }
                   6550: 
1.976     raeburn  6551: sub usertools_access {
1.1084    raeburn  6552:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6553:     my ($access,%tools);
                   6554:     if ($context eq '') {
                   6555:         $context = 'tools';
                   6556:     }
                   6557:     if ($context eq 'requestcourses') {
                   6558:         %tools = (
                   6559:                       official   => 1,
                   6560:                       unofficial => 1,
1.1006    raeburn  6561:                       community  => 1,
1.1246    raeburn  6562:                       textbook   => 1,
1.1305    raeburn  6563:                       placement  => 1,
1.985     raeburn  6564:                  );
1.1183    raeburn  6565:     } elsif ($context eq 'requestauthor') {
                   6566:         %tools = (
                   6567:                       requestauthor => 1,
                   6568:                  );
1.985     raeburn  6569:     } else {
                   6570:         %tools = (
                   6571:                       aboutme   => 1,
                   6572:                       blog      => 1,
1.1177    raeburn  6573:                       webdav    => 1,
1.985     raeburn  6574:                       portfolio => 1,
                   6575:                  );
                   6576:     }
1.976     raeburn  6577:     return if (!defined($tools{$tool}));
                   6578: 
1.1242    raeburn  6579:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6580:         $udom = $env{'user.domain'};
                   6581:         $uname = $env{'user.name'};
                   6582:     }
                   6583: 
1.978     raeburn  6584:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6585:         if ($action ne 'reload') {
1.985     raeburn  6586:             if ($context eq 'requestcourses') {
                   6587:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6588:             } elsif ($context eq 'requestauthor') {
                   6589:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6590:             } else {
                   6591:                 return $env{'environment.availabletools.'.$tool};
                   6592:             }
                   6593:         }
1.976     raeburn  6594:     }
                   6595: 
1.1183    raeburn  6596:     my ($toolstatus,$inststatus,$envkey);
                   6597:     if ($context eq 'requestauthor') {
                   6598:         $envkey = $context; 
                   6599:     } else {
                   6600:         $envkey = $context.'.'.$tool;
                   6601:     }
1.976     raeburn  6602: 
1.985     raeburn  6603:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6604:          ($action ne 'reload')) {
1.1183    raeburn  6605:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6606:         $inststatus = $env{'environment.inststatus'};
                   6607:     } else {
1.1084    raeburn  6608:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6609:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6610:             $inststatus = $userenvref->{'inststatus'};
                   6611:         } else {
1.1183    raeburn  6612:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6613:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6614:             $inststatus = $userenv{'inststatus'};
                   6615:         }
1.976     raeburn  6616:     }
                   6617: 
                   6618:     if ($toolstatus ne '') {
                   6619:         if ($toolstatus) {
                   6620:             $access = 1;
                   6621:         } else {
                   6622:             $access = 0;
                   6623:         }
                   6624:         return $access;
                   6625:     }
                   6626: 
1.1084    raeburn  6627:     my ($is_adv,%domdef);
                   6628:     if (ref($is_advref) eq 'HASH') {
                   6629:         $is_adv = $is_advref->{'is_adv'};
                   6630:     } else {
                   6631:         $is_adv = &is_advanced_user($udom,$uname);
                   6632:     }
                   6633:     if (ref($domdefref) eq 'HASH') {
                   6634:         %domdef = %{$domdefref};
                   6635:     } else {
                   6636:         %domdef = &get_domain_defaults($udom);
                   6637:     }
1.976     raeburn  6638:     if (ref($domdef{$tool}) eq 'HASH') {
                   6639:         if ($is_adv) {
                   6640:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6641:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6642:                     $access = 1;
                   6643:                 } else {
                   6644:                     $access = 0;
                   6645:                 }
                   6646:                 return $access;
                   6647:             }
                   6648:         }
                   6649:         if ($inststatus ne '') {
                   6650:             my ($hasaccess,$hasnoaccess);
                   6651:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6652:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6653:                     if ($domdef{$tool}{$affiliation}) {
                   6654:                         $hasaccess = 1;
                   6655:                     } else {
                   6656:                         $hasnoaccess = 1;
                   6657:                     }
                   6658:                 }
                   6659:             }
                   6660:             if ($hasaccess || $hasnoaccess) {
                   6661:                 if ($hasaccess) {
                   6662:                     $access = 1;
                   6663:                 } elsif ($hasnoaccess) {
                   6664:                     $access = 0; 
                   6665:                 }
                   6666:                 return $access;
                   6667:             }
                   6668:         } else {
                   6669:             if ($domdef{$tool}{'default'} ne '') {
                   6670:                 if ($domdef{$tool}{'default'}) {
                   6671:                     $access = 1;
                   6672:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6673:                     $access = 0;
                   6674:                 }
                   6675:                 return $access;
                   6676:             }
                   6677:         }
                   6678:     } else {
1.1177    raeburn  6679:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6680:             $access = 1;
                   6681:         } else {
                   6682:             $access = 0;
                   6683:         }
1.976     raeburn  6684:         return $access;
                   6685:     }
                   6686: }
                   6687: 
1.1050    raeburn  6688: sub is_course_owner {
                   6689:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6690:     if (($udom eq '') || ($uname eq '')) {
                   6691:         $udom = $env{'user.domain'};
                   6692:         $uname = $env{'user.name'};
                   6693:     }
                   6694:     unless (($udom eq '') || ($uname eq '')) {
                   6695:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6696:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6697:                 return 1;
                   6698:             } else {
                   6699:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6700:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6701:                     return 1;
                   6702:                 }
                   6703:             }
                   6704:         }
                   6705:     }
                   6706:     return;
                   6707: }
                   6708: 
1.976     raeburn  6709: sub is_advanced_user {
                   6710:     my ($udom,$uname) = @_;
1.1085    raeburn  6711:     if ($udom ne '' && $uname ne '') {
                   6712:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6713:             if (wantarray) {
                   6714:                 return ($env{'user.adv'},$env{'user.author'});
                   6715:             } else {
                   6716:                 return $env{'user.adv'};
                   6717:             }
1.1085    raeburn  6718:         }
                   6719:     }
1.976     raeburn  6720:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6721:     my %allroles;
1.1128    raeburn  6722:     my ($is_adv,$is_author);
1.976     raeburn  6723:     foreach my $role (keys(%roleshash)) {
                   6724:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6725:         my $area = '/'.$tdomain.'/'.$trest;
                   6726:         if ($sec ne '') {
                   6727:             $area .= '/'.$sec;
                   6728:         }
                   6729:         if (($area ne '') && ($trole ne '')) {
                   6730:             my $spec=$trole.'.'.$area;
                   6731:             if ($trole =~ /^cr\//) {
                   6732:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6733:             } elsif ($trole ne 'gr') {
                   6734:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6735:             }
1.1128    raeburn  6736:             if ($trole eq 'au') {
                   6737:                 $is_author = 1;
                   6738:             }
1.976     raeburn  6739:         }
                   6740:     }
                   6741:     foreach my $role (keys(%allroles)) {
                   6742:         last if ($is_adv);
                   6743:         foreach my $item (split(/:/,$allroles{$role})) {
                   6744:             if ($item ne '') {
                   6745:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6746:                 if ($privilege eq 'adv') {
                   6747:                     $is_adv = 1;
                   6748:                     last;
                   6749:                 }
                   6750:             }
                   6751:         }
                   6752:     }
1.1128    raeburn  6753:     if (wantarray) {
                   6754:         return ($is_adv,$is_author);
                   6755:     }
1.976     raeburn  6756:     return $is_adv;
                   6757: }
1.798     raeburn  6758: 
1.1035    raeburn  6759: sub check_can_request {
1.1036    raeburn  6760:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6761:     my $canreq = 0;
                   6762:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6763:     my @options = ('approval','validate','autolimit');
                   6764:     my $optregex = join('|',@options);
                   6765:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6766:         foreach my $type (@{$types}) {
                   6767:             if (&usertools_access($env{'user.name'},
                   6768:                                   $env{'user.domain'},
                   6769:                                   $type,undef,'requestcourses')) {
                   6770:                 $canreq ++;
1.1036    raeburn  6771:                 if (ref($request_domains) eq 'HASH') {
                   6772:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6773:                 }
1.1035    raeburn  6774:                 if ($dom eq $env{'user.domain'}) {
                   6775:                     $can_request->{$type} = 1;
                   6776:                 }
                   6777:             }
                   6778:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6779:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6780:                 if (@curr > 0) {
1.1036    raeburn  6781:                     foreach my $item (@curr) {
                   6782:                         if (ref($request_domains) eq 'HASH') {
                   6783:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6784:                             if ($otherdom ne '') {
                   6785:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6786:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6787:                                         push(@{$request_domains->{$type}},$otherdom);
                   6788:                                     }
                   6789:                                 } else {
                   6790:                                     push(@{$request_domains->{$type}},$otherdom);
                   6791:                                 }
                   6792:                             }
                   6793:                         }
                   6794:                     }
                   6795:                     unless($dom eq $env{'user.domain'}) {
                   6796:                         $canreq ++;
1.1035    raeburn  6797:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6798:                             $can_request->{$type} = 1;
                   6799:                         }
                   6800:                     }
                   6801:                 }
                   6802:             }
                   6803:         }
                   6804:     }
                   6805:     return $canreq;
                   6806: }
                   6807: 
1.341     www      6808: # ---------------------------------------------- Custom access rule evaluation
                   6809: 
                   6810: sub customaccess {
                   6811:     my ($priv,$uri)=@_;
1.807     albertel 6812:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6813:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6814:     $udom = &LONCAPA::clean_domain($udom);
                   6815:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6816:     my $access=0;
1.800     albertel 6817:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6818: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6819: 	if ($type eq 'user') {
                   6820: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6821: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6822: 		if ($tdom) {
                   6823: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6824: 		}
1.896     albertel 6825: 		if ($tuname) {
                   6826: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6827: 		}
                   6828: 		$access=($effect eq 'allow');
                   6829: 		last;
                   6830: 	    }
                   6831: 	} else {
                   6832: 	    if ($role) {
                   6833: 		if ($role ne $urole) { next; }
                   6834: 	    }
                   6835: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6836: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6837: 		if ($tdom) {
                   6838: 		    if ($tdom ne $udom) { next; }
                   6839: 		}
                   6840: 		if ($tcrs) {
                   6841: 		    if ($tcrs ne $ucrs) { next; }
                   6842: 		}
                   6843: 		if ($tsec) {
                   6844: 		    if ($tsec ne $usec) { next; }
                   6845: 		}
                   6846: 		$access=($effect eq 'allow');
                   6847: 		last;
                   6848: 	    }
                   6849: 	    if ($realm eq '' && $role eq '') {
                   6850: 		$access=($effect eq 'allow');
                   6851: 	    }
1.402     bowersj2 6852: 	}
1.341     www      6853:     }
                   6854:     return $access;
                   6855: }
                   6856: 
1.103     harris41 6857: # ------------------------------------------------- Check for a user privilege
1.12      www      6858: 
                   6859: sub allowed {
1.1281    raeburn  6860:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 6861:     my $ver_orguri=$uri;
1.439     www      6862:     $uri=&deversion($uri);
1.152     www      6863:     my $orguri=$uri;
1.52      www      6864:     $uri=&declutter($uri);
1.809     raeburn  6865: 
1.810     raeburn  6866:     if ($priv eq 'evb') {
                   6867: # Evade communication block restrictions for specified role in a course
                   6868:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6869:             return $1;
                   6870:         } else {
                   6871:             return;
                   6872:         }
                   6873:     }
                   6874: 
1.620     albertel 6875:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6876: # Free bre access to adm and meta resources
1.775     albertel 6877:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6878: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6879: 	&& ($priv eq 'bre')) {
1.14      www      6880: 	return 'F';
1.159     www      6881:     }
                   6882: 
1.545     banghart 6883: # Free bre access to user's own portfolio contents
1.714     raeburn  6884:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6885:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6886: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6887:         my %setters;
                   6888:         my ($startblock,$endblock) = 
                   6889:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6890:         if ($startblock && $endblock) {
                   6891:             return 'B';
                   6892:         } else {
                   6893:             return 'F';
                   6894:         }
1.545     banghart 6895:     }
                   6896: 
1.762     raeburn  6897: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6898:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6899:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6900:         if (exists($env{'request.course.id'})) {
                   6901:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6902:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6903:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6904:                 my $courseprivid=$env{'request.course.id'};
                   6905:                 $courseprivid=~s/\_/\//;
                   6906:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6907:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6908:                     return $1; 
1.762     raeburn  6909:                 } else {
                   6910:                     if ($env{'request.course.sec'}) {
                   6911:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6912:                     }
                   6913:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6914:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6915:                         return $2;
                   6916:                     }
1.714     raeburn  6917:                 }
                   6918:             }
                   6919:         }
                   6920:     }
                   6921: 
1.159     www      6922: # Free bre to public access
                   6923: 
                   6924:     if ($priv eq 'bre') {
1.238     www      6925:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6926: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6927:            return 'F'; 
                   6928:         }
1.238     www      6929:         if ($copyright eq 'priv') {
                   6930:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6931: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6932: 		return '';
                   6933:             }
                   6934:         }
                   6935:         if ($copyright eq 'domain') {
                   6936:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6937: 	    unless (($env{'user.domain'} eq $1) ||
                   6938:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6939: 		return '';
                   6940:             }
1.262     matthew  6941:         }
1.620     albertel 6942:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6943:             # Library role, so allow browsing of resources in this domain.
                   6944:             return 'F';
1.238     www      6945:         }
1.341     www      6946:         if ($copyright eq 'custom') {
                   6947: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6948:         }
1.14      www      6949:     }
1.264     matthew  6950:     # Domain coordinator is trying to create a course
1.620     albertel 6951:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6952:         # uri is the requested domain in this case.
                   6953:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6954:         # a role of dc for the domain in question.
1.620     albertel 6955:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6956:     }
1.29      www      6957: 
1.52      www      6958:     my $thisallowed='';
                   6959:     my $statecond=0;
                   6960:     my $courseprivid='';
                   6961: 
1.1039    raeburn  6962:     my $ownaccess;
1.1043    raeburn  6963:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6964:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6965:         if ($uri eq '') {
                   6966:             $ownaccess = 1;
                   6967:         } else {
                   6968:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6969:                 my $udom = $env{'user.domain'};
                   6970:                 my $uname = $env{'user.name'};
                   6971:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6972:                     $ownaccess = 1;
1.1040    raeburn  6973:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6974:                     unless ($uri =~ m{\.\./}) {
                   6975:                         $ownaccess = 1;
                   6976:                     }
                   6977:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6978:                     my $now = time;
                   6979:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6980:                         my $adom = $1;
                   6981:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6982:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6983:                                 my ($start,$end) = split('.',$env{$key});
                   6984:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6985:                                     $ownaccess = 1;
                   6986:                                     last;
                   6987:                                 }
                   6988:                             }
                   6989:                         }
                   6990:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6991:                         my $adom = $1;
                   6992:                         my $aname = $2;
1.1042    raeburn  6993:                         foreach my $role ('ca','aa') { 
                   6994:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6995:                                 my ($start,$end) =
                   6996:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6997:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6998:                                     $ownaccess = 1;
                   6999:                                     last;
                   7000:                                 }
1.1039    raeburn  7001:                             }
                   7002:                         }
                   7003:                     }
                   7004:                 }
                   7005:             }
                   7006:         }
                   7007:     }
                   7008: 
1.52      www      7009: # Course
                   7010: 
1.620     albertel 7011:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7012:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7013:             $thisallowed.=$1;
                   7014:         }
1.52      www      7015:     }
1.29      www      7016: 
1.52      www      7017: # Domain
                   7018: 
1.620     albertel 7019:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7020:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7021:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7022:             $thisallowed.=$1;
                   7023:         }
1.12      www      7024:     }
1.52      www      7025: 
1.1141    raeburn  7026: # User who is not author or co-author might still be able to edit
                   7027: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7028:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7029:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7030:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7031:             $thisallowed.=$1;
                   7032:         }
                   7033:     }
                   7034: 
1.52      www      7035: # Course: uri itself is a course
1.66      www      7036:     my $courseuri=$uri;
                   7037:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7038:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7039: 
1.620     albertel 7040:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7041:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7042:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7043:             $thisallowed.=$1;
                   7044:         }
1.12      www      7045:     }
1.29      www      7046: 
1.665     albertel 7047: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7048: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7049:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7050: 	$thisallowed='';
1.671     raeburn  7051:         my ($match)=&is_on_map($uri);
                   7052:         if ($match) {
                   7053:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7054:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7055:                 my $value = $1;
                   7056:                 if ($noblockcheck) {
                   7057:                     $thisallowed.=$value;
1.1162    raeburn  7058:                 } else {
1.1281    raeburn  7059:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7060:                     if (@blockers > 0) {
                   7061:                         $thisallowed = 'B';
                   7062:                     } else {
                   7063:                         $thisallowed.=$value;
                   7064:                     }
1.1162    raeburn  7065:                 }
1.671     raeburn  7066:             }
                   7067:         } else {
1.705     albertel 7068:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7069:             if ($refuri) {
                   7070:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7071:                     $thisallowed='F';
1.671     raeburn  7072:                 } else {
                   7073:                     $refuri=&declutter($refuri);
                   7074:                     my ($match) = &is_on_map($refuri);
                   7075:                     if ($match) {
1.1281    raeburn  7076:                         if ($noblockcheck) {
                   7077:                             $thisallowed='F';
1.1162    raeburn  7078:                         } else {
1.1281    raeburn  7079:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7080:                             if (@blockers > 0) {
                   7081:                                 $thisallowed = 'B';
                   7082:                             } else {
                   7083:                                 $thisallowed='F';
                   7084:                             }
1.1162    raeburn  7085:                         }
1.671     raeburn  7086:                     }
1.669     raeburn  7087:                 }
1.671     raeburn  7088:             }
                   7089:         }
1.314     www      7090:     }
1.492     albertel 7091: 
1.766     albertel 7092:     if ($priv eq 'bre'
                   7093: 	&& $thisallowed ne 'F' 
                   7094: 	&& $thisallowed ne '2'
                   7095: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7096: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7097:     }
1.1250    raeburn  7098: 
1.52      www      7099: # Full access at system, domain or course-wide level? Exit.
1.29      www      7100:     if ($thisallowed=~/F/) {
                   7101: 	return 'F';
                   7102:     }
                   7103: 
1.52      www      7104: # If this is generating or modifying users, exit with special codes
1.29      www      7105: 
1.643     www      7106:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7107: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7108: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7109: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7110: 	    unless ($auname) { return $thisallowed; }
                   7111: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7112: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7113: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7114: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7115: 	}
1.52      www      7116: 	return $thisallowed;
                   7117:     }
                   7118: #
1.103     harris41 7119: # Gathered so far: system, domain and course wide privileges
1.52      www      7120: #
                   7121: # Course: See if uri or referer is an individual resource that is part of 
                   7122: # the course
                   7123: 
1.620     albertel 7124:     if ($env{'request.course.id'}) {
1.232     www      7125: 
1.620     albertel 7126:        $courseprivid=$env{'request.course.id'};
                   7127:        if ($env{'request.course.sec'}) {
                   7128:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7129:        }
                   7130:        $courseprivid=~s/\_/\//;
                   7131:        my $checkreferer=1;
1.232     www      7132:        my ($match,$cond)=&is_on_map($uri);
                   7133:        if ($match) {
                   7134:            $statecond=$cond;
1.620     albertel 7135:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7136:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7137:                my $value = $1;
                   7138:                if ($priv eq 'bre') {
1.1281    raeburn  7139:                    if ($noblockcheck) {
                   7140:                        $thisallowed.=$value;
1.1162    raeburn  7141:                    } else {
1.1281    raeburn  7142:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7143:                        if (@blockers > 0) {
                   7144:                            $thisallowed = 'B';
                   7145:                        } else {
                   7146:                            $thisallowed.=$value;
                   7147:                        }
1.1162    raeburn  7148:                    }
                   7149:                } else {
                   7150:                    $thisallowed.=$value;
                   7151:                }
1.52      www      7152:                $checkreferer=0;
                   7153:            }
1.29      www      7154:        }
1.83      www      7155:        
1.148     www      7156:        if ($checkreferer) {
1.620     albertel 7157: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7158:             unless ($refuri) {
1.800     albertel 7159:                 foreach my $key (keys(%env)) {
                   7160: 		    if ($key=~/^httpref\..*\*/) {
                   7161: 			my $pattern=$key;
1.156     www      7162:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7163:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7164:                         $pattern=~s/\//\\\//g;
1.152     www      7165:                         if ($orguri=~/$pattern/) {
1.800     albertel 7166: 			    $refuri=$env{$key};
1.148     www      7167:                         }
                   7168:                     }
1.191     harris41 7169:                 }
1.148     www      7170:             }
1.232     www      7171: 
1.148     www      7172:          if ($refuri) { 
1.152     www      7173: 	  $refuri=&declutter($refuri);
1.232     www      7174:           my ($match,$cond)=&is_on_map($refuri);
                   7175:             if ($match) {
                   7176:               my $refstatecond=$cond;
1.620     albertel 7177:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7178:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7179:                   my $value = $1;
                   7180:                   if ($priv eq 'bre') {
1.1281    raeburn  7181:                       if ($noblockcheck) {
                   7182:                           $thisallowed.=$value;
1.1162    raeburn  7183:                       } else {
1.1281    raeburn  7184:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7185:                           if (@blockers > 0) {
                   7186:                               $thisallowed = 'B';
                   7187:                           } else {
                   7188:                               $thisallowed.=$value;
                   7189:                           }
1.1162    raeburn  7190:                       }
                   7191:                   } else {
                   7192:                       $thisallowed.=$value;
                   7193:                   }
1.53      www      7194:                   $uri=$refuri;
                   7195:                   $statecond=$refstatecond;
1.52      www      7196:               }
                   7197:           }
1.148     www      7198:         }
1.29      www      7199:        }
1.52      www      7200:    }
1.29      www      7201: 
1.52      www      7202: #
1.103     harris41 7203: # Gathered now: all privileges that could apply, and condition number
1.52      www      7204: # 
                   7205: #
                   7206: # Full or no access?
                   7207: #
1.29      www      7208: 
1.52      www      7209:     if ($thisallowed=~/F/) {
                   7210: 	return 'F';
                   7211:     }
1.29      www      7212: 
1.52      www      7213:     unless ($thisallowed) {
                   7214:         return '';
                   7215:     }
1.29      www      7216: 
1.52      www      7217: # Restrictions exist, deal with them
                   7218: #
                   7219: #   C:according to course preferences
                   7220: #   R:according to resource settings
                   7221: #   L:unless locked
                   7222: #   X:according to user session state
                   7223: #
                   7224: 
                   7225: # Possibly locked functionality, check all courses
1.54      www      7226: # Locks might take effect only after 10 minutes cache expiration for other
                   7227: # courses, and 2 minutes for current course
1.52      www      7228: 
                   7229:     my $envkey;
                   7230:     if ($thisallowed=~/L/) {
1.1000    raeburn  7231:         foreach $envkey (keys(%env)) {
1.54      www      7232:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7233:                my $courseid=$2;
                   7234:                my $roleid=$1.'.'.$2;
1.92      www      7235:                $courseid=~s/^\///;
1.54      www      7236:                my $expiretime=600;
1.620     albertel 7237:                if ($env{'request.role'} eq $roleid) {
1.54      www      7238: 		  $expiretime=120;
                   7239:                }
                   7240: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7241:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7242:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7243: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7244:                }
1.620     albertel 7245:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7246:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7247: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7248:                        &log($env{'user.domain'},$env{'user.name'},
                   7249:                             $env{'user.home'},
1.57      www      7250:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7251:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7252:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7253: 		       return '';
                   7254:                    }
                   7255:                }
1.620     albertel 7256:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7257:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7258: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7259:                        &log($env{'user.domain'},$env{'user.name'},
                   7260:                             $env{'user.home'},
1.57      www      7261:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7262:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7263:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7264: 		       return '';
                   7265:                    }
                   7266:                }
                   7267: 	   }
1.29      www      7268:        }
1.52      www      7269:     }
                   7270:    
                   7271: #
                   7272: # Rest of the restrictions depend on selected course
                   7273: #
                   7274: 
1.620     albertel 7275:     unless ($env{'request.course.id'}) {
1.766     albertel 7276: 	if ($thisallowed eq 'A') {
                   7277: 	    return 'A';
1.814     raeburn  7278:         } elsif ($thisallowed eq 'B') {
                   7279:             return 'B';
1.766     albertel 7280: 	} else {
                   7281: 	    return '1';
                   7282: 	}
1.52      www      7283:     }
1.29      www      7284: 
1.52      www      7285: #
                   7286: # Now user is definitely in a course
                   7287: #
1.53      www      7288: 
                   7289: 
                   7290: # Course preferences
                   7291: 
                   7292:    if ($thisallowed=~/C/) {
1.620     albertel 7293:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7294:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7295:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7296: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7297: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7298: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7299: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7300: 			$env{'request.course.id'});
                   7301: 	   }
1.237     www      7302:            return '';
                   7303:        }
                   7304: 
1.620     albertel 7305:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7306: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7307: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7308: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7309: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7310: 			$env{'request.course.id'});
                   7311: 	   }
1.54      www      7312:            return '';
                   7313:        }
1.53      www      7314:    }
                   7315: 
                   7316: # Resource preferences
                   7317: 
                   7318:    if ($thisallowed=~/R/) {
1.620     albertel 7319:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7320:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7321: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7322: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7323: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7324: 	   }
                   7325: 	   return '';
1.54      www      7326:        }
1.53      www      7327:    }
1.30      www      7328: 
1.246     www      7329: # Restricted by state or randomout?
1.30      www      7330: 
1.52      www      7331:    if ($thisallowed=~/X/) {
1.620     albertel 7332:       if ($env{'acc.randomout'}) {
1.579     albertel 7333: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7334:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7335:             return ''; 
                   7336:          }
1.247     www      7337:       }
                   7338:       if (&condval($statecond)) {
1.52      www      7339: 	 return '2';
                   7340:       } else {
                   7341:          return '';
                   7342:       }
                   7343:    }
1.30      www      7344: 
1.766     albertel 7345:     if ($thisallowed eq 'A') {
                   7346: 	return 'A';
1.814     raeburn  7347:     } elsif ($thisallowed eq 'B') {
                   7348:         return 'B';
1.766     albertel 7349:     }
1.52      www      7350:    return 'F';
1.232     www      7351: }
1.1162    raeburn  7352: 
1.1192    raeburn  7353: # ------------------------------------------- Check construction space access
                   7354: 
                   7355: sub constructaccess {
                   7356:     my ($url,$setpriv)=@_;
                   7357: 
                   7358: # We do not allow editing of previous versions of files
                   7359:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7360: 
                   7361: # Get username and domain from URL
                   7362:     my ($ownername,$ownerdomain,$ownerhome);
                   7363: 
                   7364:     ($ownerdomain,$ownername) =
1.1297    damieng  7365:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)/});
1.1192    raeburn  7366: 
                   7367: # The URL does not really point to any authorspace, forget it
                   7368:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7369: 
                   7370: # Now we need to see if the user has access to the authorspace of
                   7371: # $ownername at $ownerdomain
                   7372: 
                   7373:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7374: # Real author for this?
                   7375:        $ownerhome = $env{'user.home'};
                   7376:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7377:           return ($ownername,$ownerdomain,$ownerhome);
                   7378:        }
                   7379:     } else {
                   7380: # Co-author for this?
                   7381:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7382:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7383:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7384:             return ($ownername,$ownerdomain,$ownerhome);
                   7385:         }
1.1312    raeburn  7386:         if ($env{'request.course.id'}) {
                   7387:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   7388:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   7389:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   7390:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   7391:                     return ($ownername,$ownerdomain,$ownerhome);
                   7392:                 }
                   7393:             }
                   7394:         }
1.1192    raeburn  7395:     }
                   7396: 
                   7397: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7398: # we might as well leave
                   7399:    unless ($setpriv) { return ''; }
                   7400: 
                   7401: # Backdoor access?
                   7402:     my $allowed=&allowed('eco',$ownerdomain);
                   7403: # Nope
                   7404:     unless ($allowed) { return ''; }
                   7405: # Looks like we may have access, but could be locked by the owner of the construction space
                   7406:     if ($allowed eq 'U') {
                   7407:         my %blocked=&get('environment',['domcoord.author'],
                   7408:                          $ownerdomain,$ownername);
                   7409: # Is blocked by owner
                   7410:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7411:     }
                   7412:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7413: # Grant temporary access
                   7414:         my $then=$env{'user.login.time'};
1.1209    raeburn  7415:         my $update=$env{'user.update.time'};
1.1192    raeburn  7416:         if (!$update) { $update = $then; }
                   7417:         my $refresh=$env{'user.refresh.time'};
                   7418:         if (!$refresh) { $refresh = $update; }
                   7419:         my $now = time;
                   7420:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7421:                            $now,'ca','constructaccess');
                   7422:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7423:         return($ownername,$ownerdomain,$ownerhome);
                   7424:     }
                   7425: # No business here
                   7426:     return '';
                   7427: }
                   7428: 
1.1282    raeburn  7429: # ----------------------------------------------------------- Content Blocking
                   7430: 
                   7431: {
                   7432: # Caches for faster Course Contents display where content blocking
                   7433: # is in operation (i.e., interval param set) for timed quiz.
                   7434: #
                   7435: # User for whom data are being temporarily cached.
                   7436: my $cacheduser='';
                   7437: # Cached blockers for this user (a hash of blocking items). 
                   7438: my %cachedblockers=();
                   7439: # When the data were last cached.
                   7440: my $cachedlast='';
                   7441: 
                   7442: sub load_all_blockers {
                   7443:     my ($uname,$udom,$blocks)=@_;
                   7444:     if (($uname ne '') && ($udom ne '')) { 
                   7445:         if (($cacheduser eq $uname.':'.$udom) &&
                   7446:             (abs($cachedlast-time)<5)) {
                   7447:             return;
                   7448:         }
                   7449:     }
                   7450:     $cachedlast=time;
                   7451:     $cacheduser=$uname.':'.$udom;
                   7452:     %cachedblockers = &get_commblock_resources($blocks);
                   7453: }
                   7454: 
1.1162    raeburn  7455: sub get_comm_blocks {
                   7456:     my ($cdom,$cnum) = @_;
                   7457:     if ($cdom eq '' || $cnum eq '') {
                   7458:         return unless ($env{'request.course.id'});
                   7459:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7460:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7461:     }
                   7462:     my %commblocks;
                   7463:     my $hashid=$cdom.'_'.$cnum;
                   7464:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7465:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7466:         %commblocks = %{$blocksref};
                   7467:     } else {
                   7468:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7469:         my $cachetime = 600;
                   7470:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7471:     }
                   7472:     return %commblocks;
                   7473: }
                   7474: 
1.1282    raeburn  7475: sub get_commblock_resources {
                   7476:     my ($blocks) = @_;
                   7477:     my %blockers = ();
                   7478:     return %blockers unless ($env{'request.course.id'});
                   7479:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7480:     my %commblocks;
                   7481:     if (ref($blocks) eq 'HASH') {
                   7482:         %commblocks = %{$blocks};
                   7483:     } else {
                   7484:         %commblocks = &get_comm_blocks();
                   7485:     }
1.1282    raeburn  7486:     return %blockers unless (keys(%commblocks) > 0); 
                   7487:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7488:     return %blockers unless (ref($navmap));
1.1162    raeburn  7489:     my $now = time;
                   7490:     foreach my $block (keys(%commblocks)) {
                   7491:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7492:             my ($start,$end) = ($1,$2);
                   7493:             if ($start <= $now && $end >= $now) {
                   7494:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7495:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7496:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  7497:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7498:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  7499:                             }
                   7500:                         }
                   7501:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  7502:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7503:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7504:                             }
                   7505:                         }
                   7506:                     }
                   7507:                 }
                   7508:             }
                   7509:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7510:             my $item = $1;
1.1163    raeburn  7511:             my @to_test;
1.1162    raeburn  7512:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7513:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  7514:                     my @interval;
                   7515:                     my $type = 'map';
                   7516:                     if ($item eq 'course') {
                   7517:                         $type = 'course';
                   7518:                         @interval=&EXT("resource.0.interval");
                   7519:                     } else {
                   7520:                         if ($item =~ /___\d+___/) {
                   7521:                             $type = 'resource';
                   7522:                             @interval=&EXT("resource.0.interval",$item);
                   7523:                             if (ref($navmap)) {                        
                   7524:                                 my $res = $navmap->getBySymb($item); 
                   7525:                                 push(@to_test,$res);
                   7526:                             }
1.1162    raeburn  7527:                         } else {
1.1282    raeburn  7528:                             my $mapsymb = &symbread($item,1);
                   7529:                             if ($mapsymb) {
                   7530:                                 if (ref($navmap)) {
                   7531:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7532:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7533:                                     foreach my $res (@to_test) {
                   7534:                                         my $symb = $res->symb();
                   7535:                                         next if ($symb eq $mapsymb);
                   7536:                                         if ($symb ne '') {
                   7537:                                             @interval=&EXT("resource.0.interval",$symb);
                   7538:                                             if ($interval[1] eq 'map') {
                   7539:                                                 last;
1.1162    raeburn  7540:                                             }
                   7541:                                         }
                   7542:                                     }
                   7543:                                 }
                   7544:                             }
                   7545:                         }
1.1282    raeburn  7546:                     }
1.1310    raeburn  7547:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  7548:                         my $timelimit = $1; 
1.1282    raeburn  7549:                         my $first_access;
                   7550:                         if ($type eq 'resource') {
                   7551:                             $first_access=&get_first_access($interval[1],$item);
                   7552:                         } elsif ($type eq 'map') {
                   7553:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7554:                         } else {
                   7555:                             $first_access=&get_first_access($interval[1]);
                   7556:                         }
                   7557:                         if ($first_access) {
1.1292    raeburn  7558:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  7559:                             if ($timesup > $now) {
                   7560:                                 my $activeblock;
                   7561:                                 foreach my $res (@to_test) {
1.1283    raeburn  7562:                                     if ($res->answerable()) {
1.1282    raeburn  7563:                                         $activeblock = 1;
                   7564:                                         last;
                   7565:                                     }
                   7566:                                 }
                   7567:                                 if ($activeblock) {
                   7568:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7569:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7570:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7571:                                          }
                   7572:                                     }
                   7573:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7574:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7575:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7576:                                         }
1.1162    raeburn  7577:                                     }
                   7578:                                 }
                   7579:                             }
                   7580:                         }
                   7581:                     }
                   7582:                 }
                   7583:             }
                   7584:         }
                   7585:     }
1.1282    raeburn  7586:     return %blockers;
1.1162    raeburn  7587: }
                   7588: 
1.1282    raeburn  7589: sub has_comm_blocking {
                   7590:     my ($priv,$symb,$uri,$blocks) = @_;
                   7591:     my @blockers;
                   7592:     return unless ($env{'request.course.id'});
                   7593:     return unless ($priv eq 'bre');
                   7594:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7595:     return if ($env{'request.state'} eq 'construct');
                   7596:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7597:     return unless (keys(%cachedblockers) > 0);
                   7598:     my (%possibles,@symbs);
                   7599:     if (!$symb) {
                   7600:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7601:     }
1.1282    raeburn  7602:     if ($symb) {
                   7603:         @symbs = ($symb);
                   7604:     } elsif (keys(%possibles)) { 
                   7605:         @symbs = keys(%possibles);
                   7606:     }
                   7607:     my $noblock;
                   7608:     foreach my $symb (@symbs) {
                   7609:         last if ($noblock);
                   7610:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7611:         foreach my $block (keys(%cachedblockers)) {
                   7612:             if ($block =~ /^firstaccess____(.+)$/) {
                   7613:                 my $item = $1;
                   7614:                 if (($item eq $map) || ($item eq $symb)) {
                   7615:                     $noblock = 1;
                   7616:                     last;
                   7617:                 }
                   7618:             }
                   7619:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7620:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7621:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7622:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7623:                             push(@blockers,$block);
                   7624:                         }
                   7625:                     }
                   7626:                 }
1.1162    raeburn  7627:             }
1.1282    raeburn  7628:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7629:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7630:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7631:                         push(@blockers,$block);
                   7632:                     }
                   7633:                 }
1.1162    raeburn  7634:             }
                   7635:         }
                   7636:     }
1.1282    raeburn  7637:     return if ($noblock);
                   7638:     return @blockers;
                   7639: }
1.1162    raeburn  7640: }
                   7641: 
1.1282    raeburn  7642: # -------------------------------- Deversion and split uri into path an filename   
                   7643: 
1.1133    foxr     7644: #
1.1282    raeburn  7645: #   Removes the version from a URI and
1.1133    foxr     7646: #   splits it in to its filename and path to the filename.
                   7647: #   Seems like File::Basename could have done this more clearly.
                   7648: #   Parameters:
                   7649: #      $uri   - input URI
                   7650: #   Returns:
                   7651: #     Two element list consisting of 
                   7652: #     $pathname  - the URI up to and excluding the trailing /
                   7653: #     $filename  - The part of the URI following the last /
                   7654: #  NOTE:
                   7655: #    Another realization of this is simply:
                   7656: #    use File::Basename;
                   7657: #    ...
                   7658: #    $uri = shift;
                   7659: #    $filename = basename($uri);
                   7660: #    $path     = dirname($uri);
                   7661: #    return ($filename, $path);
                   7662: #
                   7663: #     The implementation below is probably faster however.
                   7664: #
1.710     albertel 7665: sub split_uri_for_cond {
                   7666:     my $uri=&deversion(&declutter(shift));
                   7667:     my @uriparts=split(/\//,$uri);
                   7668:     my $filename=pop(@uriparts);
                   7669:     my $pathname=join('/',@uriparts);
                   7670:     return ($pathname,$filename);
                   7671: }
1.232     www      7672: # --------------------------------------------------- Is a resource on the map?
                   7673: 
                   7674: sub is_on_map {
1.710     albertel 7675:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7676:     #Trying to find the conditional for the file
1.620     albertel 7677:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7678: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7679:     if ($match) {
1.289     bowersj2 7680: 	return (1,$1);
                   7681:     } else {
1.434     www      7682: 	return (0,0);
1.289     bowersj2 7683:     }
1.12      www      7684: }
                   7685: 
1.427     www      7686: # --------------------------------------------------------- Get symb from alias
                   7687: 
                   7688: sub get_symb_from_alias {
                   7689:     my $symb=shift;
                   7690:     my ($map,$resid,$url)=&decode_symb($symb);
                   7691: # Already is a symb
                   7692:     if ($url) { return $symb; }
                   7693: # Must be an alias
                   7694:     my $aliassymb='';
                   7695:     my %bighash;
1.620     albertel 7696:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7697:                             &GDBM_READER(),0640)) {
                   7698:         my $rid=$bighash{'mapalias_'.$symb};
                   7699: 	if ($rid) {
                   7700: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7701: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7702: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7703: 	}
                   7704:         untie %bighash;
                   7705:     }
                   7706:     return $aliassymb;
                   7707: }
                   7708: 
1.12      www      7709: # ----------------------------------------------------------------- Define Role
                   7710: 
                   7711: sub definerole {
                   7712:   if (allowed('mcr','/')) {
                   7713:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7714:     foreach my $role (split(':',$sysrole)) {
                   7715: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7716:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7717:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7718: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7719:                return "refused:s:$crole&$cqual"; 
                   7720:             }
                   7721:         }
1.191     harris41 7722:     }
1.800     albertel 7723:     foreach my $role (split(':',$domrole)) {
                   7724: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7725:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7726:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7727: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7728:                return "refused:d:$crole&$cqual"; 
                   7729:             }
                   7730:         }
1.191     harris41 7731:     }
1.800     albertel 7732:     foreach my $role (split(':',$courole)) {
                   7733: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7734:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7735:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7736: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7737:                return "refused:c:$crole&$cqual"; 
                   7738:             }
                   7739:         }
1.191     harris41 7740:     }
1.620     albertel 7741:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7742:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7743: 	        "rolesdef_$rolename=".
                   7744:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7745:     return reply($command,$env{'user.home'});
1.12      www      7746:   } else {
                   7747:     return 'refused';
                   7748:   }
1.105     harris41 7749: }
                   7750: 
                   7751: # ---------------- Make a metadata query against the network of library servers
                   7752: 
                   7753: sub metadata_query {
1.1237    raeburn  7754:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7755:     my %rhash;
1.845     albertel 7756:     my %libserv = &all_library();
1.244     matthew  7757:     my @server_list = (defined($server_array) ? @$server_array
                   7758:                                               : keys(%libserv) );
                   7759:     for my $server (@server_list) {
1.1237    raeburn  7760:         my $domains = ''; 
                   7761:         if (ref($domains_hash) eq 'HASH') {
                   7762:             $domains = $domains_hash->{$server}; 
                   7763:         }
1.118     harris41 7764: 	unless ($custom or $customshow) {
1.1237    raeburn  7765: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7766: 	    $rhash{$server}=$reply;
                   7767: 	}
                   7768: 	else {
                   7769: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7770: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7771: 			     $server);
                   7772: 	    $rhash{$server}=$reply;
                   7773: 	}
1.112     harris41 7774:     }
1.118     harris41 7775:     return \%rhash;
1.240     www      7776: }
                   7777: 
                   7778: # ----------------------------------------- Send log queries and wait for reply
                   7779: 
                   7780: sub log_query {
                   7781:     my ($uname,$udom,$query,%filters)=@_;
                   7782:     my $uhome=&homeserver($uname,$udom);
                   7783:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7784:     my $uhost=&hostname($uhome);
1.800     albertel 7785:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7786:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7787:                        $uhome);
1.479     albertel 7788:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7789:     return get_query_reply($queryid);
                   7790: }
                   7791: 
1.818     raeburn  7792: # -------------------------- Update MySQL table for portfolio file
                   7793: 
                   7794: sub update_portfolio_table {
1.821     raeburn  7795:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7796:     if ($group ne '') {
                   7797:         $file_name =~s /^\Q$group\E//;
                   7798:     }
1.818     raeburn  7799:     my $homeserver = &homeserver($uname,$udom);
                   7800:     my $queryid=
1.821     raeburn  7801:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7802:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7803:     my $reply = &get_query_reply($queryid);
                   7804:     return $reply;
                   7805: }
                   7806: 
1.899     raeburn  7807: # -------------------------- Update MySQL allusers table
                   7808: 
                   7809: sub update_allusers_table {
                   7810:     my ($uname,$udom,$names) = @_;
                   7811:     my $homeserver = &homeserver($uname,$udom);
                   7812:     my $queryid=
                   7813:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7814:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7815:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7816:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7817:                'generation='.&escape($names->{'generation'}).'%%'.
                   7818:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7819:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7820:     return;
1.899     raeburn  7821: }
                   7822: 
1.508     raeburn  7823: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7824: 
                   7825: sub fetch_enrollment_query {
1.511     raeburn  7826:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7827:     my $homeserver;
1.547     raeburn  7828:     my $maxtries = 1;
1.508     raeburn  7829:     if ($context eq 'automated') {
                   7830:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7831:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7832:     } else {
                   7833:         $homeserver = &homeserver($cnum,$dom);
                   7834:     }
1.838     albertel 7835:     my $host=&hostname($homeserver);
1.506     raeburn  7836:     my $cmd = '';
1.1000    raeburn  7837:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7838:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7839:     }
                   7840:     $cmd =~ s/%%$//;
                   7841:     $cmd = &escape($cmd);
                   7842:     my $query = 'fetchenrollment';
1.620     albertel 7843:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7844:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7845:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7846:         return 'error: '.$queryid;
                   7847:     }
1.506     raeburn  7848:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7849:     my $tries = 1;
                   7850:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7851:         $reply = &get_query_reply($queryid);
                   7852:         $tries ++;
                   7853:     }
1.526     raeburn  7854:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7855:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7856:     } else {
1.901     albertel 7857:         my @responses = split(/:/,$reply);
1.515     raeburn  7858:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7859:             foreach my $line (@responses) {
                   7860:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7861:                 $$replyref{$key} = $value;
                   7862:             }
                   7863:         } else {
1.1117    foxr     7864:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7865:             foreach my $line (@responses) {
                   7866:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7867:                 $$replyref{$key} = $value;
                   7868:                 if ($value > 0) {
1.800     albertel 7869:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7870:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7871:                         my $destname = $pathname.'/'.$filename;
                   7872:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7873:                         if ($xml_classlist =~ /^error/) {
                   7874:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7875:                         } else {
1.506     raeburn  7876:                             if ( open(FILE,">$destname") ) {
                   7877:                                 print FILE &unescape($xml_classlist);
                   7878:                                 close(FILE);
1.526     raeburn  7879:                             } else {
                   7880:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7881:                             }
                   7882:                         }
                   7883:                     }
                   7884:                 }
                   7885:             }
                   7886:         }
                   7887:         return 'ok';
                   7888:     }
                   7889:     return 'error';
                   7890: }
                   7891: 
1.242     www      7892: sub get_query_reply {
                   7893:     my $queryid=shift;
1.1117    foxr     7894:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7895:     my $reply='';
                   7896:     for (1..100) {
1.1289    damieng  7897: 	sleep(0.2);
1.240     www      7898:         if (-e $replyfile.'.end') {
1.448     albertel 7899: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7900: 		$reply = join('',<$fh>);
                   7901: 		close($fh);
1.240     www      7902: 	   } else { return 'error: reply_file_error'; }
1.242     www      7903:            return &unescape($reply);
                   7904: 	}
1.240     www      7905:     }
1.242     www      7906:     return 'timeout:'.$queryid;
1.240     www      7907: }
                   7908: 
                   7909: sub courselog_query {
1.241     www      7910: #
                   7911: # possible filters:
                   7912: # url: url or symb
                   7913: # username
                   7914: # domain
                   7915: # action: view, submit, grade
                   7916: # start: timestamp
                   7917: # end: timestamp
                   7918: #
1.240     www      7919:     my (%filters)=@_;
1.620     albertel 7920:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7921:     if ($filters{'url'}) {
                   7922: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7923:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7924:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7925:     }
1.620     albertel 7926:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7927:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7928:     return &log_query($cname,$cdom,'courselog',%filters);
                   7929: }
                   7930: 
                   7931: sub userlog_query {
1.858     raeburn  7932: #
                   7933: # possible filters:
                   7934: # action: log check role
                   7935: # start: timestamp
                   7936: # end: timestamp
                   7937: #
1.240     www      7938:     my ($uname,$udom,%filters)=@_;
                   7939:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7940: }
                   7941: 
1.506     raeburn  7942: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7943: 
                   7944: sub auto_run {
1.508     raeburn  7945:     my ($cnum,$cdom) = @_;
1.876     raeburn  7946:     my $response = 0;
                   7947:     my $settings;
                   7948:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7949:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7950:         $settings = $domconfig{'autoenroll'};
                   7951:         if ($settings->{'run'} eq '1') {
                   7952:             $response = 1;
                   7953:         }
                   7954:     } else {
1.934     raeburn  7955:         my $homeserver;
                   7956:         if (&is_course($cdom,$cnum)) {
                   7957:             $homeserver = &homeserver($cnum,$cdom);
                   7958:         } else {
                   7959:             $homeserver = &domain($cdom,'primary');
                   7960:         }
                   7961:         if ($homeserver ne 'no_host') {
                   7962:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7963:         }
1.876     raeburn  7964:     }
1.506     raeburn  7965:     return $response;
                   7966: }
1.776     albertel 7967: 
1.506     raeburn  7968: sub auto_get_sections {
1.508     raeburn  7969:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7970:     my $homeserver;
                   7971:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7972:         $homeserver = &homeserver($cnum,$cdom);
                   7973:     }
                   7974:     if (!defined($homeserver)) { 
                   7975:         if ($cdom =~ /^$match_domain$/) {
                   7976:             $homeserver = &domain($cdom,'primary');
                   7977:         }
                   7978:     }
                   7979:     my @secs;
                   7980:     if (defined($homeserver)) {
                   7981:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7982:         unless ($response eq 'refused') {
                   7983:             @secs = split(/:/,$response);
                   7984:         }
1.506     raeburn  7985:     }
                   7986:     return @secs;
                   7987: }
1.776     albertel 7988: 
1.506     raeburn  7989: sub auto_new_course {
1.1099    raeburn  7990:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7991:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7992:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7993:     return $response;
                   7994: }
1.776     albertel 7995: 
1.506     raeburn  7996: sub auto_validate_courseID {
1.508     raeburn  7997:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7998:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7999:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8000:     return $response;
                   8001: }
1.776     albertel 8002: 
1.1007    raeburn  8003: sub auto_validate_instcode {
1.1020    raeburn  8004:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8005:     my ($homeserver,$response);
                   8006:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8007:         $homeserver = &homeserver($cnum,$cdom);
                   8008:     }
                   8009:     if (!defined($homeserver)) {
                   8010:         if ($cdom =~ /^$match_domain$/) {
                   8011:             $homeserver = &domain($cdom,'primary');
                   8012:         }
                   8013:     }
1.1065    raeburn  8014:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8015:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8016:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8017:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8018: }
                   8019: 
1.506     raeburn  8020: sub auto_create_password {
1.873     raeburn  8021:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8022:     my ($homeserver,$response);
1.506     raeburn  8023:     my $create_passwd = 0;
                   8024:     my $authchk = '';
1.873     raeburn  8025:     if ($udom =~ /^$match_domain$/) {
                   8026:         $homeserver = &domain($udom,'primary');
                   8027:     }
                   8028:     if ($homeserver eq '') {
                   8029:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8030:             $homeserver = &homeserver($cnum,$cdom);
                   8031:         }
                   8032:     }
                   8033:     if ($homeserver eq '') {
                   8034:         $authchk = 'nodomain';
1.506     raeburn  8035:     } else {
1.873     raeburn  8036:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8037:         if ($response eq 'refused') {
                   8038:             $authchk = 'refused';
                   8039:         } else {
1.901     albertel 8040:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8041:         }
1.506     raeburn  8042:     }
                   8043:     return ($authparam,$create_passwd,$authchk);
                   8044: }
                   8045: 
1.706     raeburn  8046: sub auto_photo_permission {
                   8047:     my ($cnum,$cdom,$students) = @_;
                   8048:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8049:     my ($outcome,$perm_reqd,$conditions) = 
                   8050: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8051:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8052: 	return (undef,undef);
                   8053:     }
1.706     raeburn  8054:     return ($outcome,$perm_reqd,$conditions);
                   8055: }
                   8056: 
                   8057: sub auto_checkphotos {
                   8058:     my ($uname,$udom,$pid) = @_;
                   8059:     my $homeserver = &homeserver($uname,$udom);
                   8060:     my ($result,$resulttype);
                   8061:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8062: 				   &escape($uname).':'.&escape($pid),
                   8063: 				   $homeserver));
1.709     albertel 8064:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8065: 	return (undef,undef);
                   8066:     }
1.706     raeburn  8067:     if ($outcome) {
                   8068:         ($result,$resulttype) = split(/:/,$outcome);
                   8069:     } 
                   8070:     return ($result,$resulttype);
                   8071: }
                   8072: 
                   8073: sub auto_photochoice {
                   8074:     my ($cnum,$cdom) = @_;
                   8075:     my $homeserver = &homeserver($cnum,$cdom);
                   8076:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8077: 						       &escape($cdom),
                   8078: 						       $homeserver)));
1.709     albertel 8079:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8080: 	return (undef,undef);
                   8081:     }
1.706     raeburn  8082:     return ($update,$comment);
                   8083: }
                   8084: 
                   8085: sub auto_photoupdate {
                   8086:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8087:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8088:     my $host=&hostname($homeserver);
1.706     raeburn  8089:     my $cmd = '';
                   8090:     my $maxtries = 1;
1.800     albertel 8091:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8092:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8093:     }
                   8094:     $cmd =~ s/%%$//;
                   8095:     $cmd = &escape($cmd);
                   8096:     my $query = 'institutionalphotos';
                   8097:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8098:     unless ($queryid=~/^\Q$host\E\_/) {
                   8099:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8100:         return 'error: '.$queryid;
                   8101:     }
                   8102:     my $reply = &get_query_reply($queryid);
                   8103:     my $tries = 1;
                   8104:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8105:         $reply = &get_query_reply($queryid);
                   8106:         $tries ++;
                   8107:     }
                   8108:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8109:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8110:     } else {
                   8111:         my @responses = split(/:/,$reply);
                   8112:         my $outcome = shift(@responses); 
                   8113:         foreach my $item (@responses) {
                   8114:             my ($key,$value) = split(/=/,$item);
                   8115:             $$photo{$key} = $value;
                   8116:         }
                   8117:         return $outcome;
                   8118:     }
                   8119:     return 'error';
                   8120: }
                   8121: 
1.521     raeburn  8122: sub auto_instcode_format {
1.793     albertel 8123:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8124: 	$cat_order) = @_;
1.521     raeburn  8125:     my $courses = '';
1.772     raeburn  8126:     my @homeservers;
1.521     raeburn  8127:     if ($caller eq 'global') {
1.841     albertel 8128: 	my %servers = &get_servers($codedom,'library');
                   8129: 	foreach my $tryserver (keys(%servers)) {
                   8130: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8131: 		push(@homeservers,$tryserver);
                   8132: 	    }
1.584     raeburn  8133:         }
1.1022    raeburn  8134:     } elsif ($caller eq 'requests') {
                   8135:         if ($codedom =~ /^$match_domain$/) {
                   8136:             my $chome = &domain($codedom,'primary');
                   8137:             unless ($chome eq 'no_host') {
                   8138:                 push(@homeservers,$chome);
                   8139:             }
                   8140:         }
1.521     raeburn  8141:     } else {
1.772     raeburn  8142:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8143:     }
1.793     albertel 8144:     foreach my $code (keys(%{$instcodes})) {
                   8145:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8146:     }
                   8147:     chop($courses);
1.772     raeburn  8148:     my $ok_response = 0;
                   8149:     my $response;
                   8150:     while (@homeservers > 0 && $ok_response == 0) {
                   8151:         my $server = shift(@homeservers); 
                   8152:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8153:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8154:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8155: 		split(/:/,$response);
1.772     raeburn  8156:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8157:             push(@{$codetitles},&str2array($codetitles_str));
                   8158:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8159:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8160:             $ok_response = 1;
                   8161:         }
                   8162:     }
                   8163:     if ($ok_response) {
1.521     raeburn  8164:         return 'ok';
1.772     raeburn  8165:     } else {
                   8166:         return $response;
1.521     raeburn  8167:     }
                   8168: }
                   8169: 
1.792     raeburn  8170: sub auto_instcode_defaults {
                   8171:     my ($domain,$returnhash,$code_order) = @_;
                   8172:     my @homeservers;
1.841     albertel 8173: 
                   8174:     my %servers = &get_servers($domain,'library');
                   8175:     foreach my $tryserver (keys(%servers)) {
                   8176: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8177: 	    push(@homeservers,$tryserver);
                   8178: 	}
1.792     raeburn  8179:     }
1.841     albertel 8180: 
1.792     raeburn  8181:     my $response;
1.841     albertel 8182:     foreach my $server (@homeservers) {
1.792     raeburn  8183:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8184:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8185: 	
                   8186: 	foreach my $pair (split(/\&/,$response)) {
                   8187: 	    my ($name,$value)=split(/\=/,$pair);
                   8188: 	    if ($name eq 'code_order') {
                   8189: 		@{$code_order} = split(/\&/,&unescape($value));
                   8190: 	    } else {
                   8191: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8192: 	    }
                   8193: 	}
                   8194: 	return 'ok';
1.792     raeburn  8195:     }
1.841     albertel 8196: 
                   8197:     return $response;
1.1003    raeburn  8198: }
                   8199: 
                   8200: sub auto_possible_instcodes {
1.1007    raeburn  8201:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8202:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8203:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8204:         return;
                   8205:     }
1.1003    raeburn  8206:     my (@homeservers,$uhome);
                   8207:     if (defined(&domain($domain,'primary'))) {
                   8208:         $uhome=&domain($domain,'primary');
                   8209:         push(@homeservers,&domain($domain,'primary'));
                   8210:     } else {
                   8211:         my %servers = &get_servers($domain,'library');
                   8212:         foreach my $tryserver (keys(%servers)) {
                   8213:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8214:                 push(@homeservers,$tryserver);
                   8215:             }
                   8216:         }
                   8217:     }
                   8218:     my $response;
                   8219:     foreach my $server (@homeservers) {
                   8220:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8221:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8222:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8223:             split(':',$response);
                   8224:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8225:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8226:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8227:             my ($name,$value)=split('=',$item);
                   8228:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8229:         }
                   8230:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8231:             my ($name,$value)=split('=',$item);
                   8232:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8233:         }
                   8234:         return 'ok';
                   8235:     }
                   8236:     return $response;
                   8237: }
1.792     raeburn  8238: 
1.1010    raeburn  8239: sub auto_courserequest_checks {
                   8240:     my ($dom) = @_;
1.1020    raeburn  8241:     my ($homeserver,%validations);
                   8242:     if ($dom =~ /^$match_domain$/) {
                   8243:         $homeserver = &domain($dom,'primary');
                   8244:     }
                   8245:     unless ($homeserver eq 'no_host') {
                   8246:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8247:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8248:             my @items = split(/&/,$response);
                   8249:             foreach my $item (@items) {
                   8250:                 my ($key,$value) = split('=',$item);
                   8251:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8252:             }
                   8253:         }
                   8254:     }
1.1010    raeburn  8255:     return %validations; 
                   8256: }
                   8257: 
1.1020    raeburn  8258: sub auto_courserequest_validation {
1.1255    raeburn  8259:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8260:     my ($homeserver,$response);
                   8261:     if ($dom =~ /^$match_domain$/) {
                   8262:         $homeserver = &domain($dom,'primary');
                   8263:     }
1.1255    raeburn  8264:     unless ($homeserver eq 'no_host') {
                   8265:         my $customdata;
                   8266:         if (ref($custominfo) eq 'HASH') {
                   8267:             $customdata = &freeze_escape($custominfo);
                   8268:         }
1.1020    raeburn  8269:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8270:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8271:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8272:                                     $customdata,$homeserver));
1.1020    raeburn  8273:     }
                   8274:     return $response;
                   8275: }
                   8276: 
1.777     albertel 8277: sub auto_validate_class_sec {
1.918     raeburn  8278:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8279:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8280:     my $ownerlist;
                   8281:     if (ref($owners) eq 'ARRAY') {
                   8282:         $ownerlist = join(',',@{$owners});
                   8283:     } else {
                   8284:         $ownerlist = $owners;
                   8285:     }
1.773     raeburn  8286:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8287:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8288:     return $response;
                   8289: }
                   8290: 
1.1248    raeburn  8291: sub auto_crsreq_update {
                   8292:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8293:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8294:     my ($homeserver,%crsreqresponse);
                   8295:     if ($cdom =~ /^$match_domain$/) {
                   8296:         $homeserver = &domain($cdom,'primary');
                   8297:     }
                   8298:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8299:         my $info;
                   8300:         if (ref($inbound) eq 'HASH') {
                   8301:             $info = &freeze_escape($inbound);
                   8302:         }
                   8303:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8304:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8305:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8306:                             &escape($title).':'.&escape($code).':'.
                   8307:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8308:                             $homeserver);
1.1248    raeburn  8309:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8310:             my @items = split(/&/,$response);
                   8311:             foreach my $item (@items) {
                   8312:                 my ($key,$value) = split('=',$item);
                   8313:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8314:             }
                   8315:         }
                   8316:     }
                   8317:     return \%crsreqresponse;
                   8318: }
                   8319: 
1.1305    raeburn  8320: sub auto_export_grades {
1.1309    raeburn  8321:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8322:     my ($homeserver,%exportresponse);
                   8323:     if ($cdom =~ /^$match_domain$/) {
                   8324:         $homeserver = &domain($cdom,'primary');
                   8325:     }
                   8326:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8327:         my $info;
                   8328:         if (ref($inforef) eq 'HASH') {
                   8329:             $info = &freeze_escape($inforef);
                   8330:         }
                   8331:         if (ref($gradesref) eq 'HASH') {
                   8332:             my $grades = &freeze_escape($gradesref);
                   8333:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8334:                                 $info.':'.$grades,$homeserver);
                   8335:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8336:                 my @items = split(/&/,$response);
                   8337:                 foreach my $item (@items) {
                   8338:                     my ($key,$value) = split('=',$item);
                   8339:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8340:                 }
                   8341:             }
                   8342:         }
                   8343:     }
                   8344:     return \%exportresponse;
1.1305    raeburn  8345: }
                   8346: 
1.1287    raeburn  8347: sub check_instcode_cloning {
                   8348:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8349:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8350:         return;
                   8351:     }
                   8352:     my $canclone;
                   8353:     if (@{$code_order} > 0) {
                   8354:         my $instcoderegexp ='^';
                   8355:         my @clonecodes = split(/\&/,$cloner);
                   8356:         foreach my $item (@{$code_order}) {
                   8357:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8358:                 foreach my $pair (@clonecodes) {
                   8359:                     my ($key,$val) = split(/\=/,$pair,2);
                   8360:                     $val = &unescape($val);
                   8361:                     if ($key eq $item) {
                   8362:                         $instcoderegexp .= '('.$val.')';
                   8363:                         last;
                   8364:                     }
                   8365:                 }
                   8366:             } else {
                   8367:                 $instcoderegexp .= $codedefaults->{$item};
                   8368:             }
                   8369:         }
                   8370:         $instcoderegexp .= '$';
                   8371:         my (@from,@to);
                   8372:         eval {
                   8373:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8374:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8375:         };
                   8376:         if ((@from > 0) && (@to > 0)) {
                   8377:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8378:             if (!@diffs) {
                   8379:                 $canclone = 1;
                   8380:             }
                   8381:         }
                   8382:     }
                   8383:     return $canclone;
                   8384: }
                   8385: 
                   8386: sub default_instcode_cloning {
                   8387:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8388:     my (%codedefaults,@code_order,$canclone);
                   8389:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8390:         %codedefaults = %{$codedefaultsref};
                   8391:         @code_order = @{$codeorderref};
                   8392:     } elsif ($clonedom) {
                   8393:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8394:     }
                   8395:     if (($domdefclone) && (@code_order)) {
                   8396:         my @clonecodes = split(/\+/,$domdefclone);
                   8397:         my $instcoderegexp ='^';
                   8398:         foreach my $item (@code_order) {
                   8399:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8400:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8401:             } else {
                   8402:                 $instcoderegexp .= $codedefaults{$item};
                   8403:             }
                   8404:         }
                   8405:         $instcoderegexp .= '$';
                   8406:         my (@from,@to);
                   8407:         eval {
                   8408:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8409:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8410:         };
                   8411:         if ((@from > 0) && (@to > 0)) {
                   8412:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8413:             if (!@diffs) {
                   8414:                 $canclone = 1;
                   8415:             }
                   8416:         }
                   8417:     }
                   8418:     return $canclone;
                   8419: }
                   8420: 
1.679     raeburn  8421: # ------------------------------------------------------- Course Group routines
                   8422: 
                   8423: sub get_coursegroups {
1.809     raeburn  8424:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8425:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8426: }
                   8427: 
1.679     raeburn  8428: sub modify_coursegroup {
                   8429:     my ($cdom,$cnum,$groupsettings) = @_;
                   8430:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8431: }
                   8432: 
1.809     raeburn  8433: sub toggle_coursegroup_status {
                   8434:     my ($cdom,$cnum,$group,$action) = @_;
                   8435:     my ($from_namespace,$to_namespace);
                   8436:     if ($action eq 'delete') {
                   8437:         $from_namespace = 'coursegroups';
                   8438:         $to_namespace = 'deleted_groups';
                   8439:     } else {
                   8440:         $from_namespace = 'deleted_groups';
                   8441:         $to_namespace = 'coursegroups';
                   8442:     }
                   8443:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8444:     if (my $tmp = &error(%curr_group)) {
                   8445:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8446:         return ('read error',$tmp);
                   8447:     } else {
                   8448:         my %savedsettings = %curr_group; 
1.809     raeburn  8449:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8450:         my $deloutcome;
                   8451:         if ($result eq 'ok') {
1.809     raeburn  8452:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8453:         } else {
                   8454:             return ('write error',$result);
                   8455:         }
                   8456:         if ($deloutcome eq 'ok') {
                   8457:             return 'ok';
                   8458:         } else {
                   8459:             return ('delete error',$deloutcome);
                   8460:         }
                   8461:     }
                   8462: }
                   8463: 
1.679     raeburn  8464: sub modify_group_roles {
1.957     raeburn  8465:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8466:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8467:     my $role = 'gr/'.&escape($userprivs);
                   8468:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8469:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8470:     if ($result eq 'ok') {
                   8471:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8472:     }
1.679     raeburn  8473:     return $result;
                   8474: }
                   8475: 
                   8476: sub modify_coursegroup_membership {
                   8477:     my ($cdom,$cnum,$membership) = @_;
                   8478:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8479:     return $result;
                   8480: }
                   8481: 
1.682     raeburn  8482: sub get_active_groups {
                   8483:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8484:     my $now = time;
                   8485:     my %groups = ();
                   8486:     foreach my $key (keys(%env)) {
1.811     albertel 8487:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8488:             my ($start,$end) = split(/\./,$env{$key});
                   8489:             if (($end!=0) && ($end<$now)) { next; }
                   8490:             if (($start!=0) && ($start>$now)) { next; }
                   8491:             if ($1 eq $cdom && $2 eq $cnum) {
                   8492:                 $groups{$3} = $env{$key} ;
                   8493:             }
                   8494:         }
                   8495:     }
                   8496:     return %groups;
                   8497: }
                   8498: 
1.683     raeburn  8499: sub get_group_membership {
                   8500:     my ($cdom,$cnum,$group) = @_;
                   8501:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8502: }
                   8503: 
                   8504: sub get_users_groups {
                   8505:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8506:     my @usersgroups;
1.683     raeburn  8507:     my $cachetime=1800;
                   8508: 
                   8509:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8510:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8511:     if (defined($cached)) {
1.734     albertel 8512:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8513:     } else {  
                   8514:         $grouplist = '';
1.816     raeburn  8515:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8516:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8517:         my $access_end = $env{'course.'.$courseid.
                   8518:                               '.default_enrollment_end_date'};
                   8519:         my $now = time;
                   8520:         foreach my $key (keys(%roleshash)) {
                   8521:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8522:                 my $group = $1;
                   8523:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8524:                     my $start = $2;
                   8525:                     my $end = $1;
                   8526:                     if ($start == -1) { next; } # deleted from group
                   8527:                     if (($start!=0) && ($start>$now)) { next; }
                   8528:                     if (($end!=0) && ($end<$now)) {
                   8529:                         if ($access_end && $access_end < $now) {
                   8530:                             if ($access_end - $end < 86400) {
                   8531:                                 push(@usersgroups,$group);
1.733     raeburn  8532:                             }
                   8533:                         }
1.817     raeburn  8534:                         next;
1.733     raeburn  8535:                     }
1.817     raeburn  8536:                     push(@usersgroups,$group);
1.683     raeburn  8537:                 }
                   8538:             }
                   8539:         }
1.817     raeburn  8540:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8541:         $grouplist = join(':',@usersgroups);
                   8542:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8543:     }
1.733     raeburn  8544:     return @usersgroups;
1.683     raeburn  8545: }
                   8546: 
                   8547: sub devalidate_getgroups_cache {
                   8548:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8549:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8550: 
1.683     raeburn  8551:     my $hashid="$udom:$uname:$courseid";
                   8552:     &devalidate_cache_new('getgroups',$hashid);
                   8553: }
                   8554: 
1.12      www      8555: # ------------------------------------------------------------------ Plain Text
                   8556: 
                   8557: sub plaintext {
1.988     raeburn  8558:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8559:     if ($short =~ m{^cr/}) {
1.758     albertel 8560: 	return (split('/',$short))[-1];
                   8561:     }
1.742     raeburn  8562:     if (!defined($cid)) {
                   8563:         $cid = $env{'request.course.id'};
                   8564:     }
                   8565:     my %rolenames = (
1.1008    raeburn  8566:                       Course    => 'std',
                   8567:                       Community => 'alt1',
1.1305    raeburn  8568:                       Placement => 'std',
1.742     raeburn  8569:                     );
1.1037    raeburn  8570:     if ($cid ne '') {
                   8571:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8572:             unless ($forcedefault) {
                   8573:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8574:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8575:                 return &Apache::lonlocal::mt($roletext);
                   8576:             }
                   8577:         }
                   8578:     }
                   8579:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8580:         (defined($rolenames{$type})) && 
                   8581:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8582:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8583:     } elsif ($cid ne '') {
                   8584:         my $crstype = $env{'course.'.$cid.'.type'};
                   8585:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8586:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8587:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8588:         }
1.742     raeburn  8589:     }
1.1037    raeburn  8590:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8591: }
                   8592: 
                   8593: # ----------------------------------------------------------------- Assign Role
                   8594: 
                   8595: sub assignrole {
1.957     raeburn  8596:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8597:         $context)=@_;
1.21      www      8598:     my $mrole;
                   8599:     if ($role =~ /^cr\//) {
1.393     www      8600:         my $cwosec=$url;
1.811     albertel 8601:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8602: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8603:            my $refused = 1;
                   8604:            if ($context eq 'requestcourses') {
                   8605:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8606:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8607:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8608:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8609:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8610:                            if ($crsenv{'internal.courseowner'} eq
                   8611:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8612:                                $refused = '';
                   8613:                            }
                   8614:                        }
                   8615:                    }
                   8616:                }
                   8617:            }
                   8618:            if ($refused) {
                   8619:                &logthis('Refused custom assignrole: '.
                   8620:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8621:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8622:                return 'refused';
                   8623:            }
1.104     www      8624:         }
1.21      www      8625:         $mrole='cr';
1.678     raeburn  8626:     } elsif ($role =~ /^gr\//) {
                   8627:         my $cwogrp=$url;
1.811     albertel 8628:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8629:         unless (&allowed('mdg',$cwogrp)) {
                   8630:             &logthis('Refused group assignrole: '.
                   8631:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8632:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8633:             return 'refused';
                   8634:         }
                   8635:         $mrole='gr';
1.21      www      8636:     } else {
1.82      www      8637:         my $cwosec=$url;
1.811     albertel 8638:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8639:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8640:             my $refused;
                   8641:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8642:                 if (!(&allowed('c'.$role,$url))) {
                   8643:                     $refused = 1;
                   8644:                 }
                   8645:             } else {
                   8646:                 $refused = 1;
                   8647:             }
1.947     raeburn  8648:             if ($refused) {
1.1045    raeburn  8649:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8650:                 if (!$selfenroll && $context eq 'course') {
                   8651:                     my %crsenv;
                   8652:                     if ($role eq 'cc' || $role eq 'co') {
                   8653:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8654:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8655:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8656:                                 if ($crsenv{'internal.courseowner'} eq 
                   8657:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8658:                                     $refused = '';
                   8659:                                 }
                   8660:                             }
                   8661:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8662:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8663:                                 if ($crsenv{'internal.courseowner'} eq 
                   8664:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8665:                                     $refused = '';
                   8666:                                 }
                   8667:                             }
                   8668:                         }
                   8669:                     }
                   8670:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8671:                     $refused = '';
1.1017    raeburn  8672:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8673:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8674:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8675:                         my $wrongcc;
                   8676:                         if ($cnum =~ /^$match_community$/) {
                   8677:                             $wrongcc = 1 if ($role eq 'cc');
                   8678:                         } else {
                   8679:                             $wrongcc = 1 if ($role eq 'co');
                   8680:                         }
                   8681:                         unless ($wrongcc) {
                   8682:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8683:                             if ($crsenv{'internal.courseowner'} eq 
                   8684:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8685:                                 $refused = '';
                   8686:                             }
1.1017    raeburn  8687:                         }
                   8688:                     }
1.1183    raeburn  8689:                 } elsif ($context eq 'requestauthor') {
                   8690:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8691:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8692:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8693:                             $refused = '';
                   8694:                         } else {
                   8695:                             my %domdefaults = &get_domain_defaults($udom);
                   8696:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8697:                                 my $checkbystatus;
                   8698:                                 if ($env{'user.adv'}) { 
                   8699:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8700:                                     if ($disposition eq 'automatic') {
                   8701:                                         $refused = '';
                   8702:                                     } elsif ($disposition eq '') {
                   8703:                                         $checkbystatus = 1;
                   8704:                                     } 
                   8705:                                 } else {
                   8706:                                     $checkbystatus = 1;
                   8707:                                 }
                   8708:                                 if ($checkbystatus) {
                   8709:                                     if ($env{'environment.inststatus'}) {
                   8710:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8711:                                         foreach my $type (@inststatuses) {
                   8712:                                             if (($type ne '') &&
                   8713:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8714:                                                 $refused = '';
                   8715:                                             }
                   8716:                                         }
                   8717:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8718:                                         $refused = '';
                   8719:                                     }
                   8720:                                 }
                   8721:                             }
                   8722:                         }
                   8723:                     }
1.1017    raeburn  8724:                 }
                   8725:                 if ($refused) {
1.947     raeburn  8726:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8727:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8728: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8729:                     return 'refused';
                   8730:                 }
1.932     raeburn  8731:             }
1.1131    raeburn  8732:         } elsif ($role eq 'au') {
                   8733:             if ($url ne '/'.$udom.'/') {
                   8734:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8735:                          ' to assign author role for '.$uname.':'.$udom.
                   8736:                          ' in domain: '.$url.' refused (wrong domain).');
                   8737:                 return 'refused';
                   8738:             }
1.104     www      8739:         }
1.21      www      8740:         $mrole=$role;
                   8741:     }
1.620     albertel 8742:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8743:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8744:     if ($end) { $command.='_'.$end; }
1.21      www      8745:     if ($start) {
                   8746: 	if ($end) { 
1.81      www      8747:            $command.='_'.$start; 
1.21      www      8748:         } else {
1.81      www      8749:            $command.='_0_'.$start;
1.21      www      8750:         }
                   8751:     }
1.739     raeburn  8752:     my $origstart = $start;
                   8753:     my $origend = $end;
1.957     raeburn  8754:     my $delflag;
1.357     www      8755: # actually delete
                   8756:     if ($deleteflag) {
1.373     www      8757: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8758: # modify command to delete the role
1.620     albertel 8759:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8760:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8761: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8762: # set start and finish to negative values for userrolelog
                   8763:            $start=-1;
                   8764:            $end=-1;
1.957     raeburn  8765:            $delflag = 1;
1.357     www      8766:         }
                   8767:     }
                   8768: # send command
1.349     www      8769:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8770: # log new user role if status is ok
1.349     www      8771:     if ($answer eq 'ok') {
1.663     raeburn  8772: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8773:         if (($role eq 'cc') || ($role eq 'in') ||
                   8774:             ($role eq 'ep') || ($role eq 'ad') ||
                   8775:             ($role eq 'ta') || ($role eq 'st') ||
                   8776:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8777:             ($role eq 'co')) {
1.1200    raeburn  8778: # for course roles, perform group memberships changes triggered by role change.
                   8779:             unless ($role =~ /^gr/) {
                   8780:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8781:                                                  $origstart,$selfenroll,$context);
                   8782:             }
1.1184    raeburn  8783:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8784:                            $selfenroll,$context);
                   8785:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8786:                  ($role eq 'au') || ($role eq 'dc')) {
                   8787:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8788:                            $context);
                   8789:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8790:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8791:                              $context); 
                   8792:         }
1.1053    raeburn  8793:         if ($role eq 'cc') {
                   8794:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8795:         }
1.349     www      8796:     }
                   8797:     return $answer;
1.169     harris41 8798: }
                   8799: 
1.1053    raeburn  8800: sub autoupdate_coowners {
                   8801:     my ($url,$end,$start,$uname,$udom) = @_;
                   8802:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8803:     if (($cdom ne '') && ($cnum ne '')) {
                   8804:         my $now = time;
                   8805:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8806:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8807:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8808:             my $instcode = $coursehash{'internal.coursecode'};
                   8809:             if ($instcode ne '') {
1.1056    raeburn  8810:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8811:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8812:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8813:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8814:                         if ($result eq 'valid') {
                   8815:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8816:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8817:                                     push(@newcoowners,$coowner);
                   8818:                                 }
                   8819:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8820:                                     push(@newcoowners,$uname.':'.$udom);
                   8821:                                 }
                   8822:                                 @newcoowners = sort(@newcoowners);
                   8823:                             } else {
                   8824:                                 push(@newcoowners,$uname.':'.$udom);
                   8825:                             }
                   8826:                         } else {
                   8827:                             if ($coursehash{'internal.co-owners'}) {
                   8828:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8829:                                     unless ($coowner eq $uname.':'.$udom) {
                   8830:                                         push(@newcoowners,$coowner);
                   8831:                                     }
                   8832:                                 }
                   8833:                                 unless (@newcoowners > 0) {
                   8834:                                     $delcoowners = 1;
                   8835:                                     $coowners = '';
                   8836:                                 }
                   8837:                             }
                   8838:                         }
                   8839:                         if (@newcoowners || $delcoowners) {
                   8840:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8841:                                             $delcoowners,@newcoowners);
                   8842:                         }
                   8843:                     }
                   8844:                 }
                   8845:             }
                   8846:         }
                   8847:     }
                   8848: }
                   8849: 
                   8850: sub store_coowners {
                   8851:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8852:     my $cid = $cdom.'_'.$cnum;
                   8853:     my ($coowners,$delresult,$putresult);
                   8854:     if (@newcoowners) {
                   8855:         $coowners = join(',',@newcoowners);
                   8856:         my %coownershash = (
                   8857:                             'internal.co-owners' => $coowners,
                   8858:                            );
                   8859:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8860:         if ($putresult eq 'ok') {
                   8861:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8862:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8863:             }
                   8864:         }
                   8865:     }
                   8866:     if ($delcoowners) {
                   8867:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8868:         if ($delresult eq 'ok') {
                   8869:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8870:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8871:             }
                   8872:         }
                   8873:     }
                   8874:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8875:         my %crsinfo =
                   8876:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8877:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8878:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8879:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8880:         }
                   8881:     }
                   8882: }
                   8883: 
1.169     harris41 8884: # -------------------------------------------------- Modify user authentication
1.197     www      8885: # Overrides without validation
                   8886: 
1.169     harris41 8887: sub modifyuserauth {
                   8888:     my ($udom,$uname,$umode,$upass)=@_;
                   8889:     my $uhome=&homeserver($uname,$udom);
1.197     www      8890:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8891:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8892:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8893:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8894:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8895: 		     &escape($upass),$uhome);
1.620     albertel 8896:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8897:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8898:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8899:     &log($udom,,$uname,$uhome,
1.620     albertel 8900:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8901:                                      $env{'user.name'}.', '.$umode.
1.197     www      8902:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8903:     unless ($reply eq 'ok') {
1.197     www      8904:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8905: 	return 'error: '.$reply;
                   8906:     }   
1.170     harris41 8907:     return 'ok';
1.80      www      8908: }
                   8909: 
1.81      www      8910: # --------------------------------------------------------------- Modify a user
1.80      www      8911: 
1.81      www      8912: sub modifyuser {
1.206     matthew  8913:     my ($udom,    $uname, $uid,
                   8914:         $umode,   $upass, $first,
                   8915:         $middle,  $last,  $gene,
1.1058    raeburn  8916:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8917:     $udom= &LONCAPA::clean_domain($udom);
                   8918:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8919:     my $showcandelete = 'none';
                   8920:     if (ref($candelete) eq 'ARRAY') {
                   8921:         if (@{$candelete} > 0) {
                   8922:             $showcandelete = join(', ',@{$candelete});
                   8923:         }
                   8924:     }
1.81      www      8925:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8926:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8927: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8928:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8929:                                      ' desiredhome not specified'). 
1.620     albertel 8930:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8931:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8932:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8933:     my $newuser;
                   8934:     if ($uhome eq 'no_host') {
                   8935:         $newuser = 1;
                   8936:     }
1.80      www      8937: # ----------------------------------------------------------------- Create User
1.406     albertel 8938:     if (($uhome eq 'no_host') && 
                   8939: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8940:         my $unhome='';
1.844     albertel 8941:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8942:             $unhome = $desiredhome;
1.620     albertel 8943: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8944: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8945:         } else { # load balancing routine for determining $unhome
1.81      www      8946:             my $loadm=10000000;
1.841     albertel 8947: 	    my %servers = &get_servers($udom,'library');
                   8948: 	    foreach my $tryserver (keys(%servers)) {
                   8949: 		my $answer=reply('load',$tryserver);
                   8950: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8951: 		    $loadm=$answer;
                   8952: 		    $unhome=$tryserver;
                   8953: 		}
1.80      www      8954: 	    }
                   8955:         }
                   8956:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8957: 	    return 'error: unable to find a home server for '.$uname.
                   8958:                    ' in domain '.$udom;
1.80      www      8959:         }
                   8960:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8961:                          &escape($upass),$unhome);
                   8962: 	unless ($reply eq 'ok') {
                   8963:             return 'error: '.$reply;
                   8964:         }   
1.230     stredwic 8965:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8966:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8967: 	    return 'error: unable verify users home machine.';
1.80      www      8968:         }
1.209     matthew  8969:     }   # End of creation of new user
1.80      www      8970: # ---------------------------------------------------------------------- Add ID
                   8971:     if ($uid) {
                   8972:        $uid=~tr/A-Z/a-z/;
                   8973:        my %uidhash=&idrget($udom,$uname);
1.196     www      8974:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8975:          && (!$forceid)) {
1.80      www      8976: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8977: 	      return 'error: user id "'.$uid.'" does not match '.
                   8978:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8979:           }
                   8980:        } else {
1.1300    raeburn  8981: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      8982:        }
                   8983:     }
                   8984: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8985:     my @tmp=&get('environment',
1.899     raeburn  8986: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8987:                     'permanentemail','inststatus'],
1.134     albertel 8988: 		   $udom,$uname);
1.1075    raeburn  8989:     my (%names,%oldnames);
1.313     matthew  8990:     if ($tmp[0] =~ m/^error:.*/) { 
                   8991:         %names=(); 
                   8992:     } else {
                   8993:         %names = @tmp;
1.1075    raeburn  8994:         %oldnames = %names;
1.313     matthew  8995:     }
1.388     www      8996: #
1.1058    raeburn  8997: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8998: # of users did not contain them), do not overwrite existing values
                   8999: # unless field is in $candelete array ref.  
                   9000: #
                   9001: 
                   9002:     my @fields = ('firstname','middlename','lastname','generation',
                   9003:                   'permanentemail','id');
                   9004:     my %newvalues;
                   9005:     if (ref($candelete) eq 'ARRAY') {
                   9006:         foreach my $field (@fields) {
                   9007:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9008:                 if ($field eq 'firstname') {
                   9009:                     $names{$field} = $first;
                   9010:                 } elsif ($field eq 'middlename') {
                   9011:                     $names{$field} = $middle;
                   9012:                 } elsif ($field eq 'lastname') {
                   9013:                     $names{$field} = $last;
                   9014:                 } elsif ($field eq 'generation') { 
                   9015:                     $names{$field} = $gene;
                   9016:                 } elsif ($field eq 'permanentemail') {
                   9017:                     $names{$field} = $email;
                   9018:                 } elsif ($field eq 'id') {
                   9019:                     $names{$field}  = $uid;
                   9020:                 }
                   9021:             }
                   9022:         }
                   9023:     }
1.388     www      9024:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9025:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9026:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9027:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9028:     if ($email) {
                   9029:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9030:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9031:     }
1.899     raeburn  9032:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9033:     if (defined($inststatus)) {
                   9034:         $names{'inststatus'} = '';
                   9035:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9036:         if (ref($usertypes) eq 'HASH') {
                   9037:             my @okstatuses; 
                   9038:             foreach my $item (split(/:/,$inststatus)) {
                   9039:                 if (defined($usertypes->{$item})) {
                   9040:                     push(@okstatuses,$item);  
                   9041:                 }
                   9042:             }
                   9043:             if (@okstatuses) {
                   9044:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9045:             }
                   9046:         }
                   9047:     }
1.1075    raeburn  9048:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9049:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9050:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9051:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9052:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9053:     } else {
                   9054:         $logmsg .= ' during self creation';
                   9055:     }
1.1075    raeburn  9056:     my $changed;
                   9057:     if ($newuser) {
                   9058:         $changed = 1;
                   9059:     } else {
                   9060:         foreach my $field (@fields) {
                   9061:             if ($names{$field} ne $oldnames{$field}) {
                   9062:                 $changed = 1;
                   9063:                 last;
                   9064:             }
                   9065:         }
                   9066:     }
                   9067:     unless ($changed) {
                   9068:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9069:         &logthis($logmsg);
                   9070:         return 'ok';
                   9071:     }
                   9072:     my $reply = &put('environment', \%names, $udom,$uname);
                   9073:     if ($reply ne 'ok') { 
                   9074:         return 'error: '.$reply;
                   9075:     }
1.1087    raeburn  9076:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9077:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9078:     }
1.1075    raeburn  9079:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9080:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9081:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9082:     &logthis($logmsg);
1.134     albertel 9083:     return 'ok';
1.80      www      9084: }
                   9085: 
1.81      www      9086: # -------------------------------------------------------------- Modify student
1.80      www      9087: 
1.81      www      9088: sub modifystudent {
                   9089:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9090:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216    raeburn  9091:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 9092:     if (!$cid) {
1.620     albertel 9093: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9094: 	    return 'not_in_class';
                   9095: 	}
1.80      www      9096:     }
                   9097: # --------------------------------------------------------------- Make the user
1.81      www      9098:     my $reply=&modifyuser
1.209     matthew  9099: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9100:          $desiredhome,$email,$inststatus);
1.80      www      9101:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9102:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9103:     # student's environment
1.297     matthew  9104:     $uid = undef if (!$forceid);
1.455     albertel 9105:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9106:                                         $gene,$usec,$end,$start,$type,$locktype,
                   9107:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  9108:     return $reply;
                   9109: }
                   9110: 
                   9111: sub modify_student_enrollment {
1.1216    raeburn  9112:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   9113:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 9114:     my ($cdom,$cnum,$chome);
                   9115:     if (!$cid) {
1.620     albertel 9116: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9117: 	    return 'not_in_class';
                   9118: 	}
1.620     albertel 9119: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9120: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9121:     } else {
                   9122: 	($cdom,$cnum)=split(/_/,$cid);
                   9123:     }
1.620     albertel 9124:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9125:     if (!$chome) {
1.457     raeburn  9126: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9127:     }
1.455     albertel 9128:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9129:     # Make sure the user exists
1.81      www      9130:     my $uhome=&homeserver($uname,$udom);
                   9131:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9132: 	return 'error: no such user';
                   9133:     }
1.297     matthew  9134:     # Get student data if we were not given enough information
                   9135:     if (!defined($first)  || $first  eq '' || 
                   9136:         !defined($last)   || $last   eq '' || 
                   9137:         !defined($uid)    || $uid    eq '' || 
                   9138:         !defined($middle) || $middle eq '' || 
                   9139:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9140:         # They did not supply us with enough data to enroll the student, so
                   9141:         # we need to pick up more information.
1.297     matthew  9142:         my %tmp = &get('environment',
1.294     matthew  9143:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9144:                        ,$udom,$uname);
                   9145: 
1.800     albertel 9146:         #foreach my $key (keys(%tmp)) {
                   9147:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9148:         #}
1.294     matthew  9149:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9150:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9151:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9152:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9153:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9154:     }
1.556     albertel 9155:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9156:     my $user = "$uname:$udom";
                   9157:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9158:     my $reply=cput('classlist',
1.1148    raeburn  9159: 		   {$user => 
1.1216    raeburn  9160: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 9161: 		   $cdom,$cnum);
1.1148    raeburn  9162:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9163:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9164:     } else { 
1.81      www      9165: 	return 'error: '.$reply;
                   9166:     }
1.297     matthew  9167:     # Add student role to user
1.83      www      9168:     my $uurl='/'.$cid;
1.81      www      9169:     $uurl=~s/\_/\//g;
                   9170:     if ($usec) {
                   9171: 	$uurl.='/'.$usec;
                   9172:     }
1.1148    raeburn  9173:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9174:                              $selfenroll,$context);
                   9175:     if ($result ne 'ok') {
                   9176:         if ($old_entry{$user} ne '') {
                   9177:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9178:         } else {
                   9179:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9180:         }
                   9181:     }
                   9182:     return $result; 
1.21      www      9183: }
                   9184: 
1.556     albertel 9185: sub format_name {
                   9186:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9187:     my $name;
                   9188:     if ($first ne 'lastname') {
                   9189: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9190:     } else {
                   9191: 	if ($lastname=~/\S/) {
                   9192: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9193: 	    $name=~s/\s+,/,/;
                   9194: 	} else {
                   9195: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9196: 	}
                   9197:     }
                   9198:     $name=~s/^\s+//;
                   9199:     $name=~s/\s+$//;
                   9200:     $name=~s/\s+/ /g;
                   9201:     return $name;
                   9202: }
                   9203: 
1.84      www      9204: # ------------------------------------------------- Write to course preferences
                   9205: 
                   9206: sub writecoursepref {
                   9207:     my ($courseid,%prefs)=@_;
                   9208:     $courseid=~s/^\///;
                   9209:     $courseid=~s/\_/\//g;
                   9210:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9211:     my $chome=homeserver($cnum,$cdomain);
                   9212:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9213: 	return 'error: no such course';
                   9214:     }
                   9215:     my $cstring='';
1.800     albertel 9216:     foreach my $pref (keys(%prefs)) {
                   9217: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9218:     }
1.84      www      9219:     $cstring=~s/\&$//;
                   9220:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9221: }
                   9222: 
                   9223: # ---------------------------------------------------------- Make/modify course
                   9224: 
                   9225: sub createcourse {
1.741     raeburn  9226:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9227:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9228:     $url=&declutter($url);
                   9229:     my $cid='';
1.1028    raeburn  9230:     if ($context eq 'requestcourses') {
                   9231:         my $can_create = 0;
                   9232:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9233:         if ($udom eq $ownerdom) {
                   9234:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9235:                                   $context)) {
                   9236:                 $can_create = 1;
                   9237:             }
                   9238:         } else {
                   9239:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9240:                                            $category);
                   9241:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9242:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9243:                 if (@curr > 0) {
                   9244:                     my @options = qw(approval validate autolimit);
                   9245:                     my $optregex = join('|',@options);
                   9246:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9247:                         $can_create = 1;
                   9248:                     }
                   9249:                 }
                   9250:             }
                   9251:         }
                   9252:         if ($can_create) {
                   9253:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9254:                 unless (&allowed('ccc',$udom)) {
                   9255:                     return 'refused'; 
                   9256:                 }
1.1017    raeburn  9257:             }
                   9258:         } else {
                   9259:             return 'refused';
                   9260:         }
1.1028    raeburn  9261:     } elsif (!&allowed('ccc',$udom)) {
                   9262:         return 'refused';
1.84      www      9263:     }
1.1011    raeburn  9264: # --------------------------------------------------------------- Get Unique ID
                   9265:     my $uname;
                   9266:     if ($cnum =~ /^$match_courseid$/) {
                   9267:         my $chome=&homeserver($cnum,$udom,'true');
                   9268:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9269:             $uname = $cnum;
                   9270:         } else {
1.1038    raeburn  9271:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9272:         }
                   9273:     } else {
1.1038    raeburn  9274:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9275:     }
                   9276:     return $uname if ($uname =~ /^error/);
                   9277: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9278:     if (!defined($course_server)) {
                   9279:         if (defined(&domain($udom,'primary'))) {
                   9280:             $course_server = &domain($udom,'primary');
                   9281:         } else {
                   9282:             $course_server = $env{'user.home'}; 
                   9283:         }
                   9284:     }
                   9285:     my %host_servers =
                   9286:         &Apache::lonnet::get_servers($udom,'library');
                   9287:     unless ($host_servers{$course_server}) {
                   9288:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9289:     }
1.84      www      9290: # ------------------------------------------------------------- Make the course
                   9291:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9292:                       $course_server);
1.84      www      9293:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9294:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9295:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9296: 	return 'error: no such course';
                   9297:     }
1.271     www      9298: # ----------------------------------------------------------------- Course made
1.516     raeburn  9299: # log existence
1.1029    raeburn  9300:     my $now = time;
1.918     raeburn  9301:     my $newcourse = {
                   9302:                     $udom.'_'.$uname => {
1.921     raeburn  9303:                                      description => $description,
                   9304:                                      inst_code   => $inst_code,
                   9305:                                      owner       => $course_owner,
                   9306:                                      type        => $crstype,
1.1029    raeburn  9307:                                      creator     => $env{'user.name'}.':'.
                   9308:                                                     $env{'user.domain'},
                   9309:                                      created     => $now,
                   9310:                                      context     => $context,
1.918     raeburn  9311:                                                 },
                   9312:                     };
1.921     raeburn  9313:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9314: # set toplevel url
1.271     www      9315:     my $topurl=$url;
                   9316:     unless ($nonstandard) {
                   9317: # ------------------------------------------ For standard courses, make top url
                   9318:         my $mapurl=&clutter($url);
1.278     www      9319:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9320:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9321: <map>
                   9322: <resource id="1" type="start"></resource>
                   9323: <resource id="2" src="$mapurl"></resource>
                   9324: <resource id="3" type="finish"></resource>
                   9325: <link index="1" from="1" to="2"></link>
                   9326: <link index="2" from="2" to="3"></link>
                   9327: </map>
                   9328: ENDINITMAP
                   9329:         $topurl=&declutter(
1.638     albertel 9330:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9331:                           );
                   9332:     }
                   9333: # ----------------------------------------------------------- Write preferences
1.84      www      9334:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9335:                      ('description'              => $description,
                   9336:                       'url'                      => $topurl,
                   9337:                       'internal.creator'         => $env{'user.name'}.':'.
                   9338:                                                     $env{'user.domain'},
                   9339:                       'internal.created'         => $now,
                   9340:                       'internal.creationcontext' => $context)
                   9341:                     );
1.84      www      9342:     return '/'.$udom.'/'.$uname;
                   9343: }
                   9344: 
1.1011    raeburn  9345: # ------------------------------------------------------------------- Create ID
                   9346: sub generate_coursenum {
1.1038    raeburn  9347:     my ($udom,$crstype) = @_;
1.1011    raeburn  9348:     my $domdesc = &domain($udom);
                   9349:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9350:     my $first;
                   9351:     if ($crstype eq 'Community') {
                   9352:         $first = '0';
                   9353:     } else {
                   9354:         $first = int(1+rand(9)); 
                   9355:     } 
                   9356:     my $uname=$first.
1.1011    raeburn  9357:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9358:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9359:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9360: # ----------------------------------------------- Make sure that does not exist
                   9361:     my $uhome=&homeserver($uname,$udom,'true');
                   9362:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9363:         if ($crstype eq 'Community') {
                   9364:             $first = '0';
                   9365:         } else {
                   9366:             $first = int(1+rand(9));
                   9367:         }
                   9368:         $uname=$first.
1.1011    raeburn  9369:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9370:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9371:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9372:         $uhome=&homeserver($uname,$udom,'true');
                   9373:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9374:             return 'error: unable to generate unique course-ID';
                   9375:         }
                   9376:     }
                   9377:     return $uname;
                   9378: }
                   9379: 
1.813     albertel 9380: sub is_course {
1.1167    droeschl 9381:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9382:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9383: 
                   9384:     return unless $cdom and $cnum;
                   9385: 
                   9386:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9387:         '.');
                   9388: 
1.1219    raeburn  9389:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9390:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9391: }
                   9392: 
1.1015    raeburn  9393: sub store_userdata {
                   9394:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9395:     my $result;
1.1016    raeburn  9396:     if ($datakey ne '') {
1.1013    raeburn  9397:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9398:             if ($udom eq '' || $uname eq '') {
                   9399:                 $udom = $env{'user.domain'};
                   9400:                 $uname = $env{'user.name'};
                   9401:             }
                   9402:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9403:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9404:                 $result = 'error: no_host';
                   9405:             } else {
                   9406:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9407:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9408: 
                   9409:                 my $namevalue='';
                   9410:                 foreach my $key (keys(%{$storehash})) {
                   9411:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9412:                 }
                   9413:                 $namevalue=~s/\&$//;
1.1224    raeburn  9414:                 unless ($namespace eq 'courserequests') {
                   9415:                     $datakey = &escape($datakey);
                   9416:                 }
1.1105    raeburn  9417:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9418:                                   $namevalue,$uhome);
1.1013    raeburn  9419:             }
                   9420:         } else {
                   9421:             $result = 'error: data to store was not a hash reference'; 
                   9422:         }
                   9423:     } else {
                   9424:         $result= 'error: invalid requestkey'; 
                   9425:     }
                   9426:     return $result;
                   9427: }
                   9428: 
1.21      www      9429: # ---------------------------------------------------------- Assign Custom Role
                   9430: 
                   9431: sub assigncustomrole {
1.957     raeburn  9432:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9433:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9434:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9435: }
                   9436: 
                   9437: # ----------------------------------------------------------------- Revoke Role
                   9438: 
                   9439: sub revokerole {
1.957     raeburn  9440:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9441:     my $now=time;
1.965     raeburn  9442:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9443: }
                   9444: 
                   9445: # ---------------------------------------------------------- Revoke Custom Role
                   9446: 
                   9447: sub revokecustomrole {
1.957     raeburn  9448:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9449:     my $now=time;
1.357     www      9450:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9451:            $deleteflag,$selfenroll,$context);
1.17      www      9452: }
                   9453: 
1.533     banghart 9454: # ------------------------------------------------------------ Disk usage
1.535     albertel 9455: sub diskusage {
1.955     raeburn  9456:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9457:     $directorypath =~ s/\/$//;
                   9458:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9459:                        .&escape($getpropath).':'.&escape($uname).':'
                   9460:                        .&escape($udom),homeserver($uname,$udom));
                   9461:     if ($listing eq 'unknown_cmd') {
                   9462:         if ($getpropath) {
                   9463:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9464:         }
                   9465:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9466:     }
1.514     albertel 9467:     return $listing;
1.512     banghart 9468: }
                   9469: 
1.566     banghart 9470: sub is_locked {
1.1096    raeburn  9471:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9472:     my @check;
                   9473:     my $is_locked;
1.1093    raeburn  9474:     push (@check,$file_name);
1.613     albertel 9475:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9476: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9477:     my ($tmp)=keys(%locked);
                   9478:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9479:     
1.566     banghart 9480:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9481:         $is_locked = 'false';
                   9482:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9483:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9484:                $is_locked = 'true';
1.1096    raeburn  9485:                if (ref($which) eq 'ARRAY') {
                   9486:                    push(@{$which},$entry);
                   9487:                } else {
                   9488:                    last;
                   9489:                }
1.745     raeburn  9490:            }
                   9491:        }
1.566     banghart 9492:     } else {
                   9493:         $is_locked = 'false';
                   9494:     }
1.1093    raeburn  9495:     return $is_locked;
1.566     banghart 9496: }
                   9497: 
1.759     albertel 9498: sub declutter_portfile {
                   9499:     my ($file) = @_;
1.833     albertel 9500:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9501:     return $file;
                   9502: }
                   9503: 
1.559     banghart 9504: # ------------------------------------------------------------- Mark as Read Only
                   9505: 
                   9506: sub mark_as_readonly {
                   9507:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9508:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9509:     my ($tmp)=keys(%current_permissions);
                   9510:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9511:     foreach my $file (@{$files}) {
1.759     albertel 9512: 	$file = &declutter_portfile($file);
1.561     banghart 9513:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9514:     }
1.613     albertel 9515:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9516:     return;
                   9517: }
                   9518: 
1.572     banghart 9519: # ------------------------------------------------------------Save Selected Files
                   9520: 
                   9521: sub save_selected_files {
                   9522:     my ($user, $path, @files) = @_;
                   9523:     my $filename = $user."savedfiles";
1.573     banghart 9524:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9525:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9526:     foreach my $file (@files) {
1.620     albertel 9527:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9528:     }
                   9529:     foreach my $file (@other_files) {
1.574     banghart 9530:         print (OUT $file."\n");
1.572     banghart 9531:     }
1.574     banghart 9532:     close (OUT);
1.572     banghart 9533:     return 'ok';
                   9534: }
                   9535: 
1.574     banghart 9536: sub clear_selected_files {
                   9537:     my ($user) = @_;
                   9538:     my $filename = $user."savedfiles";
1.1117    foxr     9539:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9540:     print (OUT undef);
                   9541:     close (OUT);
                   9542:     return ("ok");    
                   9543: }
                   9544: 
1.572     banghart 9545: sub files_in_path {
                   9546:     my ($user, $path) = @_;
                   9547:     my $filename = $user."savedfiles";
                   9548:     my %return_files;
1.1117    foxr     9549:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9550:     while (my $line_in = <IN>) {
1.574     banghart 9551:         chomp ($line_in);
                   9552:         my @paths_and_file = split (m!/!, $line_in);
                   9553:         my $file_part = pop (@paths_and_file);
                   9554:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9555:         $path_part.='/';
                   9556:         my $path_and_file = $path_part.$file_part;
                   9557:         if ($path_part eq $path) {
                   9558:             $return_files{$file_part}= 'selected';
                   9559:         }
                   9560:     }
1.574     banghart 9561:     close (IN);
                   9562:     return (\%return_files);
1.572     banghart 9563: }
                   9564: 
                   9565: # called in portfolio select mode, to show files selected NOT in current directory
                   9566: sub files_not_in_path {
                   9567:     my ($user, $path) = @_;
                   9568:     my $filename = $user."savedfiles";
                   9569:     my @return_files;
                   9570:     my $path_part;
1.1117    foxr     9571:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9572:     while (my $line = <IN>) {
1.572     banghart 9573:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9574:         my @paths_and_file = split(m|/|, $line);
                   9575:         my $file_part = pop(@paths_and_file);
                   9576:         chomp($file_part);
                   9577:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9578:         $path_part .= '/';
                   9579:         my $path_and_file = $path_part.$file_part;
                   9580:         if ($path_part ne $path) {
1.800     albertel 9581:             push(@return_files, ($path_and_file));
1.572     banghart 9582:         }
                   9583:     }
1.800     albertel 9584:     close(OUT);
1.574     banghart 9585:     return (@return_files);
1.572     banghart 9586: }
                   9587: 
1.1273    raeburn  9588: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9589:  
                   9590: sub portfiles_versioning {
                   9591:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   9592:     my $portfolio_root = '/userfiles/portfolio';
                   9593:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   9594:     foreach my $file (@{$portfiles}) {
                   9595:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   9596:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   9597:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   9598:         my $getpropath = 1;
                   9599:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   9600:                                              $stu_name,$getpropath);
                   9601:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   9602:         my $new_answer = 
                   9603:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   9604:         if ($new_answer ne 'problem getting file') {
                   9605:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   9606:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   9607:                               [$symb,$env{'request.course.id'},'graded']);
                   9608:         }
                   9609:     }
                   9610: }
                   9611: 
                   9612: sub get_next_version {
                   9613:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   9614:     my $version;
                   9615:     if (ref($dir_list) eq 'ARRAY') {
                   9616:         foreach my $row (@{$dir_list}) {
                   9617:             my ($file) = split(/\&/,$row,2);
                   9618:             my ($file_name,$file_version,$file_ext) =
                   9619:                 &file_name_version_ext($file);
                   9620:             if (($file_name eq $answer_name) &&
                   9621:                 ($file_ext eq $answer_ext)) {
                   9622:                      # gets here if filename and extension match,
                   9623:                      # regardless of version
                   9624:                 if ($file_version ne '') {
                   9625:                     # a versioned file is found  so save it for later
                   9626:                     if ($file_version > $version) {
                   9627:                         $version = $file_version;
                   9628:                     }
                   9629:                 }
                   9630:             }
                   9631:         }
                   9632:     }
                   9633:     $version ++;
                   9634:     return($version);
                   9635: }
                   9636: 
                   9637: sub version_selected_portfile {
                   9638:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   9639:     my ($answer_name,$answer_ver,$answer_ext) =
                   9640:         &file_name_version_ext($file_name);
                   9641:     my $new_answer;
                   9642:     $env{'form.copy'} =
                   9643:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   9644:     if($env{'form.copy'} eq '-1') {
                   9645:         $new_answer = 'problem getting file';
                   9646:     } else {
                   9647:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   9648:         my $copy_result = 
                   9649:             &finishuserfileupload($stu_name,$domain,'copy',
                   9650:                                   '/portfolio'.$directory.$new_answer);
                   9651:     }
                   9652:     undef($env{'form.copy'});
                   9653:     return ($new_answer);
                   9654: }
                   9655: 
                   9656: sub file_name_version_ext {
                   9657:     my ($file)=@_;
                   9658:     my @file_parts = split(/\./, $file);
                   9659:     my ($name,$version,$ext);
                   9660:     if (@file_parts > 1) {
                   9661:         $ext=pop(@file_parts);
                   9662:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   9663:             $version=pop(@file_parts);
                   9664:         }
                   9665:         $name=join('.',@file_parts);
                   9666:     } else {
                   9667:         $name=join('.',@file_parts);
                   9668:     }
                   9669:     return($name,$version,$ext);
                   9670: }
                   9671: 
1.745     raeburn  9672: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9673: 
1.745     raeburn  9674: sub get_portfile_permissions {
                   9675:     my ($domain,$user) = @_;
1.613     albertel 9676:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9677:     my ($tmp)=keys(%current_permissions);
                   9678:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9679:     return \%current_permissions;
                   9680: }
                   9681: 
                   9682: #---------------------------------------------Get portfolio file access controls
                   9683: 
1.749     raeburn  9684: sub get_access_controls {
1.745     raeburn  9685:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9686:     my %access;
                   9687:     my $real_file = $file;
                   9688:     $file =~ s/\.meta$//;
1.745     raeburn  9689:     if (defined($file)) {
1.749     raeburn  9690:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9691:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9692:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9693:             }
                   9694:         }
1.745     raeburn  9695:     } else {
1.749     raeburn  9696:         foreach my $key (keys(%{$current_permissions})) {
                   9697:             if ($key =~ /\0accesscontrol$/) {
                   9698:                 if (defined($group)) {
                   9699:                     if ($key !~ m-^\Q$group\E/-) {
                   9700:                         next;
                   9701:                     }
                   9702:                 }
                   9703:                 my ($fullpath) = split(/\0/,$key);
                   9704:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9705:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9706:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9707:                     }
                   9708:                 }
                   9709:             }
                   9710:         }
                   9711:     }
                   9712:     return %access;
                   9713: }
                   9714: 
                   9715: sub modify_access_controls {
                   9716:     my ($file_name,$changes,$domain,$user)=@_;
                   9717:     my ($outcome,$deloutcome);
                   9718:     my %store_permissions;
                   9719:     my %new_values;
                   9720:     my %new_control;
                   9721:     my %translation;
                   9722:     my @deletions = ();
                   9723:     my $now = time;
                   9724:     if (exists($$changes{'activate'})) {
                   9725:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9726:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9727:             my $numnew = scalar(@newitems);
                   9728:             for (my $i=0; $i<$numnew; $i++) {
                   9729:                 my $newkey = $newitems[$i];
                   9730:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9731:                 if ($newkey =~ /^\d+:/) { 
                   9732:                     $newkey =~ s/^(\d+)/$newid/;
                   9733:                     $translation{$1} = $newid;
                   9734:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9735:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9736:                     $translation{$1} = $newid;
                   9737:                 }
1.749     raeburn  9738:                 $new_values{$file_name."\0".$newkey} = 
                   9739:                                           $$changes{'activate'}{$newitems[$i]};
                   9740:                 $new_control{$newkey} = $now;
                   9741:             }
                   9742:         }
                   9743:     }
                   9744:     my %todelete;
                   9745:     my %changed_items;
                   9746:     foreach my $action ('delete','update') {
                   9747:         if (exists($$changes{$action})) {
                   9748:             if (ref($$changes{$action}) eq 'HASH') {
                   9749:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9750:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9751:                     if ($action eq 'delete') { 
                   9752:                         $todelete{$itemnum} = 1;
                   9753:                     } else {
                   9754:                         $changed_items{$itemnum} = $key;
                   9755:                     }
                   9756:                 }
1.745     raeburn  9757:             }
                   9758:         }
1.749     raeburn  9759:     }
                   9760:     # get lock on access controls for file.
                   9761:     my $lockhash = {
                   9762:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9763:                                                        ':'.$env{'user.domain'},
                   9764:                    }; 
                   9765:     my $tries = 0;
                   9766:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9767:    
1.1288    damieng  9768:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  9769:         $tries ++;
1.1289    damieng  9770:         sleep(0.1);
1.749     raeburn  9771:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9772:     }
                   9773:     if ($gotlock eq 'ok') {
                   9774:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9775:         my ($tmp)=keys(%curr_permissions);
                   9776:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9777:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9778:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9779:             if (ref($curr_controls) eq 'HASH') {
                   9780:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9781:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9782:                     if (defined($todelete{$itemnum})) {
                   9783:                         push(@deletions,$file_name."\0".$control_item);
                   9784:                     } else {
                   9785:                         if (defined($changed_items{$itemnum})) {
                   9786:                             $new_control{$changed_items{$itemnum}} = $now;
                   9787:                             push(@deletions,$file_name."\0".$control_item);
                   9788:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9789:                         } else {
                   9790:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9791:                         }
                   9792:                     }
1.745     raeburn  9793:                 }
                   9794:             }
                   9795:         }
1.970     raeburn  9796:         my ($group);
                   9797:         if (&is_course($domain,$user)) {
                   9798:             ($group,my $file) = split(/\//,$file_name,2);
                   9799:         }
1.749     raeburn  9800:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9801:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9802:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9803:         #  remove lock
                   9804:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9805:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9806:         my $sqlresult =
1.970     raeburn  9807:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9808:                                     $group);
1.749     raeburn  9809:     } else {
                   9810:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9811:     }
1.749     raeburn  9812:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9813: }
                   9814: 
1.827     raeburn  9815: sub make_public_indefinitely {
1.1271    raeburn  9816:     my (@requrl) = @_;
                   9817:     return &automated_portfile_access('public',\@requrl);
                   9818: }
                   9819: 
                   9820: sub automated_portfile_access {
                   9821:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  9822:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   9823:         return 'invalid';
                   9824:     }
1.1271    raeburn  9825:     my %urls;
                   9826:     if (ref($addsref) eq 'ARRAY') {
                   9827:         foreach my $requrl (@{$addsref}) {
                   9828:             if (&is_portfolio_url($requrl)) {
                   9829:                 unless (exists($urls{$requrl})) {
                   9830:                     $urls{$requrl} = 'add';
                   9831:                 }
                   9832:             }
                   9833:         }
                   9834:     }
                   9835:     if (ref($delsref) eq 'ARRAY') {
                   9836:         foreach my $requrl (@{$delsref}) { 
                   9837:             if (&is_portfolio_url($requrl)) {
                   9838:                 unless (exists($urls{$requrl})) {
                   9839:                     $urls{$requrl} = 'delete'; 
                   9840:                 }
                   9841:             }
                   9842:         }
                   9843:     }
                   9844:     unless (keys(%urls)) {
                   9845:         return 'invalid';
                   9846:     }
                   9847:     my $ip;
                   9848:     if ($accesstype eq 'ip') {
                   9849:         if (ref($info) eq 'HASH') {
                   9850:             if ($info->{'ip'} ne '') {
                   9851:                 $ip = $info->{'ip'};
                   9852:             }
                   9853:         }
                   9854:         if ($ip eq '') {
                   9855:             return 'invalid';
                   9856:         }
                   9857:     }
                   9858:     my $errors;
1.827     raeburn  9859:     my $now = time;
1.1271    raeburn  9860:     my %current_perms;
                   9861:     foreach my $requrl (sort(keys(%urls))) {
                   9862:         my $action;
                   9863:         if ($urls{$requrl} eq 'add') {
                   9864:             $action = 'activate';
                   9865:         } else {
                   9866:             $action = 'none';
                   9867:         }
                   9868:         my $aclnum = 0;
1.827     raeburn  9869:         my (undef,$udom,$unum,$file_name,$group) =
                   9870:             &parse_portfolio_url($requrl);
1.1271    raeburn  9871:         unless (exists($current_perms{$unum.':'.$udom})) {
                   9872:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   9873:         }
                   9874:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  9875:                                                    $group,$file_name);
                   9876:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9877:             my ($num,$scope,$end,$start) = 
                   9878:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  9879:             if ($scope eq $accesstype) {
                   9880:                 if (($start <= $now) && ($end == 0)) {
                   9881:                     if ($accesstype eq 'ip') {
                   9882:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   9883:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   9884:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   9885:                                     if ($urls{$requrl} eq 'add') {
                   9886:                                         $action = 'none';
                   9887:                                         last;
                   9888:                                     } else {
                   9889:                                         $action = 'delete';
                   9890:                                         $aclnum = $num;
                   9891:                                         last;
                   9892:                                     }
                   9893:                                 }
                   9894:                             }
                   9895:                         }
                   9896:                     } elsif ($accesstype eq 'public') {
                   9897:                         if ($urls{$requrl} eq 'add') {
                   9898:                             $action = 'none';
                   9899:                             last;
                   9900:                         } else {
                   9901:                             $action = 'delete';
                   9902:                             $aclnum = $num;
                   9903:                             last;
                   9904:                         }
                   9905:                     }
                   9906:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  9907:                     $action = 'update';
                   9908:                     $aclnum = $num;
1.1271    raeburn  9909:                     last;
1.827     raeburn  9910:                 }
                   9911:             }
                   9912:         }
                   9913:         if ($action eq 'none') {
1.1271    raeburn  9914:             next;
1.827     raeburn  9915:         } else {
                   9916:             my %changes;
                   9917:             my $newend = 0;
                   9918:             my $newstart = $now;
1.1271    raeburn  9919:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  9920:             $changes{$action}{$newkey} = {
1.1271    raeburn  9921:                 type => $accesstype,
1.827     raeburn  9922:                 time => {
                   9923:                     start => $newstart,
                   9924:                     end   => $newend,
                   9925:                 },
                   9926:             };
1.1271    raeburn  9927:             if ($accesstype eq 'ip') {
                   9928:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   9929:             }
1.827     raeburn  9930:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9931:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  9932:             unless ($outcome eq 'ok') {
                   9933:                 $errors .= $outcome.' ';
                   9934:             }
1.827     raeburn  9935:         }
1.1271    raeburn  9936:     }
                   9937:     if ($errors) {
                   9938:         $errors =~ s/\s$//;
                   9939:         return $errors;
1.827     raeburn  9940:     } else {
1.1271    raeburn  9941:         return 'ok';
1.827     raeburn  9942:     }
                   9943: }
                   9944: 
1.745     raeburn  9945: #------------------------------------------------------Get Marked as Read Only
                   9946: 
                   9947: sub get_marked_as_readonly {
                   9948:     my ($domain,$user,$what,$group) = @_;
                   9949:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9950:     my @readonly_files;
1.629     banghart 9951:     my $cmp1=$what;
                   9952:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9953:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9954:         if (defined($group)) {
                   9955:             if ($file_name !~ m-^\Q$group\E/-) {
                   9956:                 next;
                   9957:             }
                   9958:         }
1.561     banghart 9959:         if (ref($value) eq "ARRAY"){
                   9960:             foreach my $stored_what (@{$value}) {
1.629     banghart 9961:                 my $cmp2=$stored_what;
1.759     albertel 9962:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9963:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9964:                 }
1.629     banghart 9965:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9966:                     push(@readonly_files, $file_name);
1.745     raeburn  9967:                     last;
1.563     banghart 9968:                 } elsif (!defined($what)) {
                   9969:                     push(@readonly_files, $file_name);
1.745     raeburn  9970:                     last;
1.561     banghart 9971:                 }
                   9972:             }
1.745     raeburn  9973:         }
1.561     banghart 9974:     }
                   9975:     return @readonly_files;
                   9976: }
1.577     banghart 9977: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9978: 
1.577     banghart 9979: sub get_marked_as_readonly_hash {
1.745     raeburn  9980:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9981:     my %readonly_files;
1.745     raeburn  9982:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9983:         if (defined($group)) {
                   9984:             if ($file_name !~ m-^\Q$group\E/-) {
                   9985:                 next;
                   9986:             }
                   9987:         }
1.577     banghart 9988:         if (ref($value) eq "ARRAY"){
                   9989:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9990:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9991:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9992:                         if ($lock_descriptor eq 'graded') {
                   9993:                             $readonly_files{$file_name} = 'graded';
                   9994:                         } elsif ($lock_descriptor eq 'handback') {
                   9995:                             $readonly_files{$file_name} = 'handback';
                   9996:                         } else {
                   9997:                             if (!exists($readonly_files{$file_name})) {
                   9998:                                 $readonly_files{$file_name} = 'locked';
                   9999:                             }
                   10000:                         }
1.745     raeburn  10001:                     }
1.750     banghart 10002:                 } 
1.577     banghart 10003:             }
                   10004:         } 
                   10005:     }
                   10006:     return %readonly_files;
                   10007: }
1.559     banghart 10008: # ------------------------------------------------------------ Unmark as Read Only
                   10009: 
                   10010: sub unmark_as_readonly {
1.629     banghart 10011:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10012:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10013:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10014:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10015:     my $symb_crs = $what;
                   10016:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10017:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10018:     my ($tmp)=keys(%current_permissions);
                   10019:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10020:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10021:     foreach my $file (@readonly_files) {
1.759     albertel 10022: 	my $clean_file = &declutter_portfile($file);
                   10023: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10024: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10025:         my @new_locks;
                   10026:         my @del_keys;
                   10027:         if (ref($current_locks) eq "ARRAY"){
                   10028:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10029:                 my $compare=$locker;
1.749     raeburn  10030:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10031:                     $compare=join('',@{$locker});
1.746     raeburn  10032:                     if ($compare ne $symb_crs) {
                   10033:                         push(@new_locks, $locker);
                   10034:                     }
1.563     banghart 10035:                 }
                   10036:             }
1.650     albertel 10037:             if (scalar(@new_locks) > 0) {
1.563     banghart 10038:                 $current_permissions{$file} = \@new_locks;
                   10039:             } else {
                   10040:                 push(@del_keys, $file);
1.613     albertel 10041:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10042:                 delete($current_permissions{$file});
1.563     banghart 10043:             }
                   10044:         }
1.561     banghart 10045:     }
1.613     albertel 10046:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10047:     return;
                   10048: }
1.512     banghart 10049: 
1.17      www      10050: # ------------------------------------------------------------ Directory lister
                   10051: 
                   10052: sub dirlist {
1.955     raeburn  10053:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10054:     $uri=~s/^\///;
                   10055:     $uri=~s/\/$//;
1.253     stredwic 10056:     my ($udom, $uname);
1.955     raeburn  10057:     if ($getuserdir) {
1.253     stredwic 10058:         $udom = $userdomain;
                   10059:         $uname = $username;
1.955     raeburn  10060:     } else {
                   10061:         (undef,$udom,$uname)=split(/\//,$uri);
                   10062:         if(defined($userdomain)) {
                   10063:             $udom = $userdomain;
                   10064:         }
                   10065:         if(defined($username)) {
                   10066:             $uname = $username;
                   10067:         }
1.253     stredwic 10068:     }
1.955     raeburn  10069:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10070: 
1.955     raeburn  10071:     $dirRoot = $perlvar{'lonDocRoot'};
                   10072:     if (defined($getpropath)) {
                   10073:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10074:         $dirRoot =~ s/\/$//;
1.955     raeburn  10075:     } elsif (defined($getuserdir)) {
                   10076:         my $subdir=$uname.'__';
                   10077:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10078:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10079:                    ."/$udom/$subdir/$uname";
                   10080:     } elsif (defined($alternateRoot)) {
                   10081:         $dirRoot = $alternateRoot;
1.751     banghart 10082:     }
1.253     stredwic 10083: 
                   10084:     if($udom) {
                   10085:         if($uname) {
1.1135    raeburn  10086:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10087:             if ($uhome eq 'no_host') {
                   10088:                 return ([],'no_host');
                   10089:             }
1.955     raeburn  10090:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10091:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10092:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10093:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10094:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10095:             } else {
                   10096:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10097:             }
1.605     matthew  10098:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10099:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10100:                 @listing_results = split(/:/,$listing);
                   10101:             } else {
                   10102:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10103:             }
1.1135    raeburn  10104:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10105:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10106:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10107:                 return ([],$listing);
                   10108:             } else {
                   10109:                 return (\@listing_results);
1.1135    raeburn  10110:             }
1.955     raeburn  10111:         } elsif(!$alternateRoot) {
1.1136    raeburn  10112:             my (%allusers,%listerror);
1.841     albertel 10113: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10114:  	    foreach my $tryserver (keys(%servers)) {
                   10115:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10116:                                   &escape($udom),$tryserver);
                   10117:                 if ($listing eq 'unknown_cmd') {
                   10118: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10119: 				      $udom, $tryserver);
                   10120:                 } else {
                   10121:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10122:                 }
1.841     albertel 10123: 		if ($listing eq 'unknown_cmd') {
                   10124: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10125: 				      $udom, $tryserver);
                   10126: 		    @listing_results = split(/:/,$listing);
                   10127: 		} else {
                   10128: 		    @listing_results =
                   10129: 			map { &unescape($_); } split(/:/,$listing);
                   10130: 		}
1.1136    raeburn  10131:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10132:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10133:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10134:                     $listerror{$tryserver} = $listing;
                   10135:                 } else {
1.841     albertel 10136: 		    foreach my $line (@listing_results) {
                   10137: 			my ($entry) = split(/&/,$line,2);
                   10138: 			$allusers{$entry} = 1;
                   10139: 		    }
                   10140: 		}
1.253     stredwic 10141:             }
1.1136    raeburn  10142:             my @alluserslist=();
1.800     albertel 10143:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10144:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10145:             }
1.1136    raeburn  10146:             return (\@alluserslist);
1.253     stredwic 10147:         } else {
1.1136    raeburn  10148:             return ([],'missing username');
1.253     stredwic 10149:         }
1.955     raeburn  10150:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10151:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10152:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10153:         return (\@all_domains);
1.955     raeburn  10154:     } else {
1.1136    raeburn  10155:         return ([],'missing domain');
1.275     stredwic 10156:     }
                   10157: }
                   10158: 
                   10159: # --------------------------------------------- GetFileTimestamp
                   10160: # This function utilizes dirlist and returns the date stamp for
                   10161: # when it was last modified.  It will also return an error of -1
                   10162: # if an error occurs
                   10163: 
                   10164: sub GetFileTimestamp {
1.955     raeburn  10165:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10166:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10167:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10168:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10169:                                     undef,$getuserdir);
                   10170:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10171:         return -1;
                   10172:     }
                   10173:     if (ref($fileref) eq 'ARRAY') {
                   10174:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10175:         # @stats contains first the filename, then the stat output
                   10176:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10177:     } else {
                   10178:         return -1;
1.253     stredwic 10179:     }
1.26      www      10180: }
                   10181: 
1.712     albertel 10182: sub stat_file {
                   10183:     my ($uri) = @_;
1.787     albertel 10184:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10185: 
1.955     raeburn  10186:     my ($udom,$uname,$file);
1.712     albertel 10187:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10188: 	($udom,$uname,$file) =
1.811     albertel 10189: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10190: 	$file = 'userfiles/'.$file;
                   10191:     }
                   10192:     if ($uri =~ m-^/res/-) {
                   10193: 	($udom,$uname) = 
1.807     albertel 10194: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10195: 	$file = $uri;
                   10196:     }
                   10197: 
                   10198:     if (!$udom || !$uname || !$file) {
                   10199: 	# unable to handle the uri
                   10200: 	return ();
                   10201:     }
1.956     raeburn  10202:     my $getpropath;
                   10203:     if ($file =~ /^userfiles\//) {
                   10204:         $getpropath = 1;
                   10205:     }
1.1136    raeburn  10206:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10207:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10208:         return ();
                   10209:     } else {
                   10210:         if (ref($listref) eq 'ARRAY') {
                   10211:             my @stats = split('&',$listref->[0]);
                   10212: 	    shift(@stats); #filename is first
                   10213: 	    return @stats;
                   10214:         }
1.712     albertel 10215:     }
                   10216:     return ();
                   10217: }
                   10218: 
1.1313  ! raeburn  10219: # --------------------------------------------------------- recursedirs
        !          10220: # Recursive function to traverse either a specific user's Authoring Space
        !          10221: # or corresponding Published Resource Space, and populate the hash ref:
        !          10222: # $dirhashref with URLs of all directories, and if $filehashref hash
        !          10223: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
        !          10224: # or .rights files in resource space, and .meta, .save, .log, and .bak
        !          10225: # files in Authoring Space.
        !          10226: #
        !          10227: # Inputs:
        !          10228: #
        !          10229: # $is_home - true if current server is home server for user's space
        !          10230: # $context - either: priv, or res respectively for Authoring or Resource Space.
        !          10231: # $docroot - Document root (i.e., /home/httpd/html
        !          10232: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
        !          10233: # $relpath - Current path (relative to top level).
        !          10234: # $dirhashref - reference to hash to populate with URLs of directories (Required)
        !          10235: # $filehashref - reference to hash to populate with URLs of files (Optional)
        !          10236: #
        !          10237: # Returns: nothing
        !          10238: #
        !          10239: # Side Effects: populates $dirhashref, and $filehashref (if provided).
        !          10240: #
        !          10241: # Currently used by interface/londocs.pm to create linked select boxes for
        !          10242: # directory and filename to import a Course "Author" resource into a course, and
        !          10243: # also to create linked select boxes for Authoring Space and Directory to choose
        !          10244: # save location for creation of a new "standard" problem from the Course Editor.
        !          10245: #
        !          10246: 
        !          10247: sub recursedirs {
        !          10248:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
        !          10249:     return unless (ref($dirhashref) eq 'HASH');
        !          10250:     my $currpath = $docroot.$toppath;
        !          10251:     if ($relpath) {
        !          10252:         $currpath .= "/$relpath";
        !          10253:     }
        !          10254:     my $savefile;
        !          10255:     if (ref($filehashref)) {
        !          10256:         $savefile = 1;
        !          10257:     }
        !          10258:     if ($is_home) {
        !          10259:         if (opendir(my $dirh,$currpath)) {
        !          10260:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
        !          10261:                 next if ($item eq '');
        !          10262:                 if (-d "$currpath/$item") {
        !          10263:                     my $newpath;
        !          10264:                     if ($relpath) {
        !          10265:                         $newpath = "$relpath/$item";
        !          10266:                     } else {
        !          10267:                         $newpath = $item;
        !          10268:                     }
        !          10269:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
        !          10270:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
        !          10271:                 } elsif ($savefile) {
        !          10272:                     if ($context eq 'priv') {
        !          10273:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
        !          10274:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
        !          10275:                         }
        !          10276:                     } else {
        !          10277:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
        !          10278:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
        !          10279:                         }
        !          10280:                     }
        !          10281:                 }
        !          10282:             }
        !          10283:             closedir($dirh);
        !          10284:         }
        !          10285:     } else {
        !          10286:         my ($dirlistref,$listerror) =
        !          10287:             &dirlist($toppath.$relpath);
        !          10288:         my @dir_lines;
        !          10289:         my $dirptr=16384;
        !          10290:         if (ref($dirlistref) eq 'ARRAY') {
        !          10291:             foreach my $dir_line (sort
        !          10292:                               {
        !          10293:                                   my ($afile)=split('&',$a,2);
        !          10294:                                   my ($bfile)=split('&',$b,2);
        !          10295:                                   return (lc($afile) cmp lc($bfile));
        !          10296:                               } (@{$dirlistref})) {
        !          10297:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
        !          10298:                     split(/\&/,$dir_line,16);
        !          10299:                 $item =~ s/\s+$//;
        !          10300:                 next if (($item =~ /^\.\.?$/) || ($obs));
        !          10301:                 if ($dirptr&$testdir) {
        !          10302:                     my $newpath;
        !          10303:                     if ($relpath) {
        !          10304:                         $newpath = "$relpath/$item";
        !          10305:                     } else {
        !          10306:                         $relpath = '/';
        !          10307:                         $newpath = $item;
        !          10308:                     }
        !          10309:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
        !          10310:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
        !          10311:                 } elsif ($savefile) {
        !          10312:                     if ($context eq 'priv') {
        !          10313:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
        !          10314:                             $filehashref->{$relpath}{$item} = 1;
        !          10315:                         }
        !          10316:                     } else {
        !          10317:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
        !          10318:                             $filehashref->{$relpath}{$item} = 1;
        !          10319:                         }
        !          10320:                     }
        !          10321:                 }
        !          10322:             }
        !          10323:         }
        !          10324:     }
        !          10325:     return;
        !          10326: }
        !          10327: 
1.26      www      10328: # -------------------------------------------------------- Value of a Condition
                   10329: 
1.713     albertel 10330: # gets the value of a specific preevaluated condition
                   10331: #    stored in the string  $env{user.state.<cid>}
                   10332: # or looks up a condition reference in the bighash and if if hasn't
                   10333: # already been evaluated recurses into docondval to get the value of
                   10334: # the condition, then memoizing it to 
                   10335: #   $env{user.state.<cid>.<condition>}
1.40      www      10336: sub directcondval {
                   10337:     my $number=shift;
1.620     albertel 10338:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10339: 	&Apache::lonuserstate::evalstate();
                   10340:     }
1.713     albertel 10341:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10342: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10343:     } elsif ($number =~ /^_/) {
                   10344: 	my $sub_condition;
                   10345: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10346: 		&GDBM_READER(),0640)) {
                   10347: 	    $sub_condition=$bighash{'conditions'.$number};
                   10348: 	    untie(%bighash);
                   10349: 	}
                   10350: 	my $value = &docondval($sub_condition);
1.949     raeburn  10351: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10352: 	return $value;
                   10353:     }
1.620     albertel 10354:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10355:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10356:     } else {
                   10357:        return 2;
                   10358:     }
                   10359: }
                   10360: 
1.713     albertel 10361: # get the collection of conditions for this resource
1.26      www      10362: sub condval {
                   10363:     my $condidx=shift;
1.54      www      10364:     my $allpathcond='';
1.713     albertel 10365:     foreach my $cond (split(/\|/,$condidx)) {
                   10366: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10367: 	    $allpathcond.=
                   10368: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10369: 	}
1.191     harris41 10370:     }
1.54      www      10371:     $allpathcond=~s/\|$//;
1.713     albertel 10372:     return &docondval($allpathcond);
                   10373: }
                   10374: 
                   10375: #evaluates an expression of conditions
                   10376: sub docondval {
                   10377:     my ($allpathcond) = @_;
                   10378:     my $result=0;
                   10379:     if ($env{'request.course.id'}
                   10380: 	&& defined($allpathcond)) {
                   10381: 	my $operand='|';
                   10382: 	my @stack;
                   10383: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10384: 	    if ($chunk eq '(') {
                   10385: 		push @stack,($operand,$result);
                   10386: 	    } elsif ($chunk eq ')') {
                   10387: 		my $before=pop @stack;
                   10388: 		if (pop @stack eq '&') {
                   10389: 		    $result=$result>$before?$before:$result;
                   10390: 		} else {
                   10391: 		    $result=$result>$before?$result:$before;
                   10392: 		}
                   10393: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10394: 		$operand=$chunk;
                   10395: 	    } else {
                   10396: 		my $new=directcondval($chunk);
                   10397: 		if ($operand eq '&') {
                   10398: 		    $result=$result>$new?$new:$result;
                   10399: 		} else {
                   10400: 		    $result=$result>$new?$result:$new;
                   10401: 		}
                   10402: 	    }
                   10403: 	}
1.26      www      10404:     }
                   10405:     return $result;
1.421     albertel 10406: }
                   10407: 
                   10408: # ---------------------------------------------------- Devalidate courseresdata
                   10409: 
                   10410: sub devalidatecourseresdata {
                   10411:     my ($coursenum,$coursedomain)=@_;
                   10412:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10413:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10414: }
                   10415: 
1.763     www      10416: 
1.200     www      10417: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10418: #
                   10419: #  Parameters:
                   10420: #      $coursenum    - Number of the course.
                   10421: #      $coursedomain - Domain at which the course was created.
                   10422: #  Returns:
                   10423: #     A hash of the course parameters along (I think) with timestamps
                   10424: #     and version info.
1.877     foxr     10425: 
1.624     albertel 10426: sub get_courseresdata {
                   10427:     my ($coursenum,$coursedomain)=@_;
1.200     www      10428:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10429:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10430:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10431:     my %dumpreply;
1.417     albertel 10432:     unless (defined($cached)) {
1.624     albertel 10433: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10434: 	$result=\%dumpreply;
1.251     albertel 10435: 	my ($tmp) = keys(%dumpreply);
                   10436: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10437: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10438: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10439: 	    return $tmp;
1.416     albertel 10440: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10441: 	    $result=undef;
1.599     albertel 10442: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10443: 	}
                   10444:     }
1.624     albertel 10445:     return $result;
                   10446: }
                   10447: 
1.633     albertel 10448: sub devalidateuserresdata {
                   10449:     my ($uname,$udom)=@_;
                   10450:     my $hashid="$udom:$uname";
                   10451:     &devalidate_cache_new('userres',$hashid);
                   10452: }
                   10453: 
1.624     albertel 10454: sub get_userresdata {
                   10455:     my ($uname,$udom)=@_;
                   10456:     #most student don\'t have any data set, check if there is some data
                   10457:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10458: 
                   10459:     my $hashid="$udom:$uname";
                   10460:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10461:     if (!defined($cached)) {
                   10462: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10463: 	$result=\%resourcedata;
                   10464: 	&do_cache_new('userres',$hashid,$result,600);
                   10465:     }
                   10466:     my ($tmp)=keys(%$result);
                   10467:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10468: 	return $result;
                   10469:     }
                   10470:     #error 2 occurs when the .db doesn't exist
                   10471:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  10472:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10473: 	    &logthis("<font color=\"blue\">WARNING:".
                   10474: 		     " Trying to get resource data for ".
                   10475: 		     $uname." at ".$udom.": ".
                   10476: 		     $tmp."</font>");
                   10477:         }
1.624     albertel 10478:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10479: 	#&EXT_cache_set($udom,$uname);
                   10480: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10481: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10482:     }
                   10483:     return $tmp;
                   10484: }
1.879     foxr     10485: #----------------------------------------------- resdata - return resource data
                   10486: #  Purpose:
                   10487: #    Return resource data for either users or for a course.
                   10488: #  Parameters:
                   10489: #     $name      - Course/user name.
                   10490: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  10491: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  10492: #     $mapp      - decluttered URL of enclosing map  
                   10493: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   10494: #     $recurseup - Ref to array of map URLs, starting with map containing
                   10495: #                  $mapp up through hierarchy of nested maps to top level map.  
                   10496: #     $courseid  - CourseID (first part of param identifier).
                   10497: #     $modifier  - Middle part of param identifier.
                   10498: #     $what      - Last part of param identifier.
1.879     foxr     10499: #     @which     - Array of names of resources desired.
                   10500: #  Returns:
                   10501: #     The value of the first reasource in @which that is found in the
                   10502: #     resource hash.
                   10503: #  Exceptional Conditions:
                   10504: #     If the $type passed in is not valid (not the string 'course' or 
                   10505: #     'user', an undefined  reference is returned.
                   10506: #     If none of the resources are found, an undef is returned
1.624     albertel 10507: sub resdata {
1.1301    raeburn  10508:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   10509:         $modifier,$what,@which)=@_;
1.624     albertel 10510:     my $result;
                   10511:     if ($type eq 'course') {
                   10512: 	$result=&get_courseresdata($name,$domain);
                   10513:     } elsif ($type eq 'user') {
                   10514: 	$result=&get_userresdata($name,$domain);
                   10515:     }
                   10516:     if (!ref($result)) { return $result; }    
1.251     albertel 10517:     foreach my $item (@which) {
1.1301    raeburn  10518:         if ($item->[1] eq 'course') {
                   10519:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   10520:                 unless ($$recursed) {
1.1302    raeburn  10521:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  10522:                     $$recursed = 1;
                   10523:                 }
                   10524:                 foreach my $item (@${recurseup}) {
                   10525:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   10526:                     last if (defined($result->{$norecursechk}));
                   10527:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   10528:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   10529:                 }
                   10530:             }
                   10531:         }
                   10532:         if (defined($result->{$item->[0]})) {
1.927     albertel 10533: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10534: 	}
1.250     albertel 10535:     }
1.291     albertel 10536:     return undef;
1.200     www      10537: }
                   10538: 
1.1298    raeburn  10539: sub get_domain_ltitools {
                   10540:     my ($cdom) = @_;
                   10541:     my %ltitools;
                   10542:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   10543:     if (defined($cached)) {
                   10544:         if (ref($result) eq 'HASH') {
                   10545:             %ltitools = %{$result};
                   10546:         }
                   10547:     } else {
                   10548:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   10549:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   10550:             %ltitools = %{$domconfig{'ltitools'}};
                   10551:         }
                   10552:         my $cachetime = 24*60*60;
                   10553:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   10554:     }
                   10555:     return %ltitools;
                   10556: }
                   10557: 
1.1236    raeburn  10558: sub get_numsuppfiles {
                   10559:     my ($cnum,$cdom,$ignorecache)=@_;
                   10560:     my $hashid=$cnum.':'.$cdom;
                   10561:     my ($suppcount,$cached);
                   10562:     unless ($ignorecache) {
                   10563:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10564:     }
                   10565:     unless (defined($cached)) {
                   10566:         my $chome=&homeserver($cnum,$cdom);
                   10567:         unless ($chome eq 'no_host') {
                   10568:             ($suppcount,my $errors) = (0,0);
                   10569:             my $suppmap = 'supplemental.sequence';
                   10570:             ($suppcount,$errors) = 
                   10571:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10572:         }
                   10573:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10574:     }
                   10575:     return $suppcount;
                   10576: }
                   10577: 
1.379     matthew  10578: #
                   10579: # EXT resource caching routines
                   10580: #
                   10581: 
1.1302    raeburn  10582: {
                   10583: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   10584: #
                   10585: # The course for which we cache
                   10586: my $cachedmapkey='';
                   10587: # The cached recursive maps for this course
                   10588: my %cachedmaps=();
                   10589: # When this was last done
                   10590: my $cachedmaptime='';
                   10591: 
1.379     matthew  10592: sub clear_EXT_cache_status {
1.383     albertel 10593:     &delenv('cache.EXT.');
1.379     matthew  10594: }
                   10595: 
                   10596: sub EXT_cache_status {
                   10597:     my ($target_domain,$target_user) = @_;
1.383     albertel 10598:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10599:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10600:         # We know already the user has no data
                   10601:         return 1;
                   10602:     } else {
                   10603:         return 0;
                   10604:     }
                   10605: }
                   10606: 
                   10607: sub EXT_cache_set {
                   10608:     my ($target_domain,$target_user) = @_;
1.383     albertel 10609:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10610:     #&appenv({$cachename => time});
1.379     matthew  10611: }
                   10612: 
1.28      www      10613: # --------------------------------------------------------- Value of a Variable
1.58      www      10614: sub EXT {
1.715     albertel 10615: 
1.1228    raeburn  10616:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10617:     unless ($varname) { return ''; }
1.218     albertel 10618:     #get real user name/domain, courseid and symb
                   10619:     my $courseid;
1.359     albertel 10620:     my $publicuser;
1.427     www      10621:     if ($symbparm) {
                   10622: 	$symbparm=&get_symb_from_alias($symbparm);
                   10623:     }
1.218     albertel 10624:     if (!($uname && $udom)) {
1.790     albertel 10625:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10626:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10627:     } else {
1.620     albertel 10628: 	$courseid=$env{'request.course.id'};
1.218     albertel 10629:     }
1.48      www      10630:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10631:     my $rest;
1.320     albertel 10632:     if (defined($therest[0])) {
1.48      www      10633:        $rest=join('.',@therest);
                   10634:     } else {
                   10635:        $rest='';
                   10636:     }
1.320     albertel 10637: 
1.57      www      10638:     my $qualifierrest=$qualifier;
                   10639:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10640:     my $spacequalifierrest=$space;
                   10641:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10642:     if ($realm eq 'user') {
1.48      www      10643: # --------------------------------------------------------------- user.resource
                   10644: 	if ($space eq 'resource') {
1.651     albertel 10645: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10646: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10647: 		 &&
1.744     albertel 10648: 		 ($symbparm eq &symbread()) ) {	
                   10649: 		# if we are in the middle of processing the resource the
                   10650: 		# get the value we are planning on committing
                   10651:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10652:                     return $Apache::lonhomework::results{$qualifierrest};
                   10653:                 } else {
                   10654:                     return $Apache::lonhomework::history{$qualifierrest};
                   10655:                 }
1.335     albertel 10656: 	    } else {
1.359     albertel 10657: 		my %restored;
1.620     albertel 10658: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10659: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10660: 		} else {
                   10661: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10662: 		}
1.335     albertel 10663: 		return $restored{$qualifierrest};
                   10664: 	    }
1.48      www      10665: # ----------------------------------------------------------------- user.access
                   10666:         } elsif ($space eq 'access') {
1.218     albertel 10667: 	    # FIXME - not supporting calls for a specific user
1.48      www      10668:             return &allowed($qualifier,$rest);
                   10669: # ------------------------------------------ user.preferences, user.environment
                   10670:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10671: 	    if (($uname eq $env{'user.name'}) &&
                   10672: 		($udom eq $env{'user.domain'})) {
                   10673: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10674: 	    } else {
1.359     albertel 10675: 		my %returnhash;
                   10676: 		if (!$publicuser) {
                   10677: 		    %returnhash=&userenvironment($udom,$uname,
                   10678: 						 $qualifierrest);
                   10679: 		}
1.218     albertel 10680: 		return $returnhash{$qualifierrest};
                   10681: 	    }
1.48      www      10682: # ----------------------------------------------------------------- user.course
                   10683:         } elsif ($space eq 'course') {
1.218     albertel 10684: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10685:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10686: # ------------------------------------------------------------------- user.role
                   10687:         } elsif ($space eq 'role') {
1.218     albertel 10688: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10689:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10690:             if ($qualifier eq 'value') {
                   10691: 		return $role;
                   10692:             } elsif ($qualifier eq 'extent') {
                   10693:                 return $where;
                   10694:             }
                   10695: # ----------------------------------------------------------------- user.domain
                   10696:         } elsif ($space eq 'domain') {
1.218     albertel 10697:             return $udom;
1.48      www      10698: # ------------------------------------------------------------------- user.name
                   10699:         } elsif ($space eq 'name') {
1.218     albertel 10700:             return $uname;
1.48      www      10701: # ---------------------------------------------------- Any other user namespace
1.29      www      10702:         } else {
1.359     albertel 10703: 	    my %reply;
                   10704: 	    if (!$publicuser) {
                   10705: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10706: 	    }
                   10707: 	    return $reply{$qualifierrest};
1.48      www      10708:         }
1.236     www      10709:     } elsif ($realm eq 'query') {
                   10710: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10711:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10712: 						[$spacequalifierrest]);
1.620     albertel 10713: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10714:    } elsif ($realm eq 'request') {
1.48      www      10715: # ------------------------------------------------------------- request.browser
                   10716:         if ($space eq 'browser') {
1.1145    bisitz   10717:             return $env{'browser.'.$qualifier};
1.57      www      10718: # ------------------------------------------------------------ request.filename
                   10719:         } else {
1.620     albertel 10720:             return $env{'request.'.$spacequalifierrest};
1.29      www      10721:         }
1.28      www      10722:     } elsif ($realm eq 'course') {
1.48      www      10723: # ---------------------------------------------------------- course.description
1.620     albertel 10724:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10725:     } elsif ($realm eq 'resource') {
1.165     www      10726: 
1.620     albertel 10727: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10728: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10729: 	}
1.693     albertel 10730: 
1.1232    raeburn  10731:         if ($qualifier eq '') {
                   10732: 	    if ($space eq 'title') {
                   10733: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10734: 	        return &gettitle($symbparm);
                   10735: 	    }
1.693     albertel 10736: 	
1.1232    raeburn  10737: 	    if ($space eq 'map') {
                   10738: 	        my ($map) = &decode_symb($symbparm);
                   10739: 	        return &symbread($map);
                   10740: 	    }
                   10741:             if ($space eq 'maptitle') {
                   10742:                 my ($map) = &decode_symb($symbparm);
                   10743:                 return &gettitle($map);
                   10744:             }
                   10745: 	    if ($space eq 'filename') {
                   10746: 	        if ($symbparm) {
                   10747: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10748: 	        }
                   10749: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10750: 	    }
1.1232    raeburn  10751: 
1.1233    raeburn  10752:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10753:                 if ($space eq 'visibleparts') {
                   10754:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10755:                     my $item;
                   10756:                     if (ref($navmap)) {
                   10757:                         my $res = $navmap->getBySymb($symbparm);
                   10758:                         my $parts = $res->parts();
                   10759:                         if (ref($parts) eq 'ARRAY') {
                   10760:                             $item = join(',',@{$parts});
                   10761:                         }
                   10762:                         undef($navmap);
1.1232    raeburn  10763:                     }
1.1233    raeburn  10764:                     return $item;
1.1232    raeburn  10765:                 }
                   10766:             }
                   10767:         }
1.693     albertel 10768: 
1.1301    raeburn  10769: 	my ($section, $group, @groups, @recurseup, $recursed);
                   10770: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  10771:         if (($courseid eq '') && ($cid)) {
                   10772:             $courseid = $cid;
                   10773:         }
                   10774: 	if (($symbparm && $courseid) && 
                   10775: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      10776: 
1.218     albertel 10777: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10778: 
1.60      www      10779: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10780: 	    my $symbp=$symbparm;
1.1301    raeburn  10781: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10782: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  10783:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 10784: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 10785: 	    if (($env{'user.name'} eq $uname) &&
                   10786: 		($env{'user.domain'} eq $udom)) {
                   10787: 		$section=$env{'request.course.sec'};
1.733     raeburn  10788:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10789:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10790: 	    } else {
1.539     albertel 10791: 		if (! defined($usection)) {
1.551     albertel 10792: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10793: 		} else {
                   10794: 		    $section = $usection;
                   10795: 		}
1.733     raeburn  10796:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10797: 	    }
                   10798: 
                   10799: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10800: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  10801:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 10802: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10803: 
1.593     albertel 10804: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10805: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  10806:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 10807: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10808: 
1.60      www      10809: # ----------------------------------------------------------- first, check user
1.624     albertel 10810: 
1.1301    raeburn  10811: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   10812:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 10813: 				       ([$courselevelr,'resource'],
                   10814: 					[$courselevelm,'map'     ],
1.1301    raeburn  10815:                                         [$courseleveli,'map'     ],
1.927     albertel 10816: 					[$courselevel, 'course'  ]));
1.931     albertel 10817: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10818: 
1.594     albertel 10819: # ------------------------------------------------ second, check some of course
1.684     raeburn  10820:             my $coursereply;
1.691     raeburn  10821:             if (@groups > 0) {
                   10822:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  10823:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   10824:                                        $mapp,\$recursed,\@recurseup);
                   10825:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  10826:             }
1.96      www      10827: 
1.684     raeburn  10828: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10829: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10830: 				  'course',$mapp,\$recursed,\@recurseup,
                   10831:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 10832: 				  ([$seclevelr,   'resource'],
                   10833: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  10834:                                    [$secleveli,   'map'     ],
1.927     albertel 10835: 				   [$seclevel,    'course'  ],
                   10836: 				   [$courselevelr,'resource']));
                   10837: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10838: 
1.60      www      10839: # ------------------------------------------------------ third, check map parms
1.218     albertel 10840: 	    my %parmhash=();
                   10841: 	    my $thisparm='';
                   10842: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10843: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10844: 		    &GDBM_READER(),0640)) {
1.218     albertel 10845: 		$thisparm=$parmhash{$symbparm};
                   10846: 		untie(%parmhash);
                   10847: 	    }
1.927     albertel 10848: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10849: 	}
1.594     albertel 10850: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  10851:  
                   10852:         my $what = $spacequalifierrest;
                   10853: 	$what=~s/\./\_/;
1.282     albertel 10854: 	my $filename;
                   10855: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10856: 	if ($symbparm) {
1.409     www      10857: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10858: 	} else {
1.620     albertel 10859: 	    $filename=$env{'request.filename'};
1.282     albertel 10860: 	}
1.1301    raeburn  10861: 	my $metadata=&metadata($filename,$what);
1.927     albertel 10862: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301    raeburn  10863: 	$metadata=&metadata($filename,'parameter_'.$what);
1.927     albertel 10864: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10865: 
1.1301    raeburn  10866: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 10867: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10868: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10869: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10870: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10871: 				     'course',$mapp,\$recursed,\@recurseup,
                   10872:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 10873: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  10874:                                       [$courseleveli,'map'   ],
1.927     albertel 10875: 				      [$courselevel, 'course']));
                   10876: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10877: 	}
1.145     www      10878: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10879: 	unless ($space eq '0') {
1.336     albertel 10880: 	    my @parts=split(/_/,$space);
                   10881: 	    my $id=pop(@parts);
                   10882: 	    my $part=join('_',@parts);
                   10883: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10884: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10885: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10886: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10887: 	}
1.395     albertel 10888: 	if ($recurse) { return undef; }
                   10889: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10890: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10891: # ---------------------------------------------------- Any other user namespace
                   10892:     } elsif ($realm eq 'environment') {
                   10893: # ----------------------------------------------------------------- environment
1.620     albertel 10894: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10895: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10896: 	} else {
1.770     albertel 10897: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10898: 		return '';
                   10899: 	    }
1.219     albertel 10900: 	    my %returnhash=&userenvironment($udom,$uname,
                   10901: 					    $spacequalifierrest);
                   10902: 	    return $returnhash{$spacequalifierrest};
                   10903: 	}
1.28      www      10904:     } elsif ($realm eq 'system') {
1.48      www      10905: # ----------------------------------------------------------------- system.time
                   10906: 	if ($space eq 'time') {
                   10907: 	    return time;
                   10908:         }
1.696     albertel 10909:     } elsif ($realm eq 'server') {
                   10910: # ----------------------------------------------------------------- system.time
                   10911: 	if ($space eq 'name') {
                   10912: 	    return $ENV{'SERVER_NAME'};
                   10913:         }
1.28      www      10914:     }
1.48      www      10915:     return '';
1.61      www      10916: }
                   10917: 
1.927     albertel 10918: sub get_reply {
                   10919:     my ($reply_value) = @_;
1.940     raeburn  10920:     if (ref($reply_value) eq 'ARRAY') {
                   10921:         if (wantarray) {
                   10922: 	    return @$reply_value;
                   10923:         }
                   10924:         return $reply_value->[0];
                   10925:     } else {
                   10926:         return $reply_value;
1.927     albertel 10927:     }
                   10928: }
                   10929: 
1.691     raeburn  10930: sub check_group_parms {
1.1301    raeburn  10931:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   10932:         $recursed,$recurseupref) = @_;
                   10933:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   10934:                   [$what,'course']);
                   10935:     my $coursereply;
1.691     raeburn  10936:     foreach my $group (@{$groups}) {
1.1301    raeburn  10937:         my @groupitems = ();
1.691     raeburn  10938:         foreach my $level (@levels) {
1.927     albertel 10939:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10940:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10941:         }
1.1301    raeburn  10942:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10943:                                    $env{'course.'.$courseid.'.domain'},
                   10944:                                    'course',$mapp,$recursed,$recurseupref,
                   10945:                                    $courseid,'.['.$group.'].',$what,
                   10946:                                    @groupitems);
                   10947:         last if (defined($coursereply));
1.691     raeburn  10948:     }
                   10949:     return $coursereply;
                   10950: }
                   10951: 
1.1301    raeburn  10952: sub get_map_hierarchy {
1.1302    raeburn  10953:     my ($mapname,$courseid) = @_;
                   10954:     my @recurseup = ();
1.1301    raeburn  10955:     if ($mapname) {
1.1302    raeburn  10956:         if (($cachedmapkey eq $courseid) &&
                   10957:             (abs($cachedmaptime-time)<5)) {
                   10958:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   10959:                 return @{$cachedmaps{$mapname}};
                   10960:             }
                   10961:         }
1.1301    raeburn  10962:         my $navmap = Apache::lonnavmaps::navmap->new();
                   10963:         if (ref($navmap)) {
                   10964:             @recurseup = $navmap->recurseup_maps($mapname);
                   10965:             undef($navmap);
1.1302    raeburn  10966:             $cachedmaps{$mapname} = \@recurseup;
                   10967:             $cachedmaptime=time;
                   10968:             $cachedmapkey=$courseid;
1.1301    raeburn  10969:         }
                   10970:     }
                   10971:     return @recurseup;
                   10972: }
                   10973: 
1.1302    raeburn  10974: }
                   10975: 
1.691     raeburn  10976: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10977:     my ($courseid,@groups) = @_;
                   10978:     @groups = sort(@groups);
1.691     raeburn  10979:     return @groups;
                   10980: }
                   10981: 
1.395     albertel 10982: sub packages_tab_default {
                   10983:     my ($uri,$varname)=@_;
                   10984:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10985: 
                   10986:     my (@extension,@specifics,$do_default);
                   10987:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10988: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10989: 	if ($pack_type eq 'default') {
                   10990: 	    $do_default=1;
                   10991: 	} elsif ($pack_type eq 'extension') {
                   10992: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10993: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10994: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10995: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10996: 	}
                   10997:     }
                   10998:     # first look for a package that matches the requested part id
                   10999:     foreach my $package (@specifics) {
                   11000: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11001: 	next if ($pack_part ne $part);
                   11002: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11003: 	    return $packagetab{"$pack_type&$name&default"};
                   11004: 	}
                   11005:     }
                   11006:     # look for any possible matching non extension_ package
                   11007:     foreach my $package (@specifics) {
                   11008: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11009: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11010: 	    return $packagetab{"$pack_type&$name&default"};
                   11011: 	}
1.585     albertel 11012: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11013: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11014: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11015: 	}
                   11016:     }
1.738     albertel 11017:     # look for any posible extension_ match
                   11018:     foreach my $package (@extension) {
                   11019: 	my ($package,$pack_type)=@{$package};
                   11020: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11021: 	    return $packagetab{"$pack_type&$name&default"};
                   11022: 	}
                   11023: 	if (defined($packagetab{$package."&$name&default"})) {
                   11024: 	    return $packagetab{$package."&$name&default"};
                   11025: 	}
                   11026:     }
                   11027:     # look for a global default setting
                   11028:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11029: 	return $packagetab{"default&$name&default"};
                   11030:     }
1.395     albertel 11031:     return undef;
                   11032: }
                   11033: 
1.334     albertel 11034: sub add_prefix_and_part {
                   11035:     my ($prefix,$part)=@_;
                   11036:     my $keyroot;
                   11037:     if (defined($prefix) && $prefix !~ /^__/) {
                   11038: 	# prefix that has a part already
                   11039: 	$keyroot=$prefix;
                   11040:     } elsif (defined($prefix)) {
                   11041: 	# prefix that is missing a part
                   11042: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11043:     } else {
                   11044: 	# no prefix at all
                   11045: 	if (defined($part)) { $keyroot='_'.$part; }
                   11046:     }
                   11047:     return $keyroot;
                   11048: }
                   11049: 
1.71      www      11050: # ---------------------------------------------------------------- Get metadata
                   11051: 
1.599     albertel 11052: my %metaentry;
1.1070    www      11053: my %importedpartids;
1.71      www      11054: sub metadata {
1.176     www      11055:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11056:     $uri=&declutter($uri);
1.288     albertel 11057:     # if it is a non metadata possible uri return quickly
1.529     albertel 11058:     if (($uri eq '') || 
                   11059: 	(($uri =~ m|^/*adm/|) && 
1.1298    raeburn  11060: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108    raeburn  11061:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11062: 	return undef;
                   11063:     }
1.1261    raeburn  11064:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11065: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11066: 	return undef;
1.288     albertel 11067:     }
1.73      www      11068:     my $filename=$uri;
                   11069:     $uri=~s/\.meta$//;
1.172     www      11070: #
                   11071: # Is the metadata already cached?
1.177     www      11072: # Look at timestamp of caching
1.172     www      11073: # Everything is cached by the main uri, libraries are never directly cached
                   11074: #
1.428     albertel 11075:     if (!defined($liburi)) {
1.599     albertel 11076: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11077: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11078:     }
                   11079:     {
1.1069    www      11080: # Imported parts would go here
1.1070    www      11081:         my %importedids=();
                   11082:         my @origfileimportpartids=();
1.1069    www      11083:         my $importedparts=0;
1.172     www      11084: #
                   11085: # Is this a recursive call for a library?
                   11086: #
1.599     albertel 11087: #	if (! exists($metacache{$uri})) {
                   11088: #	    $metacache{$uri}={};
                   11089: #	}
1.924     albertel 11090: 	my $cachetime = 60*60;
1.171     www      11091:         if ($liburi) {
                   11092: 	    $liburi=&declutter($liburi);
                   11093:             $filename=$liburi;
1.401     bowersj2 11094:         } else {
1.599     albertel 11095: 	    &devalidate_cache_new('meta',$uri);
                   11096: 	    undef(%metaentry);
1.401     bowersj2 11097: 	}
1.140     www      11098:         my %metathesekeys=();
1.73      www      11099:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11100: 	my $metastring;
1.1140    www      11101: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11102: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11103: 	    $metastring = 
1.929     albertel 11104: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11105: 					  ('grade_target' => 'meta'));
                   11106: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11107: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11108:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11109: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11110: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11111: 	    $metastring=&getfile($file);
1.489     albertel 11112: 	}
1.208     albertel 11113:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11114:         my $token;
1.140     www      11115:         undef %metathesekeys;
1.71      www      11116:         while ($token=$parser->get_token) {
1.339     albertel 11117: 	    if ($token->[0] eq 'S') {
                   11118: 		if (defined($token->[2]->{'package'})) {
1.172     www      11119: #
                   11120: # This is a package - get package info
                   11121: #
1.339     albertel 11122: 		    my $package=$token->[2]->{'package'};
                   11123: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11124: 		    if (defined($token->[2]->{'id'})) { 
                   11125: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11126: 		    }
1.599     albertel 11127: 		    if ($metaentry{':packages'}) {
                   11128: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11129: 		    } else {
1.599     albertel 11130: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11131: 		    }
1.736     albertel 11132: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11133: 			my $part=$keyroot;
                   11134: 			$part=~s/^\_//;
1.736     albertel 11135: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11136: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11137: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11138: 			    # ignore package.tab specified default values
                   11139:                             # here &package_tab_default() will fetch those
                   11140: 			    if ($subp eq 'default') { next; }
1.736     albertel 11141: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11142: 			    my $unikey;
                   11143: 			    if ($pack =~ /_0$/) {
                   11144: 				$unikey='parameter_0_'.$name;
                   11145: 				$part=0;
                   11146: 			    } else {
                   11147: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11148: 			    }
1.339     albertel 11149: 			    if ($subp eq 'display') {
                   11150: 				$value.=' [Part: '.$part.']';
                   11151: 			    }
1.599     albertel 11152: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11153: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11154: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11155: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11156: 			    }
1.599     albertel 11157: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11158: 				$metaentry{':'.$unikey}=
                   11159: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11160: 			    }
1.339     albertel 11161: 			}
                   11162: 		    }
                   11163: 		} else {
1.172     www      11164: #
                   11165: # This is not a package - some other kind of start tag
1.339     albertel 11166: #
                   11167: 		    my $entry=$token->[1];
1.1068    www      11168: 		    my $unikey='';
1.175     www      11169: 
1.339     albertel 11170: 		    if ($entry eq 'import') {
1.175     www      11171: #
                   11172: # Importing a library here
1.339     albertel 11173: #
1.1067    www      11174:                         my $location=$parser->get_text('/import');
                   11175:                         my $dir=$filename;
                   11176:                         $dir=~s|[^/]*$||;
                   11177:                         $location=&filelocation($dir,$location);
1.1069    www      11178:                        
1.1068    www      11179:                         my $importmode=$token->[2]->{'importmode'};
                   11180:                         if ($importmode eq 'problem') {
1.1069    www      11181: # Import as problem/response
1.1068    www      11182:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11183:                         } elsif ($importmode eq 'part') {
                   11184: # Import as part(s)
1.1069    www      11185:                            $importedparts=1;
                   11186: # We need to get the original file and the imported file to get the part order correct
                   11187: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11188: # Load and inspect original file
1.1070    www      11189:                            if ($#origfileimportpartids<0) {
                   11190:                               undef(%importedpartids);
                   11191:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11192:                               my $origfile=&getfile($origfilelocation);
                   11193:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11194:                            }
                   11195: 
1.1069    www      11196: # Load and inspect imported file
                   11197:                            my $impfile=&getfile($location);
                   11198:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11199:                            if ($#impfilepartids>=0) {
                   11200: # This problem had parts
1.1070    www      11201:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11202:                            } else {
                   11203: # Importing by turning a single problem into a problem part
                   11204: # It gets the import-tags ID as part-ID
                   11205:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11206:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11207:                            }
1.1068    www      11208:                         } else {
                   11209: # Normal import
                   11210:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11211:                            if (defined($token->[2]->{'id'})) {
                   11212:                               $unikey.='_'.$token->[2]->{'id'};
                   11213:                            }
1.1067    www      11214:                         }
                   11215: 
1.339     albertel 11216: 			if ($depthcount<20) {
1.736     albertel 11217: 			    my $metadata = 
                   11218: 				&metadata($uri,'keys', $location,$unikey,
                   11219: 					  $depthcount+1);
                   11220: 			    foreach my $meta (split(',',$metadata)) {
                   11221: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11222: 				$metathesekeys{$meta}=1;
1.339     albertel 11223: 			    }
1.1068    www      11224: 			
                   11225:                         }
1.1067    www      11226: 		    } else {
                   11227: #
                   11228: # Not importing, some other kind of non-package, non-library start tag
                   11229: # 
                   11230:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11231:                         if (defined($token->[2]->{'id'})) {
                   11232:                             $unikey.='_'.$token->[2]->{'id'};
                   11233:                         }
1.339     albertel 11234: 			if (defined($token->[2]->{'name'})) { 
                   11235: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11236: 			}
                   11237: 			$metathesekeys{$unikey}=1;
1.736     albertel 11238: 			foreach my $param (@{$token->[3]}) {
                   11239: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11240: 				$token->[2]->{$param};
1.339     albertel 11241: 			}
                   11242: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11243: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11244: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11245: 		 # only ws inside the tag, and not in default, so use default
                   11246: 		 # as value
1.599     albertel 11247: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11248: 			} elsif ( $internaltext =~ /\S/ ) {
                   11249: 		  # something interesting inside the tag
                   11250: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11251: 			} else {
1.908     albertel 11252: 		  # no interesting values, don't set a default
1.339     albertel 11253: 			}
1.172     www      11254: # end of not-a-package not-a-library import
1.339     albertel 11255: 		    }
1.172     www      11256: # end of not-a-package start tag
1.339     albertel 11257: 		}
1.172     www      11258: # the next is the end of "start tag"
1.339     albertel 11259: 	    }
                   11260: 	}
1.483     albertel 11261: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11262: 	$extension = lc($extension);
                   11263: 	if ($extension eq 'htm') { $extension='html'; }
                   11264: 
1.737     albertel 11265: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11266: 	    #no specific packages #how's our extension
                   11267: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11268: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11269: 					 \%metathesekeys);
                   11270: 	}
1.883     albertel 11271: 
                   11272: 	if (!exists($metaentry{':packages'})
                   11273: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11274: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11275: 		#no specific packages well let's get default then
                   11276: 		if ($key!~/^default&/) { next; }
1.488     albertel 11277: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11278: 					     \%metathesekeys);
                   11279: 	    }
                   11280: 	}
1.338     www      11281: # are there custom rights to evaluate
1.599     albertel 11282: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11283: 
1.338     www      11284:     #
                   11285:     # Importing a rights file here
1.339     albertel 11286:     #
                   11287: 	    unless ($depthcount) {
1.599     albertel 11288: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11289: 		my $dir=$filename;
                   11290: 		$dir=~s|[^/]*$||;
                   11291: 		$location=&filelocation($dir,$location);
1.736     albertel 11292: 		my $rights_metadata =
                   11293: 		    &metadata($uri,'keys',$location,'_rights',
                   11294: 			      $depthcount+1);
                   11295: 		foreach my $rights (split(',',$rights_metadata)) {
                   11296: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11297: 		    $metathesekeys{$rights}=1;
1.339     albertel 11298: 		}
                   11299: 	    }
                   11300: 	}
1.737     albertel 11301: 	# uniqifiy package listing
                   11302: 	my %seen;
                   11303: 	my @uniq_packages =
                   11304: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11305: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11306: 
1.1070    www      11307:         if ($importedparts) {
                   11308: # We had imported parts and need to rebuild partorder
                   11309:            $metaentry{':partorder'}='';
                   11310:            $metathesekeys{'partorder'}=1;
                   11311:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11312:                if ($origfileimportpartids[$index] eq 'part') {
                   11313: # original part, part of the problem
                   11314:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11315:                } else {
                   11316: # we have imported parts at this position
                   11317:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11318:                }
                   11319:            }
                   11320:            $metaentry{':partorder'}=~s/^\,//;
                   11321:         }
                   11322: 
1.737     albertel 11323: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11324: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  11325: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11326: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11327: # this is the end of "was not already recently cached
1.71      www      11328:     }
1.599     albertel 11329:     return $metaentry{':'.$what};
1.261     albertel 11330: }
                   11331: 
1.488     albertel 11332: sub metadata_create_package_def {
1.483     albertel 11333:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11334:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11335:     if ($subp eq 'default') { next; }
                   11336:     
1.599     albertel 11337:     if (defined($metaentry{':packages'})) {
                   11338: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11339:     } else {
1.599     albertel 11340: 	$metaentry{':packages'}=$package;
1.483     albertel 11341:     }
                   11342:     my $value=$packagetab{$key};
                   11343:     my $unikey;
                   11344:     $unikey='parameter_0_'.$name;
1.599     albertel 11345:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11346:     $$metathesekeys{$unikey}=1;
1.599     albertel 11347:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11348: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11349:     }
1.599     albertel 11350:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11351: 	$metaentry{':'.$unikey}=
                   11352: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11353:     }
                   11354: }
                   11355: 
1.261     albertel 11356: sub metadata_generate_part0 {
                   11357:     my ($metadata,$metacache,$uri) = @_;
                   11358:     my %allnames;
1.737     albertel 11359:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11360: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11361: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11362: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11363: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11364: 	    $allnames{$name}=$part;
                   11365: 	  }
                   11366: 	}
                   11367:     }
                   11368:     foreach my $name (keys(%allnames)) {
                   11369:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11370:       my $key=":parameter_0_$name";
1.261     albertel 11371:       $$metacache{"$key.part"}='0';
                   11372:       $$metacache{"$key.name"}=$name;
1.428     albertel 11373:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11374: 					   $allnames{$name}.'_'.$name.
                   11375: 					   '.type'};
1.428     albertel 11376:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11377: 			     '.display'};
1.644     www      11378:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11379:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11380:       $$metacache{"$key.display"}=$olddis;
                   11381:     }
1.71      www      11382: }
                   11383: 
1.764     albertel 11384: # ------------------------------------------------------ Devalidate title cache
                   11385: 
                   11386: sub devalidate_title_cache {
                   11387:     my ($url)=@_;
                   11388:     if (!$env{'request.course.id'}) { return; }
                   11389:     my $symb=&symbread($url);
                   11390:     if (!$symb) { return; }
                   11391:     my $key=$env{'request.course.id'}."\0".$symb;
                   11392:     &devalidate_cache_new('title',$key);
                   11393: }
                   11394: 
1.1014    droeschl 11395: # ------------------------------------------------- Get the title of a course
                   11396: 
                   11397: sub current_course_title {
                   11398:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11399: }
1.301     www      11400: # ------------------------------------------------- Get the title of a resource
                   11401: 
                   11402: sub gettitle {
                   11403:     my $urlsymb=shift;
                   11404:     my $symb=&symbread($urlsymb);
1.534     albertel 11405:     if ($symb) {
1.620     albertel 11406: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11407: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11408: 	if (defined($cached)) { 
                   11409: 	    return $result;
                   11410: 	}
1.534     albertel 11411: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11412: 	my $title='';
1.907     albertel 11413: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11414: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11415: 	} else {
                   11416: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11417: 		    &GDBM_READER(),0640)) {
                   11418: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11419: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11420: 		untie(%bighash);
                   11421: 	    }
1.534     albertel 11422: 	}
                   11423: 	$title=~s/\&colon\;/\:/gs;
                   11424: 	if ($title) {
1.1159    www      11425: # Remember both $symb and $title for dynamic metadata
                   11426:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11427:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11428: # Cache this title and then return it
1.599     albertel 11429: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11430: 	}
                   11431: 	$urlsymb=$url;
                   11432:     }
                   11433:     my $title=&metadata($urlsymb,'title');
                   11434:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11435:     return $title;
1.301     www      11436: }
1.613     albertel 11437: 
1.614     albertel 11438: sub get_slot {
                   11439:     my ($which,$cnum,$cdom)=@_;
                   11440:     if (!$cnum || !$cdom) {
1.790     albertel 11441: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11442: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11443: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11444:     }
1.703     albertel 11445:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11446:     my %slotinfo;
                   11447:     if (exists($remembered{$key})) {
                   11448: 	$slotinfo{$which} = $remembered{$key};
                   11449:     } else {
                   11450: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11451: 	&Apache::lonhomework::showhash(%slotinfo);
                   11452: 	my ($tmp)=keys(%slotinfo);
                   11453: 	if ($tmp=~/^error:/) { return (); }
                   11454: 	$remembered{$key} = $slotinfo{$which};
                   11455:     }
1.616     albertel 11456:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11457: 	return %{$slotinfo{$which}};
                   11458:     }
                   11459:     return $slotinfo{$which};
1.614     albertel 11460: }
1.1150    raeburn  11461: 
                   11462: sub get_reservable_slots {
                   11463:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11464:     my $now = time;
                   11465:     my $reservable_info;
                   11466:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11467:     if (exists($remembered{$key})) {
                   11468:         $reservable_info = $remembered{$key};
                   11469:     } else {
                   11470:         my %resv;
                   11471:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11472:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11473:         $reservable_info = \%resv;
                   11474:         $remembered{$key} = $reservable_info;
                   11475:     }
                   11476:     return $reservable_info;
                   11477: }
                   11478: 
                   11479: sub get_course_slots {
                   11480:     my ($cnum,$cdom) = @_;
                   11481:     my $hashid=$cnum.':'.$cdom;
                   11482:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11483:     if (defined($cached)) {
                   11484:         if (ref($result) eq 'HASH') {
                   11485:             return %{$result};
                   11486:         }
                   11487:     } else {
                   11488:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11489:         my ($tmp) = keys(%slots);
                   11490:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  11491:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11492:             return %slots;
                   11493:         }
                   11494:     }
                   11495:     return;
                   11496: }
                   11497: 
                   11498: sub devalidate_slots_cache {
                   11499:     my ($cnum,$cdom)=@_;
                   11500:     my $hashid=$cnum.':'.$cdom;
                   11501:     &devalidate_cache_new('allslots',$hashid);
                   11502: }
                   11503: 
1.1181    raeburn  11504: sub get_coursechange {
                   11505:     my ($cdom,$cnum) = @_;
                   11506:     if ($cdom eq '' || $cnum eq '') {
                   11507:         return unless ($env{'request.course.id'});
                   11508:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11509:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11510:     }
                   11511:     my $hashid=$cdom.'_'.$cnum;
                   11512:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11513:     if ((defined($cached)) && ($change ne '')) {
                   11514:         return $change;
                   11515:     } else {
                   11516:         my %crshash;
                   11517:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11518:         if ($crshash{'internal.contentchange'} eq '') {
                   11519:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11520:             if ($change eq '') {
                   11521:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11522:                 $change = $crshash{'internal.created'};
                   11523:             }
                   11524:         } else {
                   11525:             $change = $crshash{'internal.contentchange'};
                   11526:         }
                   11527:         my $cachetime = 600;
                   11528:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11529:     }
                   11530:     return $change;
                   11531: }
                   11532: 
                   11533: sub devalidate_coursechange_cache {
                   11534:     my ($cnum,$cdom)=@_;
                   11535:     my $hashid=$cnum.':'.$cdom;
                   11536:     &devalidate_cache_new('crschange',$hashid);
                   11537: }
                   11538: 
1.31      www      11539: # ------------------------------------------------- Update symbolic store links
                   11540: 
                   11541: sub symblist {
                   11542:     my ($mapname,%newhash)=@_;
1.438     www      11543:     $mapname=&deversion(&declutter($mapname));
1.31      www      11544:     my %hash;
1.620     albertel 11545:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11546:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11547:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11548: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11549: 		next if ($url eq 'last_known'
                   11550: 			 && $env{'form.no_update_last_known'});
                   11551: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11552: 						    $newhash{$url}->[1],
                   11553: 						    $newhash{$url}->[0]);
1.191     harris41 11554:             }
1.31      www      11555:             if (untie(%hash)) {
                   11556: 		return 'ok';
                   11557:             }
                   11558:         }
                   11559:     }
                   11560:     return 'error';
1.212     www      11561: }
                   11562: 
                   11563: # --------------------------------------------------------------- Verify a symb
                   11564: 
                   11565: sub symbverify {
1.1190    raeburn  11566:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11567:     my $thisfn=$thisurl;
1.439     www      11568:     $thisfn=&declutter($thisfn);
1.215     www      11569: # direct jump to resource in page or to a sequence - will construct own symbs
                   11570:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11571: # check URL part
1.409     www      11572:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11573: 
1.431     www      11574:     unless ($url eq $thisfn) { return 0; }
1.213     www      11575: 
1.216     www      11576:     $symb=&symbclean($symb);
1.510     www      11577:     $thisurl=&deversion($thisurl);
1.439     www      11578:     $thisfn=&deversion($thisfn);
1.213     www      11579: 
                   11580:     my %bighash;
                   11581:     my $okay=0;
1.431     www      11582: 
1.620     albertel 11583:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11584:                             &GDBM_READER(),0640)) {
1.1204    raeburn  11585:         my $noclutter;
1.1032    raeburn  11586:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11587:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  11588:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11589:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11590:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11591:                 $noclutter = 1;
                   11592:             }
                   11593:         }
                   11594:         my $ids;
                   11595:         if ($noclutter) {
                   11596:             $ids=$bighash{'ids_'.$thisurl};
                   11597:         } else {
                   11598:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11599:         }
1.1102    raeburn  11600:         unless ($ids) {
                   11601:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   11602:             $ids=$bighash{$idkey};
1.216     www      11603:         }
                   11604:         if ($ids) {
                   11605: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  11606:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  11607:                 $symb =~ s/\?.+$//;
1.1202    raeburn  11608:             }
1.800     albertel 11609: 	    foreach my $id (split(/\,/,$ids)) {
                   11610: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11611:                if (
                   11612:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  11613:    eq $symb) {
                   11614:                    if (ref($encstate)) {
                   11615:                        $$encstate = $bighash{'encrypted_'.$id};
                   11616:                    }
1.620     albertel 11617: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  11618: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   11619:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  11620: 		       $okay=1;
1.1202    raeburn  11621:                        last;
1.582     albertel 11622: 		   }
                   11623: 	       }
1.216     www      11624: 	   }
                   11625:         }
1.213     www      11626: 	untie(%bighash);
                   11627:     }
                   11628:     return $okay;
1.31      www      11629: }
                   11630: 
1.210     www      11631: # --------------------------------------------------------------- Clean-up symb
                   11632: 
                   11633: sub symbclean {
                   11634:     my $symb=shift;
1.568     albertel 11635:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11636: # remove version from map
                   11637:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11638: 
1.210     www      11639: # remove version from URL
                   11640:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11641: 
1.507     www      11642: # remove wrapper
                   11643: 
1.510     www      11644:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11645:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11646:     return $symb;
1.409     www      11647: }
                   11648: 
                   11649: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11650: 
                   11651: sub encode_symb {
                   11652:     my ($map,$resid,$url)=@_;
                   11653:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11654: }
1.409     www      11655: 
                   11656: sub decode_symb {
1.568     albertel 11657:     my $symb=shift;
                   11658:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11659:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11660:     return (&fixversion($map),$resid,&fixversion($url));
                   11661: }
                   11662: 
                   11663: sub fixversion {
                   11664:     my $fn=shift;
1.609     banghart 11665:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11666:     my %bighash;
                   11667:     my $uri=&clutter($fn);
1.620     albertel 11668:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11669: # is this cached?
1.599     albertel 11670:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11671:     if (defined($cached)) { return $result; }
                   11672: # unfortunately not cached, or expired
1.620     albertel 11673:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11674: 	    &GDBM_READER(),0640)) {
                   11675:  	if ($bighash{'version_'.$uri}) {
                   11676:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11677:  	    unless (($version eq 'mostrecent') || 
                   11678: 		    ($version==&getversion($uri))) {
1.440     www      11679:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11680:  	    }
                   11681:  	}
                   11682:  	untie %bighash;
1.413     www      11683:     }
1.599     albertel 11684:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11685: }
                   11686: 
                   11687: sub deversion {
                   11688:     my $url=shift;
                   11689:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11690:     return $url;
1.210     www      11691: }
                   11692: 
1.31      www      11693: # ------------------------------------------------------ Return symb list entry
                   11694: 
                   11695: sub symbread {
1.1282    raeburn  11696:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  11697:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  11698:     if (defined($env{$cache_str})) {
                   11699:         if ($ignorecachednull) {
                   11700:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11701:         } else {
                   11702:             return $env{$cache_str};
                   11703:         }
                   11704:     }
1.242     www      11705: # no filename provided? try from environment
1.1265    raeburn  11706:     unless ($thisfn) {
1.620     albertel 11707:         if ($env{'request.symb'}) {
                   11708: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 11709: 	}
1.620     albertel 11710: 	$thisfn=$env{'request.filename'};
1.44      www      11711:     }
1.569     albertel 11712:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11713: # is that filename actually a symb? Verify, clean, and return
                   11714:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11715: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11716: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11717: 	}
1.242     www      11718:     }
1.44      www      11719:     $thisfn=declutter($thisfn);
1.31      www      11720:     my %hash;
1.37      www      11721:     my %bighash;
                   11722:     my $syval='';
1.620     albertel 11723:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11724:         my $targetfn = $thisfn;
1.609     banghart 11725:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11726:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11727:         }
1.687     albertel 11728: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11729: 	    $targetfn=$1;
                   11730: 	}
1.620     albertel 11731:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11732:                       &GDBM_READER(),0640)) {
1.481     raeburn  11733: 	    $syval=$hash{$targetfn};
1.37      www      11734:             untie(%hash);
                   11735:         }
                   11736: # ---------------------------------------------------------- There was an entry
                   11737:         if ($syval) {
1.601     albertel 11738: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11739: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11740: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11741: 		    #return $env{$cache_str}='';
1.601     albertel 11742: 		#}    
                   11743: 		#$syval.=$1;
                   11744: 	    #}
1.37      www      11745:         } else {
                   11746: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11747:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11748:                             &GDBM_READER(),0640)) {
1.37      www      11749: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11750:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11751:               unless ($ids) { 
                   11752:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11753:               }
                   11754:               unless ($ids) {
                   11755: # alias?
                   11756: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11757:               }
1.37      www      11758:               if ($ids) {
                   11759: # ------------------------------------------------------------------- Has ID(s)
                   11760:                  my @possibilities=split(/\,/,$ids);
1.39      www      11761:                  if ($#possibilities==0) {
                   11762: # ----------------------------------------------- There is only one possibility
1.37      www      11763: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11764: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11765: 						    $resid,$thisfn);
1.1282    raeburn  11766:                      if (ref($possibles) eq 'HASH') {
                   11767:                          $possibles->{$syval} = 1;    
                   11768:                      }
                   11769:                      if ($checkforblock) {
                   11770:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11771:                          if (@blockers) {
                   11772:                              $syval = '';
                   11773:                              return;
                   11774:                          }
                   11775:                      }
                   11776:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      11777: # ------------------------------------------ There is more than one possibility
                   11778:                      my $realpossible=0;
1.800     albertel 11779:                      foreach my $id (@possibilities) {
                   11780: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  11781:                          my $canaccess;
                   11782:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11783:                              $canaccess = 1;
                   11784:                          } else { 
                   11785:                              $canaccess = &allowed('bre',$file);
                   11786:                          }
                   11787:                          if ($canaccess) {
                   11788:          		     my ($mapid,$resid)=split(/\./,$id);
                   11789:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11790:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11791: 						             $resid,$thisfn);
                   11792:                                  if (ref($possibles) eq 'HASH') {
                   11793:                                      $possibles->{$syval} = 1;
                   11794:                                  }
                   11795:                                  if ($checkforblock) {
                   11796:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11797:                                      unless (@blockers > 0) {
                   11798:                                          $syval = $poss_syval;
                   11799:                                          $realpossible++;
                   11800:                                      }
                   11801:                                  } else {
                   11802:                                      $syval = $poss_syval;
                   11803:                                      $realpossible++;
                   11804:                                  }
                   11805:                              }
1.39      www      11806: 			 }
1.191     harris41 11807:                      }
1.39      www      11808: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11809:                  } else {
                   11810:                      $syval='';
1.37      www      11811:                  }
                   11812: 	      }
1.1282    raeburn  11813:               untie(%bighash);
1.481     raeburn  11814:            }
1.31      www      11815:         }
1.62      www      11816:         if ($syval) {
1.620     albertel 11817: 	    return $env{$cache_str}=$syval;
1.62      www      11818:         }
1.31      www      11819:     }
1.949     raeburn  11820:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11821:     return $env{$cache_str}='';
1.31      www      11822: }
                   11823: 
                   11824: # ---------------------------------------------------------- Return random seed
                   11825: 
1.32      www      11826: sub numval {
                   11827:     my $txt=shift;
                   11828:     $txt=~tr/A-J/0-9/;
                   11829:     $txt=~tr/a-j/0-9/;
                   11830:     $txt=~tr/K-T/0-9/;
                   11831:     $txt=~tr/k-t/0-9/;
                   11832:     $txt=~tr/U-Z/0-5/;
                   11833:     $txt=~tr/u-z/0-5/;
                   11834:     $txt=~s/\D//g;
1.564     albertel 11835:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11836:     return int($txt);
1.368     albertel 11837: }
                   11838: 
1.484     albertel 11839: sub numval2 {
                   11840:     my $txt=shift;
                   11841:     $txt=~tr/A-J/0-9/;
                   11842:     $txt=~tr/a-j/0-9/;
                   11843:     $txt=~tr/K-T/0-9/;
                   11844:     $txt=~tr/k-t/0-9/;
                   11845:     $txt=~tr/U-Z/0-5/;
                   11846:     $txt=~tr/u-z/0-5/;
                   11847:     $txt=~s/\D//g;
                   11848:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11849:     my $total;
                   11850:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11851:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11852:     return int($total);
                   11853: }
                   11854: 
1.575     albertel 11855: sub numval3 {
                   11856:     use integer;
                   11857:     my $txt=shift;
                   11858:     $txt=~tr/A-J/0-9/;
                   11859:     $txt=~tr/a-j/0-9/;
                   11860:     $txt=~tr/K-T/0-9/;
                   11861:     $txt=~tr/k-t/0-9/;
                   11862:     $txt=~tr/U-Z/0-5/;
                   11863:     $txt=~tr/u-z/0-5/;
                   11864:     $txt=~s/\D//g;
                   11865:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11866:     my $total;
                   11867:     foreach my $val (@txts) { $total+=$val; }
                   11868:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11869:     return $total;
                   11870: }
                   11871: 
1.675     albertel 11872: sub digest {
                   11873:     my ($data)=@_;
                   11874:     my $digest=&Digest::MD5::md5($data);
                   11875:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11876:     my ($e,$f);
                   11877:     {
                   11878:         use integer;
                   11879:         $e=($a+$b);
                   11880:         $f=($c+$d);
                   11881:         if ($_64bit) {
                   11882:             $e=(($e<<32)>>32);
                   11883:             $f=(($f<<32)>>32);
                   11884:         }
                   11885:     }
                   11886:     if (wantarray) {
                   11887: 	return ($e,$f);
                   11888:     } else {
                   11889: 	my $g;
                   11890: 	{
                   11891: 	    use integer;
                   11892: 	    $g=($e+$f);
                   11893: 	    if ($_64bit) {
                   11894: 		$g=(($g<<32)>>32);
                   11895: 	    }
                   11896: 	}
                   11897: 	return $g;
                   11898:     }
                   11899: }
                   11900: 
1.368     albertel 11901: sub latest_rnd_algorithm_id {
1.675     albertel 11902:     return '64bit5';
1.366     albertel 11903: }
1.32      www      11904: 
1.503     albertel 11905: sub get_rand_alg {
                   11906:     my ($courseid)=@_;
1.790     albertel 11907:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11908:     if ($courseid) {
1.620     albertel 11909: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11910:     }
                   11911:     return &latest_rnd_algorithm_id();
                   11912: }
                   11913: 
1.562     albertel 11914: sub validCODE {
                   11915:     my ($CODE)=@_;
                   11916:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11917:     return 0;
                   11918: }
                   11919: 
1.491     albertel 11920: sub getCODE {
1.620     albertel 11921:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11922:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11923: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11924: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11925: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11926:     }
                   11927:     return undef;
                   11928: }
1.1133    foxr     11929: #
                   11930: #  Determines the random seed for a specific context:
                   11931: #
                   11932: # parameters:
                   11933: #   symb      - in course context the symb for the seed.
                   11934: #   course_id - The course id of the form domain_coursenum.
                   11935: #   domain    - Domain for the user.
                   11936: #   course    - Course for the user.
                   11937: #   cenv      - environment of the course.
                   11938: #
                   11939: # NOTE:
                   11940: #   All parameters are picked out of the environment if missing
                   11941: #   or not defined.
                   11942: #   If a symb cannot be determined the current time is used instead.
                   11943: #
                   11944: #  For a given well defined symb, courside, domain, username,
                   11945: #  and course environment, the seed is reproducible.
                   11946: #
1.31      www      11947: sub rndseed {
1.1133    foxr     11948:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11949:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11950:     if (!defined($symb)) {
1.366     albertel 11951: 	unless ($symb=$wsymb) { return time; }
                   11952:     }
1.1146    foxr     11953:     if (!defined $courseid) { 
                   11954: 	$courseid=$wcourseid; 
                   11955:     }
                   11956:     if (!defined $domain) { $domain=$wdomain; }
                   11957:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11958: 
                   11959:     my $which;
                   11960:     if (defined($cenv->{'rndseed'})) {
                   11961: 	$which = $cenv->{'rndseed'};
                   11962:     } else {
                   11963: 	$which =&get_rand_alg($courseid);
                   11964:     }
1.491     albertel 11965:     if (defined(&getCODE())) {
1.1133    foxr     11966: 
1.675     albertel 11967: 	if ($which eq '64bit5') {
                   11968: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11969: 	} elsif ($which eq '64bit4') {
1.575     albertel 11970: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11971: 	} else {
                   11972: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11973: 	}
1.675     albertel 11974:     } elsif ($which eq '64bit5') {
                   11975: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11976:     } elsif ($which eq '64bit4') {
                   11977: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11978:     } elsif ($which eq '64bit3') {
                   11979: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11980:     } elsif ($which eq '64bit2') {
                   11981: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11982:     } elsif ($which eq '64bit') {
                   11983: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11984:     }
                   11985:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11986: }
                   11987: 
                   11988: sub rndseed_32bit {
                   11989:     my ($symb,$courseid,$domain,$username)=@_;
                   11990:     {
                   11991: 	use integer;
                   11992: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11993: 	my $symbseed=numval($symb) << 22;
                   11994: 	my $namechck=unpack("%32C*",$username) << 17;
                   11995: 	my $nameseed=numval($username) << 12;
                   11996: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11997: 	my $courseseed=unpack("%32C*",$courseid);
                   11998: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11999: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12000: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12001: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12002: 	return $num;
                   12003:     }
                   12004: }
                   12005: 
                   12006: sub rndseed_64bit {
                   12007:     my ($symb,$courseid,$domain,$username)=@_;
                   12008:     {
                   12009: 	use integer;
                   12010: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12011: 	my $symbseed=numval($symb) << 10;
                   12012: 	my $namechck=unpack("%32S*",$username);
                   12013: 	
                   12014: 	my $nameseed=numval($username) << 21;
                   12015: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12016: 	my $courseseed=unpack("%32S*",$courseid);
                   12017: 	
                   12018: 	my $num1=$symbchck+$symbseed+$namechck;
                   12019: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12020: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12021: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12022: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12023: 	return "$num1,$num2";
1.155     albertel 12024:     }
1.366     albertel 12025: }
                   12026: 
1.443     albertel 12027: sub rndseed_64bit2 {
                   12028:     my ($symb,$courseid,$domain,$username)=@_;
                   12029:     {
                   12030: 	use integer;
                   12031: 	# strings need to be an even # of cahracters long, it it is odd the
                   12032:         # last characters gets thrown away
                   12033: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12034: 	my $symbseed=numval($symb) << 10;
                   12035: 	my $namechck=unpack("%32S*",$username.' ');
                   12036: 	
                   12037: 	my $nameseed=numval($username) << 21;
1.501     albertel 12038: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12039: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12040: 	
                   12041: 	my $num1=$symbchck+$symbseed+$namechck;
                   12042: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12043: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12044: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12045: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12046: 	return "$num1,$num2";
                   12047:     }
                   12048: }
                   12049: 
                   12050: sub rndseed_64bit3 {
                   12051:     my ($symb,$courseid,$domain,$username)=@_;
                   12052:     {
                   12053: 	use integer;
                   12054: 	# strings need to be an even # of cahracters long, it it is odd the
                   12055:         # last characters gets thrown away
                   12056: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12057: 	my $symbseed=numval2($symb) << 10;
                   12058: 	my $namechck=unpack("%32S*",$username.' ');
                   12059: 	
                   12060: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12061: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12062: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12063: 	
                   12064: 	my $num1=$symbchck+$symbseed+$namechck;
                   12065: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12066: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12067: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12068: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12069: 	
1.503     albertel 12070: 	return "$num1:$num2";
1.443     albertel 12071:     }
                   12072: }
                   12073: 
1.575     albertel 12074: sub rndseed_64bit4 {
                   12075:     my ($symb,$courseid,$domain,$username)=@_;
                   12076:     {
                   12077: 	use integer;
                   12078: 	# strings need to be an even # of cahracters long, it it is odd the
                   12079:         # last characters gets thrown away
                   12080: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12081: 	my $symbseed=numval3($symb) << 10;
                   12082: 	my $namechck=unpack("%32S*",$username.' ');
                   12083: 	
                   12084: 	my $nameseed=numval3($username) << 21;
                   12085: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12086: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12087: 	
                   12088: 	my $num1=$symbchck+$symbseed+$namechck;
                   12089: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12090: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12091: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12092: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12093: 	
1.575     albertel 12094: 	return "$num1:$num2";
                   12095:     }
                   12096: }
                   12097: 
1.675     albertel 12098: sub rndseed_64bit5 {
                   12099:     my ($symb,$courseid,$domain,$username)=@_;
                   12100:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12101:     return "$num1:$num2";
                   12102: }
                   12103: 
1.366     albertel 12104: sub rndseed_CODE_64bit {
                   12105:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12106:     {
1.366     albertel 12107: 	use integer;
1.443     albertel 12108: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12109: 	my $symbseed=numval2($symb);
1.491     albertel 12110: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12111: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12112: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12113: 	my $num1=$symbseed+$CODEchck;
                   12114: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12115: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12116: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12117: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12118: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12119: 	return "$num1:$num2";
1.366     albertel 12120:     }
                   12121: }
                   12122: 
1.575     albertel 12123: sub rndseed_CODE_64bit4 {
                   12124:     my ($symb,$courseid,$domain,$username)=@_;
                   12125:     {
                   12126: 	use integer;
                   12127: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12128: 	my $symbseed=numval3($symb);
                   12129: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12130: 	my $CODEseed=numval3(&getCODE());
                   12131: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12132: 	my $num1=$symbseed+$CODEchck;
                   12133: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12134: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12135: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12136: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12137: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12138: 	return "$num1:$num2";
                   12139:     }
                   12140: }
                   12141: 
1.675     albertel 12142: sub rndseed_CODE_64bit5 {
                   12143:     my ($symb,$courseid,$domain,$username)=@_;
                   12144:     my $code = &getCODE();
                   12145:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12146:     return "$num1:$num2";
                   12147: }
                   12148: 
1.366     albertel 12149: sub setup_random_from_rndseed {
                   12150:     my ($rndseed)=@_;
1.503     albertel 12151:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  12152:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12153:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12154:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12155:         } else {
                   12156:             &Math::Random::random_set_seed($num1,$num2);
                   12157:         }
1.366     albertel 12158:     } else {
                   12159: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12160:     }
1.36      albertel 12161: }
                   12162: 
1.474     albertel 12163: sub latest_receipt_algorithm_id {
1.835     albertel 12164:     return 'receipt3';
1.474     albertel 12165: }
                   12166: 
1.480     www      12167: sub recunique {
                   12168:     my $fucourseid=shift;
                   12169:     my $unique;
1.835     albertel 12170:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12171: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12172: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12173:     } else {
                   12174: 	$unique=$perlvar{'lonReceipt'};
                   12175:     }
                   12176:     return unpack("%32C*",$unique);
                   12177: }
                   12178: 
                   12179: sub recprefix {
                   12180:     my $fucourseid=shift;
                   12181:     my $prefix;
1.835     albertel 12182:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12183: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12184: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12185:     } else {
                   12186: 	$prefix=$perlvar{'lonHostID'};
                   12187:     }
                   12188:     return unpack("%32C*",$prefix);
                   12189: }
                   12190: 
1.76      www      12191: sub ireceipt {
1.474     albertel 12192:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12193: 
                   12194:     my $return =&recprefix($fucourseid).'-';
                   12195: 
                   12196:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12197: 	$env{'request.state'} eq 'construct') {
                   12198: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12199: 	return $return;
                   12200:     }
                   12201: 
1.76      www      12202:     my $cuname=unpack("%32C*",$funame);
                   12203:     my $cudom=unpack("%32C*",$fudom);
                   12204:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12205:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12206:     my $cunique=&recunique($fucourseid);
1.474     albertel 12207:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12208:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12209: 
1.790     albertel 12210: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12211: 			       
                   12212: 	$return.= ($cunique%$cuname+
                   12213: 		   $cunique%$cudom+
                   12214: 		   $cusymb%$cuname+
                   12215: 		   $cusymb%$cudom+
                   12216: 		   $cucourseid%$cuname+
                   12217: 		   $cucourseid%$cudom+
                   12218: 		   $cpart%$cuname+
                   12219: 		   $cpart%$cudom);
                   12220:     } else {
                   12221: 	$return.= ($cunique%$cuname+
                   12222: 		   $cunique%$cudom+
                   12223: 		   $cusymb%$cuname+
                   12224: 		   $cusymb%$cudom+
                   12225: 		   $cucourseid%$cuname+
                   12226: 		   $cucourseid%$cudom);
                   12227:     }
                   12228:     return $return;
1.76      www      12229: }
                   12230: 
                   12231: sub receipt {
1.474     albertel 12232:     my ($part)=@_;
1.790     albertel 12233:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12234:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12235: }
1.260     ng       12236: 
1.790     albertel 12237: sub whichuser {
                   12238:     my ($passedsymb)=@_;
                   12239:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12240:     if (defined($env{'form.grade_symb'})) {
                   12241: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12242: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12243: 	if (!$allowed &&
                   12244: 	    exists($env{'request.course.sec'}) &&
                   12245: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12246: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12247: 			      '/'.$env{'request.course.sec'});
                   12248: 	}
                   12249: 	if ($allowed) {
                   12250: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12251: 	    $courseid=$tmp_courseid;
                   12252: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12253: 	    ($name)=&get_env_multiple('form.grade_username');
                   12254: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12255: 	}
                   12256:     }
                   12257:     if (!$passedsymb) {
                   12258: 	$symb=&symbread();
                   12259:     } else {
                   12260: 	$symb=$passedsymb;
                   12261:     }
                   12262:     $courseid=$env{'request.course.id'};
                   12263:     $domain=$env{'user.domain'};
                   12264:     $name=$env{'user.name'};
                   12265:     if ($name eq 'public' && $domain eq 'public') {
                   12266: 	if (!defined($env{'form.username'})) {
                   12267: 	    $env{'form.username'}.=time.rand(10000000);
                   12268: 	}
                   12269: 	$name.=$env{'form.username'};
                   12270:     }
                   12271:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12272: 
                   12273: }
                   12274: 
1.36      albertel 12275: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12276: # returns either the contents of the file or 
                   12277: # -1 if the file doesn't exist
1.481     raeburn  12278: #
                   12279: # if the target is a file that was uploaded via DOCS, 
                   12280: # a check will be made to see if a current copy exists on the local server,
                   12281: # if it does this will be served, otherwise a copy will be retrieved from
                   12282: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12283: # the local server.   
1.472     albertel 12284: 
1.36      albertel 12285: sub getfile {
1.538     albertel 12286:     my ($file) = @_;
1.609     banghart 12287:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12288:     &repcopy($file);
                   12289:     return &readfile($file);
                   12290: }
                   12291: 
                   12292: sub repcopy_userfile {
                   12293:     my ($file)=@_;
1.1142    raeburn  12294:     my $londocroot = $perlvar{'lonDocRoot'};
                   12295:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12296:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12297:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12298: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12299:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12300:     if (-e "$file") {
1.828     www      12301: # we already have a local copy, check it out
1.538     albertel 12302: 	my @fileinfo = stat($file);
1.828     www      12303: 	my $rtncode;
                   12304: 	my $info;
1.538     albertel 12305: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12306: 	if ($lwpresp ne 'ok') {
1.828     www      12307: # there is no such file anymore, even though we had a local copy
1.482     albertel 12308: 	    if ($rtncode eq '404') {
1.538     albertel 12309: 		unlink($file);
1.482     albertel 12310: 	    }
                   12311: 	    return -1;
                   12312: 	}
                   12313: 	if ($info < $fileinfo[9]) {
1.828     www      12314: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12315: 	    return 'ok';
1.828     www      12316: 	} else {
                   12317: # the file is outdated, get rid of it
                   12318: 	    unlink($file);
1.482     albertel 12319: 	}
1.828     www      12320:     }
                   12321: # one way or the other, at this point, we don't have the file
                   12322: # construct the correct path for the file
                   12323:     my @parts = ($cdom,$cnum); 
                   12324:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12325: 	push @parts, split(/\//,$1);
                   12326:     }
                   12327:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12328:     foreach my $part (@parts) {
                   12329: 	$path .= '/'.$part;
                   12330: 	if (!-e $path) {
                   12331: 	    mkdir($path,0770);
1.482     albertel 12332: 	}
                   12333:     }
1.828     www      12334: # now the path exists for sure
                   12335: # get a user agent
                   12336:     my $ua=new LWP::UserAgent;
                   12337:     my $transferfile=$file.'.in.transfer';
                   12338: # FIXME: this should flock
                   12339:     if (-e $transferfile) { return 'ok'; }
                   12340:     my $request;
                   12341:     $uri=~s/^\///;
1.980     raeburn  12342:     my $homeserver = &homeserver($cnum,$cdom);
                   12343:     my $protocol = $protocol{$homeserver};
                   12344:     $protocol = 'http' if ($protocol ne 'https');
                   12345:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12346:     my $response=$ua->request($request,$transferfile);
                   12347: # did it work?
                   12348:     if ($response->is_error()) {
                   12349: 	unlink($transferfile);
                   12350: 	&logthis("Userfile repcopy failed for $uri");
                   12351: 	return -1;
                   12352:     }
                   12353: # worked, rename the transfer file
                   12354:     rename($transferfile,$file);
1.607     raeburn  12355:     return 'ok';
1.481     raeburn  12356: }
                   12357: 
1.517     albertel 12358: sub tokenwrapper {
                   12359:     my $uri=shift;
1.980     raeburn  12360:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12361:     $uri=~s|^/||;
1.620     albertel 12362:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12363:     my $token=$1;
1.552     albertel 12364:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12365:     if ($udom && $uname && $file) {
                   12366: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12367:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12368:         my $homeserver = &homeserver($uname,$udom);
                   12369:         my $protocol = $protocol{$homeserver};
                   12370:         $protocol = 'http' if ($protocol ne 'https');
                   12371:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12372:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12373:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12374:     } else {
                   12375:         return '/adm/notfound.html';
                   12376:     }
                   12377: }
                   12378: 
1.828     www      12379: # call with reqtype HEAD: get last modification time
                   12380: # call with reqtype GET: get the file contents
                   12381: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12382: #
1.481     raeburn  12383: sub getuploaded {
                   12384:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12385:     $uri=~s/^\///;
1.980     raeburn  12386:     my $homeserver = &homeserver($cnum,$cdom);
                   12387:     my $protocol = $protocol{$homeserver};
                   12388:     $protocol = 'http' if ($protocol ne 'https');
                   12389:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12390:     my $ua=new LWP::UserAgent;
                   12391:     my $request=new HTTP::Request($reqtype,$uri);
                   12392:     my $response=$ua->request($request);
                   12393:     $$rtncode = $response->code;
1.482     albertel 12394:     if (! $response->is_success()) {
                   12395: 	return 'failed';
                   12396:     }      
                   12397:     if ($reqtype eq 'HEAD') {
1.486     www      12398: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12399:     } elsif ($reqtype eq 'GET') {
                   12400: 	$$info = $response->content;
1.472     albertel 12401:     }
1.482     albertel 12402:     return 'ok';
1.36      albertel 12403: }
                   12404: 
1.481     raeburn  12405: sub readfile {
                   12406:     my $file = shift;
                   12407:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12408:     my $fh;
                   12409:     open($fh,"<$file");
                   12410:     my $a='';
1.800     albertel 12411:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12412:     return $a;
                   12413: }
                   12414: 
1.36      albertel 12415: sub filelocation {
1.590     banghart 12416:     my ($dir,$file) = @_;
                   12417:     my $location;
                   12418:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12419: 
                   12420:     if ($file =~ m-^/adm/-) {
                   12421: 	$file=~s-^/adm/wrapper/-/-;
                   12422: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12423:     }
1.882     albertel 12424: 
1.1139    www      12425:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12426:         $location = $file;
1.609     banghart 12427:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12428:         my ($udom,$uname,$filename)=
1.811     albertel 12429:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12430:         my $home=&homeserver($uname,$udom);
                   12431:         my $is_me=0;
                   12432:         my @ids=&current_machine_ids();
                   12433:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12434:         if ($is_me) {
1.1117    foxr     12435:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12436:         } else {
                   12437:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12438:   	      $udom.'/'.$uname.'/'.$filename;
                   12439:         }
1.882     albertel 12440:     } elsif ($file =~ m-^/adm/-) {
                   12441: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12442:     } else {
                   12443:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12444:         $file=~s:^/(res|priv)/:/:;
                   12445:         my $space=$1;
1.590     banghart 12446:         if ( !( $file =~ m:^/:) ) {
                   12447:             $location = $dir. '/'.$file;
                   12448:         } else {
1.1142    raeburn  12449:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12450:         }
1.59      albertel 12451:     }
1.590     banghart 12452:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12453:     while ($location=~m{/\.\./}) {
                   12454: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12455: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12456: 	} else {
                   12457: 	    $location=~ s{/\.\./}{/}g;
                   12458: 	}
                   12459:     } #remove dir/..
1.590     banghart 12460:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12461:     return $location;
1.46      www      12462: }
1.36      albertel 12463: 
1.46      www      12464: sub hreflocation {
                   12465:     my ($dir,$file)=@_;
1.980     raeburn  12466:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12467: 	$file=filelocation($dir,$file);
1.700     albertel 12468:     } elsif ($file=~m-^/adm/-) {
                   12469: 	$file=~s-^/adm/wrapper/-/-;
                   12470: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12471:     }
                   12472:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12473: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12474:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12475: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12476: 	        {/uploaded/$1/$2/}x;
1.46      www      12477:     }
1.913     albertel 12478:     if ($file=~ m{^/userfiles/}) {
                   12479: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12480:     }
1.462     albertel 12481:     return $file;
1.465     albertel 12482: }
                   12483: 
1.1139    www      12484: 
                   12485: 
                   12486: 
                   12487: 
1.465     albertel 12488: sub current_machine_domains {
1.853     albertel 12489:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12490: }
                   12491: 
                   12492: sub machine_domains {
                   12493:     my ($hostname) = @_;
1.465     albertel 12494:     my @domains;
1.838     albertel 12495:     my %hostname = &all_hostnames();
1.465     albertel 12496:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12497: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12498: 	if ($hostname eq $name) {
1.844     albertel 12499: 	    push(@domains,&host_domain($id));
1.465     albertel 12500: 	}
                   12501:     }
                   12502:     return @domains;
                   12503: }
                   12504: 
                   12505: sub current_machine_ids {
1.853     albertel 12506:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12507: }
                   12508: 
                   12509: sub machine_ids {
                   12510:     my ($hostname) = @_;
                   12511:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12512:     my @ids;
1.888     albertel 12513:     my %name_to_host = &all_names();
1.889     albertel 12514:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12515: 	return @{ $name_to_host{$hostname} };
                   12516:     }
                   12517:     return;
1.31      www      12518: }
                   12519: 
1.824     raeburn  12520: sub additional_machine_domains {
                   12521:     my @domains;
                   12522:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12523:     while( my $line = <$fh>) {
                   12524:         $line =~ s/\s//g;
                   12525:         push(@domains,$line);
                   12526:     }
                   12527:     return @domains;
                   12528: }
                   12529: 
                   12530: sub default_login_domain {
                   12531:     my $domain = $perlvar{'lonDefDomain'};
                   12532:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12533:     foreach my $posdom (&current_machine_domains(),
                   12534:                         &additional_machine_domains()) {
                   12535:         if (lc($posdom) eq lc($testdomain)) {
                   12536:             $domain=$posdom;
                   12537:             last;
                   12538:         }
                   12539:     }
                   12540:     return $domain;
                   12541: }
                   12542: 
1.31      www      12543: # ------------------------------------------------------------- Declutters URLs
                   12544: 
                   12545: sub declutter {
                   12546:     my $thisfn=shift;
1.569     albertel 12547:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  12548:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12549:         $thisfn=~s{^/home/httpd/html}{};
                   12550:     }
1.31      www      12551:     $thisfn=~s/^\///;
1.697     albertel 12552:     $thisfn=~s|^adm/wrapper/||;
                   12553:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12554:     $thisfn=~s/^res\///;
1.1172    bisitz   12555:     $thisfn=~s/^priv\///;
1.1032    raeburn  12556:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12557:         $thisfn=~s/\?.+$//;
                   12558:     }
1.268     www      12559:     return $thisfn;
                   12560: }
                   12561: 
                   12562: # ------------------------------------------------------------- Clutter up URLs
                   12563: 
                   12564: sub clutter {
                   12565:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12566:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12567: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12568:        $thisfn='/res'.$thisfn; 
                   12569:     }
1.1031    raeburn  12570:     if ($thisfn !~m|^/adm|) {
                   12571: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12572: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12573: 	} else {
                   12574: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12575: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12576: 	    if ($embstyle eq 'ssi'
                   12577: 		|| ($embstyle eq 'hdn')
                   12578: 		|| ($embstyle eq 'rat')
                   12579: 		|| ($embstyle eq 'prv')
                   12580: 		|| ($embstyle eq 'ign')) {
                   12581: 		#do nothing with these
                   12582: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12583: 		|| ($embstyle eq 'emb')
                   12584: 		|| ($embstyle eq 'wrp')) {
                   12585: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12586: 	    } elsif ($embstyle eq 'unk'
                   12587: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12588: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12589: 	    } else {
1.718     www      12590: #		&logthis("Got a blank emb style");
1.695     albertel 12591: 	    }
1.694     albertel 12592: 	}
1.1298    raeburn  12593:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
                   12594:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 12595:     }
1.31      www      12596:     return $thisfn;
1.12      www      12597: }
                   12598: 
1.787     albertel 12599: sub clutter_with_no_wrapper {
                   12600:     my $uri = &clutter(shift);
                   12601:     if ($uri =~ m-^/adm/-) {
                   12602: 	$uri =~ s-^/adm/wrapper/-/-;
                   12603: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12604:     }
                   12605:     return $uri;
                   12606: }
                   12607: 
1.557     albertel 12608: sub freeze_escape {
                   12609:     my ($value)=@_;
                   12610:     if (ref($value)) {
                   12611: 	$value=&nfreeze($value);
                   12612: 	return '__FROZEN__'.&escape($value);
                   12613:     }
                   12614:     return &escape($value);
                   12615: }
                   12616: 
1.11      www      12617: 
1.557     albertel 12618: sub thaw_unescape {
                   12619:     my ($value)=@_;
                   12620:     if ($value =~ /^__FROZEN__/) {
                   12621: 	substr($value,0,10,undef);
                   12622: 	$value=&unescape($value);
                   12623: 	return &thaw($value);
                   12624:     }
                   12625:     return &unescape($value);
                   12626: }
                   12627: 
1.436     albertel 12628: sub correct_line_ends {
                   12629:     my ($result)=@_;
                   12630:     $$result =~s/\r\n/\n/mg;
                   12631:     $$result =~s/\r/\n/mg;
1.415     albertel 12632: }
1.1       albertel 12633: # ================================================================ Main Program
                   12634: 
1.184     www      12635: sub goodbye {
1.204     albertel 12636:    &logthis("Starting Shut down");
1.443     albertel 12637: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12638:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12639: #converted
1.599     albertel 12640: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12641:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12642: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12643: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12644: #1.1 only
1.870     albertel 12645: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12646: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12647: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12648: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12649:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12650:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12651:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12652:    &flushcourselogs();
                   12653:    &logthis("Shutting down");
                   12654: }
                   12655: 
1.852     albertel 12656: sub get_dns {
1.1210    raeburn  12657:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12658:     if (!$ignore_cache) {
                   12659: 	my ($content,$cached)=
                   12660: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12661: 	if ($cached) {
1.1210    raeburn  12662: 	    &$func($content,$hashref);
1.869     albertel 12663: 	    return;
                   12664: 	}
                   12665:     }
                   12666: 
                   12667:     my %alldns;
1.852     albertel 12668:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12669:     foreach my $dns (<$config>) {
                   12670: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12671:         my $line = $1;
                   12672:         my ($host,$protocol) = split(/:/,$line);
                   12673:         if ($protocol ne 'https') {
                   12674:             $protocol = 'http';
                   12675:         }
                   12676: 	$alldns{$host} = $protocol;
1.869     albertel 12677:     }
                   12678:     while (%alldns) {
1.1263    raeburn  12679: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12680: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12681:         $ua->timeout(30);
1.979     raeburn  12682: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12683: 	my $response=$ua->request($request);
1.979     raeburn  12684:         delete($alldns{$dns});
1.852     albertel 12685: 	next if ($response->is_error());
                   12686: 	my @content = split("\n",$response->content);
1.1210    raeburn  12687: 	unless ($nocache) {
1.1219    raeburn  12688: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  12689: 	}
                   12690: 	&$func(\@content,$hashref);
1.869     albertel 12691: 	return;
1.852     albertel 12692:     }
                   12693:     close($config);
1.871     albertel 12694:     my $which = (split('/',$url))[3];
                   12695:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12696:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12697:     my @content = <$config>;
1.1210    raeburn  12698:     &$func(\@content,$hashref);
                   12699:     return;
                   12700: }
                   12701: 
                   12702: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  12703: sub parse_dns_checksums_tab {
1.1210    raeburn  12704:     my ($lines,$hashref) = @_;
1.1264    raeburn  12705:     my $lonhost = $perlvar{'lonHostID'};
                   12706:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  12707:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  12708:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12709:     my $webconfdir = '/etc/httpd/conf';
                   12710:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12711:         $webconfdir = '/etc/apache2';
                   12712:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12713:         if ($1 >= 10) {
                   12714:             $webconfdir = '/etc/apache2';
                   12715:         }
                   12716:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12717:         if ($1 >= 10.0) {
                   12718:             $webconfdir = '/etc/apache2';
                   12719:         }
                   12720:     }
1.1210    raeburn  12721:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12722:     my (%chksum,%revnum);
                   12723:     if (ref($lines) eq 'ARRAY') {
                   12724:         chomp(@{$lines});
1.1238    raeburn  12725:         my $version = shift(@{$lines});
                   12726:         if ($version eq $release) {  
1.1210    raeburn  12727:             foreach my $line (@{$lines}) {
1.1238    raeburn  12728:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  12729:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12730:                     if ($webconfdir eq '/etc/apache2') {
                   12731:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12732:                     }
                   12733:                 }
1.1238    raeburn  12734:                 $chksum{$file} = $shasum;
                   12735:                 $revnum{$file} = $version;
1.1210    raeburn  12736:             }
                   12737:             if (ref($hashref) eq 'HASH') {
                   12738:                 %{$hashref} = (
                   12739:                                 sums     => \%chksum,
                   12740:                                 versions => \%revnum,
                   12741:                               );
                   12742:             }
                   12743:         }
                   12744:     }
1.869     albertel 12745:     return;
1.852     albertel 12746: }
1.1210    raeburn  12747: 
                   12748: sub fetch_dns_checksums {
1.1238    raeburn  12749:     my %checksums;
                   12750:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  12751:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  12752:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12753:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  12754:              \%checksums);
1.1210    raeburn  12755:     return \%checksums;
                   12756: }
                   12757: 
1.327     albertel 12758: # ------------------------------------------------------------ Read domain file
                   12759: {
1.852     albertel 12760:     my $loaded;
1.846     albertel 12761:     my %domain;
                   12762: 
1.852     albertel 12763:     sub parse_domain_tab {
                   12764: 	my ($lines) = @_;
                   12765: 	foreach my $line (@$lines) {
                   12766: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12767: 
1.846     albertel 12768: 	    chomp($line);
1.852     albertel 12769: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12770: 	    my %this_domain;
                   12771: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12772: 			       'lang_def', 'city', 'longi', 'lati',
                   12773: 			       'primary') {
                   12774: 		$this_domain{$field} = shift(@elements);
                   12775: 	    }
                   12776: 	    $domain{$name} = \%this_domain;
1.852     albertel 12777: 	}
                   12778:     }
1.864     albertel 12779: 
                   12780:     sub reset_domain_info {
                   12781: 	undef($loaded);
                   12782: 	undef(%domain);
                   12783:     }
                   12784: 
1.852     albertel 12785:     sub load_domain_tab {
1.1293    raeburn  12786: 	my ($ignore_cache,$nocache) = @_;
                   12787: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12788: 	my $fh;
                   12789: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12790: 	    my @lines = <$fh>;
                   12791: 	    &parse_domain_tab(\@lines);
1.448     albertel 12792: 	}
1.852     albertel 12793: 	close($fh);
                   12794: 	$loaded = 1;
1.327     albertel 12795:     }
1.846     albertel 12796: 
                   12797:     sub domain {
1.852     albertel 12798: 	&load_domain_tab() if (!$loaded);
                   12799: 
1.846     albertel 12800: 	my ($name,$what) = @_;
                   12801: 	return if ( !exists($domain{$name}) );
                   12802: 
                   12803: 	if (!$what) {
                   12804: 	    return $domain{$name}{'description'};
                   12805: 	}
                   12806: 	return $domain{$name}{$what};
                   12807:     }
1.974     raeburn  12808: 
                   12809:     sub domain_info {
                   12810:         &load_domain_tab() if (!$loaded);
                   12811:         return %domain;
                   12812:     }
                   12813: 
1.327     albertel 12814: }
                   12815: 
                   12816: 
1.1       albertel 12817: # ------------------------------------------------------------- Read hosts file
                   12818: {
1.838     albertel 12819:     my %hostname;
1.844     albertel 12820:     my %hostdom;
1.845     albertel 12821:     my %libserv;
1.852     albertel 12822:     my $loaded;
1.888     albertel 12823:     my %name_to_host;
1.1074    raeburn  12824:     my %internetdom;
1.1107    raeburn  12825:     my %LC_dns_serv;
1.852     albertel 12826: 
                   12827:     sub parse_hosts_tab {
                   12828: 	my ($file) = @_;
                   12829: 	foreach my $configline (@$file) {
                   12830: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12831:             chomp($configline);
                   12832: 	    if ($configline =~ /^\^/) {
                   12833:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12834:                     $LC_dns_serv{$1} = 1;
                   12835:                 }
                   12836:                 next;
                   12837:             }
1.1074    raeburn  12838: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12839: 	    $name=~s/\s//g;
                   12840: 	    if ($id && $domain && $role && $name) {
                   12841: 		$hostname{$id}=$name;
1.888     albertel 12842: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12843: 		$hostdom{$id}=$domain;
                   12844: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12845:                 if (defined($protocol)) {
                   12846:                     if ($protocol eq 'https') {
                   12847:                         $protocol{$id} = $protocol;
                   12848:                     } else {
                   12849:                         $protocol{$id} = 'http'; 
                   12850:                     }
1.968     raeburn  12851:                 } else {
1.969     raeburn  12852:                     $protocol{$id} = 'http';
1.968     raeburn  12853:                 }
1.1074    raeburn  12854:                 if (defined($intdom)) {
                   12855:                     $internetdom{$id} = $intdom;
                   12856:                 }
1.852     albertel 12857: 	    }
                   12858: 	}
                   12859:     }
1.864     albertel 12860:     
                   12861:     sub reset_hosts_info {
1.897     albertel 12862: 	&purge_remembered();
1.864     albertel 12863: 	&reset_domain_info();
                   12864: 	&reset_hosts_ip_info();
1.892     albertel 12865: 	undef(%name_to_host);
1.864     albertel 12866: 	undef(%hostname);
                   12867: 	undef(%hostdom);
                   12868: 	undef(%libserv);
                   12869: 	undef($loaded);
                   12870:     }
1.1       albertel 12871: 
1.852     albertel 12872:     sub load_hosts_tab {
1.1293    raeburn  12873: 	my ($ignore_cache,$nocache) = @_;
                   12874: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 12875: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12876: 	my @config = <$config>;
                   12877: 	&parse_hosts_tab(\@config);
                   12878: 	close($config);
                   12879: 	$loaded=1;
1.1       albertel 12880:     }
1.852     albertel 12881: 
1.838     albertel 12882:     sub hostname {
1.852     albertel 12883: 	&load_hosts_tab() if (!$loaded);
                   12884: 
1.838     albertel 12885: 	my ($lonid) = @_;
                   12886: 	return $hostname{$lonid};
                   12887:     }
1.845     albertel 12888: 
1.838     albertel 12889:     sub all_hostnames {
1.852     albertel 12890: 	&load_hosts_tab() if (!$loaded);
                   12891: 
1.838     albertel 12892: 	return %hostname;
                   12893:     }
1.845     albertel 12894: 
1.888     albertel 12895:     sub all_names {
1.1293    raeburn  12896:         my ($ignore_cache,$nocache) = @_;
                   12897: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 12898: 
                   12899: 	return %name_to_host;
                   12900:     }
                   12901: 
1.974     raeburn  12902:     sub all_host_domain {
                   12903:         &load_hosts_tab() if (!$loaded);
                   12904:         return %hostdom;
                   12905:     }
                   12906: 
1.845     albertel 12907:     sub is_library {
1.852     albertel 12908: 	&load_hosts_tab() if (!$loaded);
                   12909: 
1.845     albertel 12910: 	return exists($libserv{$_[0]});
                   12911:     }
                   12912: 
                   12913:     sub all_library {
1.852     albertel 12914: 	&load_hosts_tab() if (!$loaded);
                   12915: 
1.845     albertel 12916: 	return %libserv;
                   12917:     }
                   12918: 
1.1062    droeschl 12919:     sub unique_library {
                   12920: 	#2x reverse removes all hostnames that appear more than once
                   12921:         my %unique = reverse &all_library();
                   12922:         return reverse %unique;
                   12923:     }
                   12924: 
1.841     albertel 12925:     sub get_servers {
1.852     albertel 12926: 	&load_hosts_tab() if (!$loaded);
                   12927: 
1.841     albertel 12928: 	my ($domain,$type) = @_;
                   12929: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12930: 	                                          : %hostname;
                   12931: 	my %result;
1.842     albertel 12932: 	if (ref($domain) eq 'ARRAY') {
                   12933: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12934: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12935: 		    $result{$host} = $hostname;
                   12936: 		}
                   12937: 	    }
                   12938: 	} else {
                   12939: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12940: 		if ($hostdom{$host} eq $domain) {
                   12941: 		    $result{$host} = $hostname;
                   12942: 		}
1.841     albertel 12943: 	    }
                   12944: 	}
                   12945: 	return %result;
                   12946:     }
1.845     albertel 12947: 
1.1062    droeschl 12948:     sub get_unique_servers {
                   12949:         my %unique = reverse &get_servers(@_);
                   12950: 	return reverse %unique;
                   12951:     }
                   12952: 
1.844     albertel 12953:     sub host_domain {
1.852     albertel 12954: 	&load_hosts_tab() if (!$loaded);
                   12955: 
1.844     albertel 12956: 	my ($lonid) = @_;
                   12957: 	return $hostdom{$lonid};
                   12958:     }
                   12959: 
1.841     albertel 12960:     sub all_domains {
1.852     albertel 12961: 	&load_hosts_tab() if (!$loaded);
                   12962: 
1.841     albertel 12963: 	my %seen;
                   12964: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12965: 	return @uniq;
                   12966:     }
1.1074    raeburn  12967: 
                   12968:     sub internet_dom {
                   12969:         &load_hosts_tab() if (!$loaded);
                   12970: 
                   12971:         my ($lonid) = @_;
                   12972:         return $internetdom{$lonid};
                   12973:     }
1.1107    raeburn  12974: 
                   12975:     sub is_LC_dns {
                   12976:         &load_hosts_tab() if (!$loaded);
                   12977: 
                   12978:         my ($hostname) = @_;
                   12979:         return exists($LC_dns_serv{$hostname});
                   12980:     }
                   12981: 
1.1       albertel 12982: }
                   12983: 
1.847     albertel 12984: { 
                   12985:     my %iphost;
1.856     albertel 12986:     my %name_to_ip;
                   12987:     my %lonid_to_ip;
1.869     albertel 12988: 
1.847     albertel 12989:     sub get_hosts_from_ip {
                   12990: 	my ($ip) = @_;
                   12991: 	my %iphosts = &get_iphost();
                   12992: 	if (ref($iphosts{$ip})) {
                   12993: 	    return @{$iphosts{$ip}};
                   12994: 	}
                   12995: 	return;
1.839     albertel 12996:     }
1.864     albertel 12997:     
                   12998:     sub reset_hosts_ip_info {
                   12999: 	undef(%iphost);
                   13000: 	undef(%name_to_ip);
                   13001: 	undef(%lonid_to_ip);
                   13002:     }
1.856     albertel 13003: 
                   13004:     sub get_host_ip {
                   13005: 	my ($lonid) = @_;
                   13006: 	if (exists($lonid_to_ip{$lonid})) {
                   13007: 	    return $lonid_to_ip{$lonid};
                   13008: 	}
                   13009: 	my $name=&hostname($lonid);
                   13010:    	my $ip = gethostbyname($name);
                   13011: 	return if (!$ip || length($ip) ne 4);
                   13012: 	$ip=inet_ntoa($ip);
                   13013: 	$name_to_ip{$name}   = $ip;
                   13014: 	$lonid_to_ip{$lonid} = $ip;
                   13015: 	return $ip;
                   13016:     }
1.847     albertel 13017:     
                   13018:     sub get_iphost {
1.1293    raeburn  13019: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13020: 
1.869     albertel 13021: 	if (!$ignore_cache) {
                   13022: 	    if (%iphost) {
                   13023: 		return %iphost;
                   13024: 	    }
                   13025: 	    my ($ip_info,$cached)=
                   13026: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13027: 	    if ($cached) {
                   13028: 		%iphost      = %{$ip_info->[0]};
                   13029: 		%name_to_ip  = %{$ip_info->[1]};
                   13030: 		%lonid_to_ip = %{$ip_info->[2]};
                   13031: 		return %iphost;
                   13032: 	    }
                   13033: 	}
1.894     albertel 13034: 
                   13035: 	# get yesterday's info for fallback
                   13036: 	my %old_name_to_ip;
                   13037: 	my ($ip_info,$cached)=
                   13038: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13039: 	if ($cached) {
                   13040: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13041: 	}
                   13042: 
1.1293    raeburn  13043: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13044: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13045: 	    my $ip;
                   13046: 	    if (!exists($name_to_ip{$name})) {
                   13047: 		$ip = gethostbyname($name);
                   13048: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13049: 		    if (defined($old_name_to_ip{$name})) {
                   13050: 			$ip = $old_name_to_ip{$name};
                   13051: 			&logthis("Can't find $name defaulting to old $ip");
                   13052: 		    } else {
                   13053: 			&logthis("Name $name no IP found");
                   13054: 			next;
                   13055: 		    }
                   13056: 		} else {
                   13057: 		    $ip=inet_ntoa($ip);
1.847     albertel 13058: 		}
                   13059: 		$name_to_ip{$name} = $ip;
                   13060: 	    } else {
                   13061: 		$ip = $name_to_ip{$name};
1.653     albertel 13062: 	    }
1.888     albertel 13063: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13064: 		$lonid_to_ip{$id} = $ip;
                   13065: 	    }
                   13066: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13067: 	}
1.1293    raeburn  13068:         unless ($nocache) {
                   13069: 	    &do_cache_new('iphost','iphost',
                   13070: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13071: 		          48*60*60);
                   13072:         }
1.869     albertel 13073: 
1.847     albertel 13074: 	return %iphost;
1.598     albertel 13075:     }
                   13076: 
1.992     raeburn  13077:     #
                   13078:     #  Given a DNS returns the loncapa host name for that DNS 
                   13079:     # 
                   13080:     sub host_from_dns {
                   13081:         my ($dns) = @_;
                   13082:         my @hosts;
                   13083:         my $ip;
                   13084: 
1.993     raeburn  13085:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13086:             $ip = $name_to_ip{$dns};
                   13087:         }
                   13088:         if (!$ip) {
                   13089:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13090:             if (length($ip) == 4) { 
                   13091: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13092:             }
                   13093:         }
                   13094:         if ($ip) {
                   13095: 	    @hosts = get_hosts_from_ip($ip);
                   13096: 	    return $hosts[0];
                   13097:         }
                   13098:         return undef;
1.986     foxr     13099:     }
1.992     raeburn  13100: 
1.1074    raeburn  13101:     sub get_internet_names {
                   13102:         my ($lonid) = @_;
                   13103:         return if ($lonid eq '');
                   13104:         my ($idnref,$cached)=
                   13105:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13106:         if ($cached) {
                   13107:             return $idnref;
                   13108:         }
                   13109:         my $ip = &get_host_ip($lonid);
                   13110:         my @hosts = &get_hosts_from_ip($ip);
                   13111:         my %iphost = &get_iphost();
                   13112:         my (@idns,%seen);
                   13113:         foreach my $id (@hosts) {
                   13114:             my $dom = &host_domain($id);
                   13115:             my $prim_id = &domain($dom,'primary');
                   13116:             my $prim_ip = &get_host_ip($prim_id);
                   13117:             next if ($seen{$prim_ip});
                   13118:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13119:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13120:                     my $intdom = &internet_dom($id);
                   13121:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13122:                         push(@idns,$intdom);
                   13123:                     }
                   13124:                 }
                   13125:             }
                   13126:             $seen{$prim_ip} = 1;
                   13127:         }
1.1219    raeburn  13128:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13129:     }
                   13130: 
1.986     foxr     13131: }
                   13132: 
1.1079    raeburn  13133: sub all_loncaparevs {
1.1249    raeburn  13134:     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  13135: }
                   13136: 
1.1227    raeburn  13137: # ---------------------------------------------------------- Read loncaparev table
                   13138: {
                   13139:     sub load_loncaparevs { 
                   13140:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   13141:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   13142:                 while (my $configline=<$config>) {
                   13143:                     chomp($configline);
                   13144:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13145:                     $loncaparevs{$hostid}=$loncaparev;
                   13146:                 }
                   13147:                 close($config);
                   13148:             }
                   13149:         }
                   13150:     }
                   13151: }
                   13152: 
                   13153: # ---------------------------------------------------------- Read serverhostID table
                   13154: {
                   13155:     sub load_serverhomeIDs {
                   13156:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   13157:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   13158:                 while (my $configline=<$config>) {
                   13159:                     chomp($configline);
                   13160:                     my ($name,$id)=split(/:/,$configline);
                   13161:                     $serverhomeIDs{$name}=$id;
                   13162:                 }
                   13163:                 close($config);
                   13164:             }
                   13165:         }
                   13166:     }
                   13167: }
                   13168: 
                   13169: 
1.862     albertel 13170: BEGIN {
                   13171: 
                   13172: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13173:     unless ($readit) {
                   13174: {
                   13175:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13176:     %perlvar = (%perlvar,%{$configvars});
                   13177: }
                   13178: 
                   13179: 
1.1       albertel 13180: # ------------------------------------------------------ Read spare server file
                   13181: {
1.448     albertel 13182:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13183: 
                   13184:     while (my $configline=<$config>) {
                   13185:        chomp($configline);
1.284     matthew  13186:        if ($configline) {
1.784     albertel 13187: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13188: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13189: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13190:        }
                   13191:     }
1.448     albertel 13192:     close($config);
1.1       albertel 13193: }
1.11      www      13194: # ------------------------------------------------------------ Read permissions
                   13195: {
1.448     albertel 13196:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13197: 
                   13198:     while (my $configline=<$config>) {
1.448     albertel 13199: 	chomp($configline);
                   13200: 	if ($configline) {
                   13201: 	    my ($role,$perm)=split(/ /,$configline);
                   13202: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13203: 	}
1.11      www      13204:     }
1.448     albertel 13205:     close($config);
1.11      www      13206: }
                   13207: 
                   13208: # -------------------------------------------- Read plain texts for permissions
                   13209: {
1.448     albertel 13210:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13211: 
                   13212:     while (my $configline=<$config>) {
1.448     albertel 13213: 	chomp($configline);
                   13214: 	if ($configline) {
1.742     raeburn  13215: 	    my ($short,@plain)=split(/:/,$configline);
                   13216:             %{$prp{$short}} = ();
                   13217: 	    if (@plain > 0) {
                   13218:                 $prp{$short}{'std'} = $plain[0];
                   13219:                 for (my $i=1; $i<@plain; $i++) {
                   13220:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13221:                 }
                   13222:             }
1.448     albertel 13223: 	}
1.135     www      13224:     }
1.448     albertel 13225:     close($config);
1.135     www      13226: }
                   13227: 
                   13228: # ---------------------------------------------------------- Read package table
                   13229: {
1.448     albertel 13230:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13231: 
                   13232:     while (my $configline=<$config>) {
1.483     albertel 13233: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13234: 	chomp($configline);
                   13235: 	my ($short,$plain)=split(/:/,$configline);
                   13236: 	my ($pack,$name)=split(/\&/,$short);
                   13237: 	if ($plain ne '') {
                   13238: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13239: 	    $packagetab{$short}=$plain; 
                   13240: 	}
1.11      www      13241:     }
1.448     albertel 13242:     close($config);
1.329     matthew  13243: }
                   13244: 
1.1073    raeburn  13245: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  13246: 
                   13247: &load_loncaparevs();
1.1073    raeburn  13248: 
1.1074    raeburn  13249: # ---------------------------------------------------------- Read serverhostID table
                   13250: 
1.1227    raeburn  13251: &load_serverhomeIDs();
                   13252: 
                   13253: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13254: {
                   13255:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13256:     if (-e $file) {
                   13257:         my $parser = HTML::LCParser->new($file);
                   13258:         while (my $token = $parser->get_token()) {
                   13259:             if ($token->[0] eq 'S') {
                   13260:                 my $item = $token->[1];
                   13261:                 my $name = $token->[2]{'name'};
                   13262:                 my $value = $token->[2]{'value'};
1.1285    raeburn  13263:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  13264:                 my $namematch = $token->[2]{'namematch'};
                   13265:                 if ($item eq 'parameter') {
                   13266:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   13267:                         my $release = $parser->get_text();
                   13268:                         $release =~ s/(^\s*|\s*$ )//gx;
                   13269:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   13270:                     }
                   13271:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  13272:                     my $release = $parser->get_text();
                   13273:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  13274:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  13275:                 }
                   13276:             }
                   13277:         }
                   13278:     }
1.1073    raeburn  13279: }
                   13280: 
1.1138    raeburn  13281: # ---------------------------------------------------------- Read managers table
                   13282: {
                   13283:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   13284:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   13285:             while (my $configline=<$config>) {
                   13286:                 chomp($configline);
                   13287:                 next if ($configline =~ /^\#/);
                   13288:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13289:                     $managerstab{$configline} = 1;
                   13290:                 }
                   13291:             }
                   13292:             close($config);
                   13293:         }
                   13294:     }
                   13295: }
                   13296: 
1.329     matthew  13297: # ------------- set up temporary directory
                   13298: {
1.1117    foxr     13299:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13300: 
1.11      www      13301: }
                   13302: 
1.794     albertel 13303: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13304: 				'compress_threshold'=> 20_000,
                   13305:  			        });
1.185     www      13306: 
1.281     www      13307: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13308: $dumpcount=0;
1.958     www      13309: $locknum=0;
1.22      www      13310: 
1.163     harris41 13311: &logtouch();
1.672     albertel 13312: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13313: $readit=1;
1.564     albertel 13314:     {
                   13315: 	use integer;
                   13316: 	my $test=(2**32)+1;
1.568     albertel 13317: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13318: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13319:     }
1.195     www      13320: }
1.1       albertel 13321: }
1.179     www      13322: 
1.1       albertel 13323: 1;
1.191     harris41 13324: __END__
                   13325: 
1.243     albertel 13326: =pod
                   13327: 
1.191     harris41 13328: =head1 NAME
                   13329: 
1.243     albertel 13330: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13331: 
                   13332: =head1 SYNOPSIS
                   13333: 
1.243     albertel 13334: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13335: 
                   13336:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13337: 
1.243     albertel 13338: Common parameters:
                   13339: 
                   13340: =over 4
                   13341: 
                   13342: =item *
                   13343: 
                   13344: $uname : an internal username (if $cname expecting a course Id specifically)
                   13345: 
                   13346: =item *
                   13347: 
                   13348: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13349: 
                   13350: =item *
                   13351: 
                   13352: $symb : a resource instance identifier
                   13353: 
                   13354: =item *
                   13355: 
                   13356: $namespace : the name of a .db file that contains the data needed or
                   13357: being set.
                   13358: 
                   13359: =back
                   13360: 
1.394     bowersj2 13361: =head1 OVERVIEW
1.191     harris41 13362: 
1.394     bowersj2 13363: lonnet provides subroutines which interact with the
                   13364: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13365: about classes, users, and resources.
1.243     albertel 13366: 
                   13367: For many of these objects you can also use this to store data about
                   13368: them or modify them in various ways.
1.191     harris41 13369: 
1.394     bowersj2 13370: =head2 Symbs
1.191     harris41 13371: 
1.394     bowersj2 13372: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13373: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13374: map, the resource number of the resource in the map, and the URL of
                   13375: the resource itself. The latter is somewhat redundant, but might help
                   13376: if maps change.
                   13377: 
                   13378: An example is
                   13379: 
                   13380:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13381: 
                   13382: The respective map entry is
                   13383: 
                   13384:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13385:   title="Problem 2">
                   13386:  </resource>
                   13387: 
                   13388: Symbs are used by the random number generator, as well as to store and
                   13389: restore data specific to a certain instance of for example a problem.
                   13390: 
                   13391: =head2 Storing And Retrieving Data
                   13392: 
                   13393: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13394: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13395: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13396: is is the non-critical message twin of cstore. These functions are for
                   13397: handlers to store a perl hash to a user's permanent data space in an
                   13398: easy manner, and to retrieve it again on another call. It is expected
                   13399: that a handler would use this once at the beginning to retrieve data,
                   13400: and then again once at the end to send only the new data back.
                   13401: 
                   13402: The data is stored in the user's data directory on the user's
                   13403: homeserver under the ID of the course.
                   13404: 
                   13405: The hash that is returned by restore will have all of the previous
                   13406: value for all of the elements of the hash.
                   13407: 
                   13408: Example:
                   13409: 
                   13410:  #creating a hash
                   13411:  my %hash;
                   13412:  $hash{'foo'}='bar';
                   13413: 
                   13414:  #storing it
                   13415:  &Apache::lonnet::cstore(\%hash);
                   13416: 
                   13417:  #changing a value
                   13418:  $hash{'foo'}='notbar';
                   13419: 
                   13420:  #adding a new value
                   13421:  $hash{'bar'}='foo';
                   13422:  &Apache::lonnet::cstore(\%hash);
                   13423: 
                   13424:  #retrieving the hash
                   13425:  my %history=&Apache::lonnet::restore();
                   13426: 
                   13427:  #print the hash
                   13428:  foreach my $key (sort(keys(%history))) {
                   13429:    print("\%history{$key} = $history{$key}");
                   13430:  }
                   13431: 
                   13432: Will print out:
1.191     harris41 13433: 
1.394     bowersj2 13434:  %history{1:foo} = bar
                   13435:  %history{1:keys} = foo:timestamp
                   13436:  %history{1:timestamp} = 990455579
                   13437:  %history{2:bar} = foo
                   13438:  %history{2:foo} = notbar
                   13439:  %history{2:keys} = foo:bar:timestamp
                   13440:  %history{2:timestamp} = 990455580
                   13441:  %history{bar} = foo
                   13442:  %history{foo} = notbar
                   13443:  %history{timestamp} = 990455580
                   13444:  %history{version} = 2
                   13445: 
                   13446: Note that the special hash entries C<keys>, C<version> and
                   13447: C<timestamp> were added to the hash. C<version> will be equal to the
                   13448: total number of versions of the data that have been stored. The
                   13449: C<timestamp> attribute will be the UNIX time the hash was
                   13450: stored. C<keys> is available in every historical section to list which
                   13451: keys were added or changed at a specific historical revision of a
                   13452: hash.
                   13453: 
                   13454: B<Warning>: do not store the hash that restore returns directly. This
                   13455: will cause a mess since it will restore the historical keys as if the
                   13456: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13457: 
1.394     bowersj2 13458: Calling convention:
1.191     harris41 13459: 
1.1225    raeburn  13460:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  13461:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13462: 
1.394     bowersj2 13463: For more detailed information, see lonnet specific documentation.
1.191     harris41 13464: 
1.394     bowersj2 13465: =head1 RETURN MESSAGES
1.191     harris41 13466: 
1.394     bowersj2 13467: =over 4
1.191     harris41 13468: 
1.394     bowersj2 13469: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13470: 
1.394     bowersj2 13471: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13472: when the connection is brought back up
1.191     harris41 13473: 
1.394     bowersj2 13474: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13475: for later delivery
1.191     harris41 13476: 
1.967     bisitz   13477: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13478: 
1.394     bowersj2 13479: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13480: that was requested
1.191     harris41 13481: 
1.243     albertel 13482: =back
1.191     harris41 13483: 
1.243     albertel 13484: =head1 PUBLIC SUBROUTINES
1.191     harris41 13485: 
1.243     albertel 13486: =head2 Session Environment Functions
1.191     harris41 13487: 
1.243     albertel 13488: =over 4
1.191     harris41 13489: 
1.394     bowersj2 13490: =item * 
                   13491: X<appenv()>
1.949     raeburn  13492: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13493: the user envirnoment file, and will be restored for each access this
1.620     albertel 13494: user makes during this session, also modifies the %env for the current
1.949     raeburn  13495: process. Optional rolesarrayref - if defined contains a reference to an array
                   13496: of roles which are exempt from the restriction on modifying user.role entries 
                   13497: in the user's environment.db and in %env.    
1.191     harris41 13498: 
                   13499: =item *
1.394     bowersj2 13500: X<delenv()>
1.987     raeburn  13501: B<delenv($delthis,$regexp)>: removes all items from the session
                   13502: environment file that begin with $delthis. If the 
                   13503: optional second arg - $regexp - is true, $delthis is treated as a 
                   13504: regular expression, otherwise \Q$delthis\E is used. 
                   13505: The values are also deleted from the current processes %env.
1.191     harris41 13506: 
1.795     albertel 13507: =item * get_env_multiple($name) 
                   13508: 
                   13509: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13510: values may be defined and end up as an array ref.
                   13511: 
                   13512: returns an array of values
                   13513: 
1.243     albertel 13514: =back
                   13515: 
                   13516: =head2 User Information
1.191     harris41 13517: 
1.243     albertel 13518: =over 4
1.191     harris41 13519: 
                   13520: =item *
1.394     bowersj2 13521: X<queryauthenticate()>
                   13522: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13523: authentication scheme
                   13524: 
                   13525: =item *
1.394     bowersj2 13526: X<authenticate()>
1.1073    raeburn  13527: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13528: authenticate user from domain's lib servers (first use the current
                   13529: one). C<$upass> should be the users password.
1.1073    raeburn  13530: $checkdefauth is optional (value is 1 if a check should be made to
                   13531:    authenticate user using default authentication method, and allow
                   13532:    account creation if username does not have account in the domain).
                   13533: $clientcancheckhost is optional (value is 1 if checking whether the
                   13534:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13535: 
                   13536: =item *
1.394     bowersj2 13537: X<homeserver()>
                   13538: B<homeserver($uname,$udom)>: find the server which has
                   13539: the user's directory and files (there must be only one), this caches
                   13540: the answer, and also caches if there is a borken connection.
1.191     harris41 13541: 
                   13542: =item *
1.394     bowersj2 13543: X<idget()>
1.1300    raeburn  13544: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   13545: a list of student/employee IDs or clicker IDs
                   13546: (student/employee IDs are a unique resource in a domain, there must be 
                   13547: only 1 ID per username, and only 1 username per ID in a specific domain).
                   13548: clickerIDs are not necessarily unique, as students might share clickers.
                   13549: (returns hash: id=>name,id=>name)
1.191     harris41 13550: 
                   13551: =item *
1.394     bowersj2 13552: X<idrget()>
                   13553: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13554: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13555: 
                   13556: =item *
1.394     bowersj2 13557: X<idput()>
1.1300    raeburn  13558: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   13559: names and associated student/employee IDs or clicker IDs.
                   13560: 
                   13561: =item *
                   13562: X<iddel()>
                   13563: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   13564: student/employee ID or clicker ID username look-ups from domain.
                   13565: The homeserver ($uhome) and namespace ($namespace) are optional.
                   13566: If no $uhome is provided, it will be determined usig &homeserver()
                   13567: for each user.  If no $namespace is provided, the default is ids.
                   13568: 
                   13569: =item *
                   13570: X<updateclickers()>
                   13571: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   13572: clicker ID-to-username look-ups in clickers.db on library server.
                   13573: Permitted actions are add or del (i.e., add or delete). The 
                   13574: clickers.db contains clickerID as keys (escaped), and each corresponding
                   13575: value is an escaped comma-separated list of usernames (for whom the
                   13576: library server is the homeserver), who registered that particular ID.
                   13577: If $critical is true, the update will be sent via &critical, otherwise
                   13578: &reply() will be used.
1.191     harris41 13579: 
                   13580: =item *
1.394     bowersj2 13581: X<rolesinit()>
1.1169    droeschl 13582: B<rolesinit($udom,$username)>: get user privileges.
                   13583: returns user role, first access and timer interval hashes
1.243     albertel 13584: 
                   13585: =item *
1.1171    droeschl 13586: X<privileged()>
                   13587: B<privileged($username,$domain)>: returns a true if user has a
                   13588: privileged and active role (i.e. su or dc), false otherwise.
                   13589: 
                   13590: =item *
1.551     albertel 13591: X<getsection()>
                   13592: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13593: course $cname, return section name/number or '' for "not in course"
                   13594: and '-1' for "no section"
                   13595: 
                   13596: =item *
1.394     bowersj2 13597: X<userenvironment()>
                   13598: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13599: passed in @what from the requested user's environment, returns a hash
                   13600: 
1.858     raeburn  13601: =item * 
                   13602: X<userlog_query()>
1.859     albertel 13603: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13604: activity.log file. %filters defines filters applied when parsing the
                   13605: log file. These can be start or end timestamps, or the type of action
                   13606: - log to look for Login or Logout events, check for Checkin or
                   13607: Checkout, role for role selection. The response is in the form
                   13608: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13609: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13610: 
1.243     albertel 13611: =back
                   13612: 
                   13613: =head2 User Roles
                   13614: 
                   13615: =over 4
                   13616: 
                   13617: =item *
                   13618: 
1.1284    raeburn  13619: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13620: returns codes for allowed actions.
                   13621: 
                   13622: The first argument is required, all others are optional.
                   13623: 
                   13624: $priv is the privilege being checked.
                   13625: $uri contains additional information about what is being checked for access (e.g.,
                   13626: URL, course ID etc.). 
                   13627: $symb is the unique resource instance identifier in a course; if needed,
                   13628: but not provided, it will be retrieved via a call to &symbread(). 
                   13629: $role is the role for which a priv is being checked (only used if priv is evb). 
                   13630: $clientip is the user's IP address (only used when checking for access to portfolio 
                   13631: files).
                   13632: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   13633: prevents recursive calls to &allowed.
                   13634: 
1.243     albertel 13635:  F: full access
                   13636:  U,I,K: authentication modes (cxx only)
                   13637:  '': forbidden
                   13638:  1: user needs to choose course
                   13639:  2: browse allowed
1.766     albertel 13640:  A: passphrase authentication needed
1.1284    raeburn  13641:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13642: 
                   13643: =item *
                   13644: 
1.1192    raeburn  13645: constructaccess($url,$setpriv) : check for access to construction space URL
                   13646: 
                   13647: See if the owner domain and name in the URL match those in the
                   13648: expected environment.  If so, return three element list
                   13649: ($ownername,$ownerdomain,$ownerhome).
                   13650: 
                   13651: Otherwise return the null string.
                   13652: 
                   13653: If second argument 'setpriv' is true, it assigns the privileges,
                   13654: and returns the same three element list, unless the owner has
                   13655: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13656: in which case the null string is returned.
                   13657: 
                   13658: =item *
                   13659: 
1.243     albertel 13660: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   13661: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   13662: and course level
                   13663: 
                   13664: =item *
                   13665: 
1.988     raeburn  13666: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13667: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13668: $type is Course (default) or Community.
1.988     raeburn  13669: If $forcedefault evaluates to true, text returned will be default 
                   13670: text for $type. Otherwise, if this is a course, the text returned 
                   13671: will be a custom name for the role (if defined in the course's 
                   13672: environment).  If no custom name is defined the default is returned.
                   13673:    
1.832     raeburn  13674: =item *
                   13675: 
1.1219    raeburn  13676: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13677: All arguments are optional. Returns a hash of a roles, either for
                   13678: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13679: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13680: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13681: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13682: For each key, value is set to colon-separated start and end times for
                   13683: the role.  If no username and domain are specified, will default to
1.934     raeburn  13684: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13685: of role statuses (active, future or previous), roles 
                   13686: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13687: to restrict the list of roles reported. If no array ref is 
                   13688: provided for types, will default to return only active roles.
1.834     albertel 13689: 
1.1195    raeburn  13690: =item *
                   13691: 
                   13692: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  13693: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   13694: 
                   13695: Additional optional arguments are: $type (if role checking is to be restricted 
                   13696: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  13697: available roles) or future (roles available in the future), and
                   13698: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  13699: have active Domain Coordinator role in course's domain or in additional
                   13700: domains (specified in 'Domains to check for privileged users' in course
                   13701: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13702: 
                   13703: =item *
                   13704: 
                   13705: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13706: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13707: $possdomains and $possroles are optional array refs -- to domains to check and
                   13708: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13709: users' roles.db to check for a dc or su role in any domain. This can be
                   13710: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13711: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13712: this then allows &privileged_by_domain() to be used, which caches the identity
                   13713: of privileged users, eliminating the need for repeated calls to &dump().
                   13714: 
                   13715: =item *
                   13716: 
                   13717: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13718: where the outer hash keys are domains specified in the $possdomains array ref,
                   13719: next inner hash keys are privileged roles specified in the $roles array ref,
                   13720: and the innermost hash contains key = value pairs for username:domain = end:start
                   13721: for active or future "privileged" users with that role in that domain. To avoid
                   13722: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13723: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  13724: 
1.243     albertel 13725: =back
                   13726: 
                   13727: =head2 User Modification
                   13728: 
                   13729: =over 4
                   13730: 
                   13731: =item *
                   13732: 
1.957     raeburn  13733: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13734: user for the level given by URL.  Optional start and end dates (leave empty
                   13735: string or zero for "no date")
1.191     harris41 13736: 
                   13737: =item *
                   13738: 
1.243     albertel 13739: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13740: change a users, password, possible return values are: ok,
                   13741: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13742: refused
1.191     harris41 13743: 
                   13744: =item *
                   13745: 
1.243     albertel 13746: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13747: 
                   13748: =item *
                   13749: 
1.1058    raeburn  13750: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13751:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13752: 
                   13753: will update user information (firstname,middlename,lastname,generation,
                   13754: permanentemail), and if forceid is true, student/employee ID also.
                   13755: A user's institutional affiliation(s) can also be updated.
                   13756: User information fields will not be overwritten with empty entries 
                   13757: unless the field is included in the $candelete array reference.
                   13758: This array is included when a single user is modified via "Manage Users",
                   13759: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13760: 
                   13761: =item *
                   13762: 
1.286     matthew  13763: modifystudent
                   13764: 
1.957     raeburn  13765: modify a student's enrollment and identification information.
1.1235    raeburn  13766: The course id is resolved based on the current user's environment.  
                   13767: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13768: associated with a course.
                   13769: 
1.297     matthew  13770: This call is essentially a wrapper for lonnet::modifyuser and
                   13771: lonnet::modify_student_enrollment
1.286     matthew  13772: 
                   13773: Inputs: 
                   13774: 
                   13775: =over 4
                   13776: 
1.957     raeburn  13777: =item B<$udom> Student's loncapa domain
1.286     matthew  13778: 
1.957     raeburn  13779: =item B<$uname> Student's loncapa login name
1.286     matthew  13780: 
1.964     bisitz   13781: =item B<$uid> Student/Employee ID
1.286     matthew  13782: 
1.957     raeburn  13783: =item B<$umode> Student's authentication mode
1.286     matthew  13784: 
1.957     raeburn  13785: =item B<$upass> Student's password
1.286     matthew  13786: 
1.957     raeburn  13787: =item B<$first> Student's first name
1.286     matthew  13788: 
1.957     raeburn  13789: =item B<$middle> Student's middle name
1.286     matthew  13790: 
1.957     raeburn  13791: =item B<$last> Student's last name
1.286     matthew  13792: 
1.957     raeburn  13793: =item B<$gene> Student's generation
1.286     matthew  13794: 
1.957     raeburn  13795: =item B<$usec> Student's section in course
1.286     matthew  13796: 
                   13797: =item B<$end> Unix time of the roles expiration
                   13798: 
                   13799: =item B<$start> Unix time of the roles start date
                   13800: 
                   13801: =item B<$forceid> If defined, allow $uid to be changed
                   13802: 
                   13803: =item B<$desiredhome> server to use as home server for student
                   13804: 
1.957     raeburn  13805: =item B<$email> Student's permanent e-mail address
                   13806: 
                   13807: =item B<$type> Type of enrollment (auto or manual)
                   13808: 
1.963     raeburn  13809: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13810: 
                   13811: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13812: 
1.963     raeburn  13813: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13814: 
1.963     raeburn  13815: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13816: 
1.1216    raeburn  13817: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13818: 
                   13819: =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  13820: 
1.286     matthew  13821: =back
1.297     matthew  13822: 
                   13823: =item *
                   13824: 
                   13825: modify_student_enrollment
                   13826: 
1.1235    raeburn  13827: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13828: 'role.request.course' must be defined for this function to proceed.
                   13829: 
                   13830: Inputs:
                   13831: 
                   13832: =over 4
                   13833: 
1.1235    raeburn  13834: =item $udom, student's domain
1.297     matthew  13835: 
1.1235    raeburn  13836: =item $uname, student's name
1.297     matthew  13837: 
1.1235    raeburn  13838: =item $uid, student's user id
1.297     matthew  13839: 
1.1235    raeburn  13840: =item $first, student's first name
1.297     matthew  13841: 
                   13842: =item $middle
                   13843: 
                   13844: =item $last
                   13845: 
                   13846: =item $gene
                   13847: 
                   13848: =item $usec
                   13849: 
                   13850: =item $end
                   13851: 
                   13852: =item $start
                   13853: 
1.957     raeburn  13854: =item $type
                   13855: 
                   13856: =item $locktype
                   13857: 
                   13858: =item $cid
                   13859: 
                   13860: =item $selfenroll
                   13861: 
                   13862: =item $context
                   13863: 
1.1216    raeburn  13864: =item $credits, number of credits student will earn from this class
                   13865: 
1.297     matthew  13866: =back
                   13867: 
1.191     harris41 13868: 
                   13869: =item *
                   13870: 
1.243     albertel 13871: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13872: custom role; give a custom role to a user for the level given by URL.  Specify
                   13873: name and domain of role author, and role name
1.191     harris41 13874: 
                   13875: =item *
                   13876: 
1.243     albertel 13877: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13878: 
                   13879: =item *
                   13880: 
1.243     albertel 13881: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13882: 
                   13883: =back
                   13884: 
                   13885: =head2 Course Infomation
                   13886: 
                   13887: =over 4
1.191     harris41 13888: 
                   13889: =item *
                   13890: 
1.1118    foxr     13891: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13892: specified course id, including all environment settings for the
                   13893: course, the description of the course will be in the hash under the
                   13894: key 'description'
1.191     harris41 13895: 
1.1118    foxr     13896: $options is an optional parameter that if supplied is a hash reference that controls
                   13897: what how this function works.  It has the following key/values:
                   13898: 
                   13899: =over 4
                   13900: 
                   13901: =item freshen_cache
                   13902: 
                   13903: If defined, and the environment cache for the course is valid, it is 
                   13904: returned in the returned hash.
                   13905: 
                   13906: =item one_time
                   13907: 
                   13908: If defined, the last cache time is set to _now_
                   13909: 
                   13910: =item user
                   13911: 
                   13912: If defined, the supplied username is used instead of the current user.
                   13913: 
                   13914: 
                   13915: =back
                   13916: 
1.191     harris41 13917: =item *
                   13918: 
1.624     albertel 13919: resdata($name,$domain,$type,@which) : request for current parameter
                   13920: setting for a specific $type, where $type is either 'course' or 'user',
                   13921: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  13922: answers for 10 minutes.
1.243     albertel 13923: 
1.877     foxr     13924: =item *
                   13925: 
                   13926: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13927: data base, returning a hash that is keyed by the resource name and has
                   13928: values that are the resource value.  I believe that the timestamps and
                   13929: versions are also returned.
                   13930: 
1.1236    raeburn  13931: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13932: supplemental content area. This routine caches the number of files for 
                   13933: 10 minutes.
                   13934: 
1.243     albertel 13935: =back
                   13936: 
                   13937: =head2 Course Modification
                   13938: 
                   13939: =over 4
1.191     harris41 13940: 
                   13941: =item *
                   13942: 
1.243     albertel 13943: writecoursepref($courseid,%prefs) : write preferences (environment
                   13944: database) for a course
1.191     harris41 13945: 
                   13946: =item *
                   13947: 
1.1011    raeburn  13948: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13949: 
                   13950: =item *
                   13951: 
1.1038    raeburn  13952: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13953: 
1.1167    droeschl 13954: =item *
                   13955: 
                   13956: is_course($courseid), is_course($cdom, $cnum)
                   13957: 
                   13958: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13959: two component version $cdom, $cnum. It checks if the specified course exists.
                   13960: 
                   13961: Returns:
                   13962:     undef if the course doesn't exist, otherwise
                   13963:     in scalar context the combined courseid.
                   13964:     in list context the two components of the course identifier, domain and 
                   13965:     courseid.    
                   13966: 
1.243     albertel 13967: =back
                   13968: 
                   13969: =head2 Resource Subroutines
                   13970: 
                   13971: =over 4
1.191     harris41 13972: 
                   13973: =item *
                   13974: 
1.243     albertel 13975: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13976: 
                   13977: =item *
                   13978: 
1.243     albertel 13979: repcopy($filename) : subscribes to the requested file, and attempts to
                   13980: replicate from the owning library server, Might return
1.607     raeburn  13981: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13982: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13983: resource. Expects the local filesystem pathname
                   13984: (/home/httpd/html/res/....)
                   13985: 
                   13986: =back
                   13987: 
                   13988: =head2 Resource Information
                   13989: 
                   13990: =over 4
1.191     harris41 13991: 
                   13992: =item *
                   13993: 
1.1228    raeburn  13994: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13995: and returns the value of a variety of different possible values,
                   13996: $varname should be a request string, and the other parameters can be
                   13997: used to specify who and what one is asking about. Ordinarily, $cid 
                   13998: does not need to be specified, as it is retrived from 
                   13999: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14000: within lonuserstate::loadmap() when initializing a course, before
                   14001: $env{'request.course.id'} has been set, so it needs to be provided
                   14002: in that one case.
1.243     albertel 14003: 
                   14004: Possible values for $varname are environment.lastname (or other item
                   14005: from the envirnment hash), user.name (or someother aspect about the
                   14006: user), resource.0.maxtries (or some other part and parameter of a
                   14007: resource)
1.204     albertel 14008: 
                   14009: =item *
                   14010: 
1.243     albertel 14011: directcondval($number) : get current value of a condition; reads from a state
                   14012: string
1.204     albertel 14013: 
                   14014: =item *
                   14015: 
1.243     albertel 14016: condval($condidx) : value of condition index based on state
1.204     albertel 14017: 
                   14018: =item *
                   14019: 
1.243     albertel 14020: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14021: resource's metadata, $what should be either a specific key, or either
                   14022: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14023: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14024: 
                   14025: this function automatically caches all requests
1.191     harris41 14026: 
                   14027: =item *
                   14028: 
1.243     albertel 14029: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14030: network of library servers; returns file handle of where SQL and regex results
                   14031: will be stored for query
1.191     harris41 14032: 
                   14033: =item *
                   14034: 
1.1282    raeburn  14035: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   14036: return symbolic list entry (all arguments optional). 
                   14037: 
                   14038: Args: filename is the filename (including path) for the file for which a symb 
                   14039: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   14040: to check access status if more than one resource was found in the bighash 
                   14041: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   14042: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   14043: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14044: cause possible symbs to be checked to determine if they are subject to content
                   14045: blocking, if so they will not be included as possible symbs; possibles is a
                   14046: ref to a hash, which, as a side effect, will be populated with all possible 
                   14047: symbs (content blocking not tested).
                   14048:  
1.243     albertel 14049: returns the data handle
1.191     harris41 14050: 
                   14051: =item *
                   14052: 
1.1190    raeburn  14053: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   14054: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14055: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  14056: on failure, user must be in a course, as it assumes the existence of
                   14057: the course initial hash, and uses $env('request.course.id'}.  The third
                   14058: arg is an optional reference to a scalar.  If this arg is passed in the 
                   14059: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14060: encrypted; otherwise it will be null.  
1.191     harris41 14061: 
                   14062: =item *
                   14063: 
1.243     albertel 14064: symbclean($symb) : removes versions numbers from a symb, returns the
                   14065: cleaned symb
1.191     harris41 14066: 
                   14067: =item *
                   14068: 
1.243     albertel 14069: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14070: course map, user must be in a course for it to work.
1.191     harris41 14071: 
                   14072: =item *
                   14073: 
1.243     albertel 14074: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14075: 
                   14076: =item *
                   14077: 
1.243     albertel 14078: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14079: a random seed, all arguments are optional, if they aren't sent it uses the
                   14080: environment to derive them. Note: if symb isn't sent and it can't get one
                   14081: from &symbread it will use the current time as its return value
1.191     harris41 14082: 
                   14083: =item *
                   14084: 
1.243     albertel 14085: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14086: unfakeable, receipt
1.191     harris41 14087: 
                   14088: =item *
                   14089: 
1.620     albertel 14090: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14091: 
                   14092: =item *
                   14093: 
1.243     albertel 14094: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14095: 
                   14096: =item *
                   14097: 
1.243     albertel 14098: 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 14099: 
                   14100: =item *
                   14101: 
1.243     albertel 14102: 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 14103: 
                   14104: =item *
                   14105: 
1.243     albertel 14106: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14107: 
                   14108: =item *
                   14109: 
1.243     albertel 14110: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14111: forcing spreadsheet to reevaluate the resource scores next time.
                   14112: 
1.1195    raeburn  14113: =item * 
                   14114: 
1.1196    raeburn  14115: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14116: when viewing in course context.
1.1195    raeburn  14117: 
1.1196    raeburn  14118:  input: six args -- filename (decluttered), course number, course domain,
                   14119:                     url, symb (if registered) and group (if this is a 
                   14120:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  14121: 
1.1196    raeburn  14122:  output: array of five scalars --
1.1195    raeburn  14123:          $cfile -- url for file editing if editable on current server
                   14124:          $home -- homeserver of resource (i.e., for author if published,
                   14125:                                           or course if uploaded.).
                   14126:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  14127:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   14128:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  14129: 
                   14130: =item *
                   14131: 
                   14132: is_course_upload($file,$cnum,$cdom)
                   14133: 
                   14134: Used in course context to determine if current file was uploaded to 
                   14135: the course (i.e., would be found in /userfiles/docs on the course's 
                   14136: homeserver.
                   14137: 
                   14138:   input: 3 args -- filename (decluttered), course number and course domain.
                   14139:   output: boolean -- 1 if file was uploaded.
                   14140: 
1.243     albertel 14141: =back
                   14142: 
                   14143: =head2 Storing/Retreiving Data
                   14144: 
                   14145: =over 4
1.191     harris41 14146: 
                   14147: =item *
                   14148: 
1.1269    raeburn  14149: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   14150: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14151: the remaining args aren't required and if they aren't passed or are '' they will
                   14152: be derived from the env (with the exception of $laststore, which is an 
                   14153: optional arg used when a user's submission is stored in grading).
                   14154: $laststore is $version=$timestamp, where $version is the most recent version
                   14155: number retrieved for the corresponding $symb in the $namespace db file, and
                   14156: $timestamp is the timestamp for that transaction (UNIX time).
                   14157: $laststore is currently only passed when cstore() is called by 
                   14158: structuretags::finalize_storage().
1.191     harris41 14159: 
                   14160: =item *
                   14161: 
1.1269    raeburn  14162: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   14163: but uses critical subroutine
1.191     harris41 14164: 
                   14165: =item *
                   14166: 
1.243     albertel 14167: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14168: all args are optional
1.191     harris41 14169: 
                   14170: =item *
                   14171: 
1.717     albertel 14172: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14173: dumps the complete (or key matching regexp) namespace into a hash
                   14174: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14175: normally &store()ed into
                   14176: 
                   14177: $range should be either an integer '100' (give me the first 100
                   14178:                                            matching records)
                   14179:               or be  two integers sperated by a - with no spaces
                   14180:                  '30-50' (give me the 30th through the 50th matching
                   14181:                           records)
                   14182: 
                   14183: 
                   14184: =item *
                   14185: 
1.1269    raeburn  14186: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14187: replaces a &store() version of data with a replacement set of data
                   14188: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  14189: reference. If $tolog is true, the transaction is logged in the courselog
                   14190: with an action=PUTSTORE.
1.717     albertel 14191: 
                   14192: =item *
                   14193: 
1.243     albertel 14194: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14195: works very similar to store/cstore, but all data is stored in a
                   14196: temporary location and can be reset using tmpreset, $storehash should
                   14197: be a hash reference, returns nothing on success
1.191     harris41 14198: 
                   14199: =item *
                   14200: 
1.243     albertel 14201: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14202: similar to restore, but all data is stored in a temporary location and
                   14203: can be reset using tmpreset. Returns a hash of values on success,
                   14204: error string otherwise.
1.191     harris41 14205: 
                   14206: =item *
                   14207: 
1.243     albertel 14208: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14209: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14210: 
                   14211: =item *
                   14212: 
1.243     albertel 14213: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14214: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14215: 
                   14216: =item *
                   14217: 
1.243     albertel 14218: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14219: namesp ($udom and $uname are optional)
1.191     harris41 14220: 
                   14221: =item *
                   14222: 
1.702     albertel 14223: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14224: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14225: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14226: 
1.702     albertel 14227: $range should be either an integer '100' (give me the first 100
                   14228:                                            matching records)
                   14229:               or be  two integers sperated by a - with no spaces
                   14230:                  '30-50' (give me the 30th through the 50th matching
                   14231:                           records)
1.449     matthew  14232: =item *
                   14233: 
                   14234: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14235: $store can be a scalar, an array reference, or if the amount to be 
                   14236: incremented is > 1, a hash reference.
                   14237: 
                   14238: ($udom and $uname are optional)
1.191     harris41 14239: 
                   14240: =item *
                   14241: 
1.243     albertel 14242: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14243: ($udom and $uname are optional)
1.191     harris41 14244: 
                   14245: =item *
                   14246: 
1.243     albertel 14247: cput($namespace,$storehash,$udom,$uname) : critical put
                   14248: ($udom and $uname are optional)
1.191     harris41 14249: 
                   14250: =item *
                   14251: 
1.748     albertel 14252: newput($namespace,$storehash,$udom,$uname) :
                   14253: 
                   14254: Attempts to store the items in the $storehash, but only if they don't
                   14255: currently exist, if this succeeds you can be certain that you have 
                   14256: successfully created a new key value pair in the $namespace db.
                   14257: 
                   14258: 
                   14259: Args:
                   14260:  $namespace: name of database to store values to
                   14261:  $storehash: hashref to store to the db
                   14262:  $udom: (optional) domain of user containing the db
                   14263:  $uname: (optional) name of user caontaining the db
                   14264: 
                   14265: Returns:
                   14266:  'ok' -> succeeded in storing all keys of $storehash
                   14267:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14268:                         least <key> already existed in the db (other
                   14269:                         requested keys may also already exist)
1.967     bisitz   14270:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14271:  'con_lost' -> unable to contact request server
                   14272:  'refused' -> action was not allowed by remote machine
                   14273: 
                   14274: 
                   14275: =item *
                   14276: 
1.243     albertel 14277: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14278: reference filled in from namesp (encrypts the return communication)
                   14279: ($udom and $uname are optional)
1.191     harris41 14280: 
                   14281: =item *
                   14282: 
1.243     albertel 14283: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14284: critical subroutine
                   14285: 
1.806     raeburn  14286: =item *
                   14287: 
1.860     raeburn  14288: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14289: array reference filled in from namespace found in domain level on either
                   14290: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14291: 
                   14292: =item *
                   14293: 
1.860     raeburn  14294: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14295: domain level either on specified domain server ($uhome) or primary domain 
                   14296: server ($udom and $uhome are optional)
1.806     raeburn  14297: 
1.943     raeburn  14298: =item * 
                   14299: 
1.1240    raeburn  14300: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   14301: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14302: the target domain.
                   14303: 
                   14304: May also include additional key => value pairs for the following groups:
                   14305: 
                   14306: =over
                   14307: 
                   14308: =item
                   14309: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14310: 
                   14311: =over
                   14312: 
                   14313: =item defaultquota, authorquota
                   14314: 
                   14315: =back
                   14316: 
                   14317: =item
                   14318: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14319: portfolio for users).
                   14320: 
                   14321: =over
                   14322: 
                   14323: =item
                   14324: aboutme, blog, webdav, portfolio
                   14325: 
                   14326: =back
                   14327: 
                   14328: =item
                   14329: requestcourses: ability to request courses, and how requests are processed.
                   14330: 
                   14331: =over
                   14332: 
                   14333: =item
1.1305    raeburn  14334: official, unofficial, community, textbook, placement
1.1240    raeburn  14335: 
                   14336: =back
                   14337: 
                   14338: =item
                   14339: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14340: 
                   14341: =over
                   14342: 
                   14343: =item
1.1256    raeburn  14344: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  14345: 
                   14346: =back
                   14347: 
                   14348: =item
                   14349: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14350: for course's uploaded content.
                   14351: 
                   14352: =over
                   14353: 
                   14354: =item
1.1246    raeburn  14355: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  14356: communityquota, textbookquota, placementquota
1.1240    raeburn  14357: 
                   14358: =back
                   14359: 
                   14360: =item
                   14361: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14362: on your servers.
                   14363: 
                   14364: =over
                   14365: 
                   14366: =item 
                   14367: remotesessions, hostedsessions
                   14368: 
                   14369: =back
                   14370: 
                   14371: =back
                   14372: 
                   14373: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14374: utility to create a configuration.db file on a domain's primary library server 
                   14375: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14376: -- corresponding values are authentication type (internal, krb4, krb5,
                   14377: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   14378: will be available. Values are retrieved from cache (if current), unless the
                   14379: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14380: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14381: 
                   14382: Typical usage:
1.943     raeburn  14383: 
1.1240    raeburn  14384: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14385: 
1.243     albertel 14386: =back
                   14387: 
                   14388: =head2 Network Status Functions
                   14389: 
                   14390: =over 4
1.191     harris41 14391: 
                   14392: =item *
                   14393: 
1.1137    raeburn  14394: dirlist() : return directory list based on URI (first arg).
                   14395: 
                   14396: Inputs: 1 required, 5 optional.
                   14397: 
                   14398: =over
                   14399: 
                   14400: =item 
                   14401: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14402: 
                   14403: =item
                   14404: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14405: 
                   14406: =item
                   14407: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14408: 
                   14409: =item
                   14410: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14411: 
                   14412: =item
                   14413: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14414: 
                   14415: =item 
                   14416: $alternateRoot - path to prepend in place of path from $uri.
                   14417: 
                   14418: =back
                   14419: 
                   14420: Returns: Array of up to two items.
                   14421: 
                   14422: =over
                   14423: 
                   14424: a reference to an array of files/subdirectories
                   14425: 
                   14426: =over
                   14427: 
                   14428: Each element in the array of files/subdirectories is a & separated list of
                   14429: item name and the result of running stat on the item.  If dirlist was requested
                   14430: for a file instead of a directory, the item name will be ''. For a directory 
                   14431: listing, if the item is a metadata file, the element will end &N&M 
                   14432: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14433: default copyright set (1).  
                   14434: 
                   14435: =back
                   14436: 
                   14437: a scalar containing error condition (if encountered).
                   14438: 
                   14439: =over
                   14440: 
                   14441: =item 
                   14442: no_host (no homeserver identified for $username:$domain).
                   14443: 
                   14444: =item 
                   14445: no_such_host (server contacted for listing not identified as valid host).
                   14446: 
                   14447: =item 
                   14448: con_lost (connection to remote server failed).
                   14449: 
                   14450: =item 
                   14451: refused (invalid $username:$domain received on lond side).
                   14452: 
                   14453: =item 
                   14454: no_such_dir (directory at specified path on lond side does not exist). 
                   14455: 
                   14456: =item 
                   14457: empty (directory at specified path on lond side is empty).
                   14458: 
                   14459: =over
                   14460: 
                   14461: This is currently not encountered because the &ls3, &ls2, 
                   14462: &ls (_handler) routines on the lond side do not filter out
                   14463: . and .. from a directory listing. 
                   14464: 
                   14465: =back
                   14466: 
                   14467: =back
                   14468: 
                   14469: =back
1.191     harris41 14470: 
                   14471: =item *
                   14472: 
1.243     albertel 14473: spareserver() : find server with least workload from spare.tab
                   14474: 
1.986     foxr     14475: 
                   14476: =item *
                   14477: 
                   14478: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14479: if there is no corresponding loncapa host.
                   14480: 
1.243     albertel 14481: =back
                   14482: 
1.986     foxr     14483: 
1.243     albertel 14484: =head2 Apache Request
                   14485: 
                   14486: =over 4
1.191     harris41 14487: 
                   14488: =item *
                   14489: 
1.243     albertel 14490: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14491: localhost, posts hash
                   14492: 
                   14493: =back
                   14494: 
                   14495: =head2 Data to String to Data
                   14496: 
                   14497: =over 4
1.191     harris41 14498: 
                   14499: =item *
                   14500: 
1.243     albertel 14501: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14502: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14503: 
                   14504: =item *
                   14505: 
1.243     albertel 14506: hashref2str($hashref) : convert a hashref into a string complete with
                   14507: escaping and '=' and '&' separators, supports elements that are
                   14508: arrayrefs and hashrefs
1.191     harris41 14509: 
                   14510: =item *
                   14511: 
1.243     albertel 14512: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14513: with escaping and '&' separators, supports elements that are arrayrefs
                   14514: and hashrefs
1.191     harris41 14515: 
                   14516: =item *
                   14517: 
1.243     albertel 14518: str2hash($string) : convert string to hash using unescaping and
                   14519: splitting on '=' and '&', supports elements that are arrayrefs and
                   14520: hashrefs
1.191     harris41 14521: 
                   14522: =item *
                   14523: 
1.243     albertel 14524: str2array($string) : convert string to hash using unescaping and
                   14525: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14526: 
                   14527: =back
                   14528: 
                   14529: =head2 Logging Routines
                   14530: 
                   14531: 
                   14532: These routines allow one to make log messages in the lonnet.log and
                   14533: lonnet.perm logfiles.
1.191     harris41 14534: 
1.1119    foxr     14535: =over 4
                   14536: 
1.191     harris41 14537: =item *
                   14538: 
1.243     albertel 14539: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14540: 
                   14541: =item *
                   14542: 
1.243     albertel 14543: logthis() : append message to the normal lonnet.log file, it gets
                   14544: preiodically rolled over and deleted.
1.191     harris41 14545: 
                   14546: =item *
                   14547: 
1.243     albertel 14548: logperm() : append a permanent message to lonnet.perm.log, this log
                   14549: file never gets deleted by any automated portion of the system, only
                   14550: messages of critical importance should go in here.
                   14551: 
1.1119    foxr     14552: 
1.243     albertel 14553: =back
                   14554: 
                   14555: =head2 General File Helper Routines
                   14556: 
                   14557: =over 4
1.191     harris41 14558: 
                   14559: =item *
                   14560: 
1.481     raeburn  14561: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14562: (a) files in /uploaded
                   14563:   (i) If a local copy of the file exists - 
                   14564:       compares modification date of local copy with last-modified date for 
                   14565:       definitive version stored on home server for course. If local copy is 
                   14566:       stale, requests a new version from the home server and stores it. 
                   14567:       If the original has been removed from the home server, then local copy 
                   14568:       is unlinked.
                   14569:   (ii) If local copy does not exist -
                   14570:       requests the file from the home server and stores it. 
                   14571:   
                   14572:   If $caller is 'uploadrep':  
                   14573:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14574:     for request for files originally uploaded via DOCS. 
                   14575:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14576:   
                   14577:   Otherwise:
                   14578:      This indicates a call from the content generation phase of the request.
                   14579:      -  returns the entire contents of the file or -1.
                   14580:      
                   14581: (b) files in /res
                   14582:    - returns the entire contents of a file or -1; 
                   14583:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14584: 
1.712     albertel 14585: 
                   14586: =item *
                   14587: 
                   14588: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14589:                   reference
                   14590: 
                   14591: returns either a stat() list of data about the file or an empty list
                   14592: if the file doesn't exist or couldn't find out about it (connection
                   14593: problems or user unknown)
                   14594: 
1.191     harris41 14595: =item *
                   14596: 
1.243     albertel 14597: filelocation($dir,$file) : returns file system location of a file
                   14598: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14599: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14600: and a file of ../bob will become /a/bob)
1.191     harris41 14601: 
                   14602: =item *
                   14603: 
                   14604: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14605: filelocation except for hrefs
                   14606: 
                   14607: =item *
                   14608: 
1.1261    raeburn  14609: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14610: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14611: 
1.243     albertel 14612: =back
                   14613: 
1.608     albertel 14614: =head2 Usererfile file routines (/uploaded*)
                   14615: 
                   14616: =over 4
                   14617: 
                   14618: =item *
                   14619: 
                   14620: userfileupload(): main rotine for putting a file in a user or course's
                   14621:                   filespace, arguments are,
                   14622: 
1.620     albertel 14623:  formname - required - this is the name of the element in $env where the
1.608     albertel 14624:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14625:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14626:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14627:  context - if coursedoc, store the file in the course of the active role
                   14628:              of the current user; 
                   14629:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14630:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14631:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14632:          if undefined, it will be placed in "unknown"
                   14633: 
                   14634:  (This routine calls clean_filename() to remove any dangerous
                   14635:  characters from the filename, and then calls finuserfileupload() to
                   14636:  complete the transaction)
                   14637: 
                   14638:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14639:  and /adm/notfound.html if unsuccessful
                   14640: 
                   14641: =item *
                   14642: 
                   14643: clean_filename(): routine for cleaing a filename up for storage in
                   14644:                  userfile space, argument is:
                   14645: 
                   14646:  filename - proposed filename
                   14647: 
                   14648: returns: the new clean filename
                   14649: 
                   14650: =item *
                   14651: 
1.1090    raeburn  14652: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14653: userspace, probably shouldn't be called directly
                   14654: 
                   14655:   docuname: username or courseid of destination for the file
                   14656:   docudom: domain of user/course of destination for the file
                   14657:   formname: same as for userfileupload()
1.1090    raeburn  14658:   fname: filename (including subdirectories) for the file
                   14659:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14660:   allfiles: reference to hash used to store objects found by parser
                   14661:   codebase: reference to hash used for codebases of java objects found by parser
                   14662:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14663:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14664:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14665:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14666:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14667:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14668:   mimetype: reference to scalar to accommodate mime type determined
                   14669:             from File::MMagic if $parser = parse.
1.608     albertel 14670: 
                   14671:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14672:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14673:  was 'overwrite').
                   14674:  
1.608     albertel 14675: 
                   14676: =item *
                   14677: 
                   14678: renameuserfile(): renames an existing userfile to a new name
                   14679: 
                   14680:   Args:
                   14681:    docuname: username or courseid of destination for the file
                   14682:    docudom: domain of user/course of destination for the file
                   14683:    old: current file name (including any subdirs under userfiles)
                   14684:    new: desired file name (including any subdirs under userfiles)
                   14685: 
                   14686: =item *
                   14687: 
                   14688: mkdiruserfile(): creates a directory is a userfiles dir
                   14689: 
                   14690:   Args:
                   14691:    docuname: username or courseid of destination for the file
                   14692:    docudom: domain of user/course of destination for the file
                   14693:    dir: dir to create (including any subdirs under userfiles)
                   14694: 
                   14695: =item *
                   14696: 
                   14697: removeuserfile(): removes a file that exists in userfiles
                   14698: 
                   14699:   Args:
                   14700:    docuname: username or courseid of destination for the file
                   14701:    docudom: domain of user/course of destination for the file
                   14702:    fname: filname to delete (including any subdirs under userfiles)
                   14703: 
                   14704: =item *
                   14705: 
                   14706: removeuploadedurl(): convience function for removeuserfile()
                   14707: 
                   14708:   Args:
                   14709:    url:  a full /uploaded/... url to delete
                   14710: 
1.747     albertel 14711: =item * 
                   14712: 
                   14713: get_portfile_permissions():
                   14714:   Args:
                   14715:     domain: domain of user or course contain the portfolio files
                   14716:     user: name of user or num of course contain the portfolio files
                   14717:   Returns:
                   14718:     hashref of a dump of the proper file_permissions.db
                   14719:    
                   14720: 
                   14721: =item * 
                   14722: 
                   14723: get_access_controls():
                   14724: 
                   14725: Args:
                   14726:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14727:   group: (optional) the group you want the files associated with
                   14728:   file: (optional) the file you want access info on
                   14729: 
                   14730: Returns:
1.749     raeburn  14731:     a hash (keys are file names) of hashes containing
                   14732:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14733:         values are XML containing access control settings (see below) 
1.747     albertel 14734: 
                   14735: Internal notes:
                   14736: 
1.749     raeburn  14737:  access controls are stored in file_permissions.db as key=value pairs.
                   14738:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14739:         where scope -> public,guest,course,group,domains or users.
                   14740:               end -> UNIX time for end of access (0 -> no end date)
                   14741:               start -> UNIX time for start of access
                   14742: 
                   14743:     value -> XML description of access control
                   14744:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14745:             <start></start>
                   14746:             <end></end>
                   14747: 
                   14748:             <password></password>  for scope type = guest
                   14749: 
                   14750:             <domain></domain>     for scope type = course or group
                   14751:             <number></number>
                   14752:             <roles id="">
                   14753:              <role></role>
                   14754:              <access></access>
                   14755:              <section></section>
                   14756:              <group></group>
                   14757:             </roles>
                   14758: 
                   14759:             <dom></dom>         for scope type = domains
                   14760: 
                   14761:             <users>             for scope type = users
                   14762:              <user>
                   14763:               <uname></uname>
                   14764:               <udom></udom>
                   14765:              </user>
                   14766:             </users>
                   14767:            </scope> 
                   14768:               
                   14769:  Access data is also aggregated for each file in an additional key=value pair:
                   14770:  key -> path to file/file_name\0accesscontrol 
                   14771:  value -> reference to hash
                   14772:           hash contains key = value pairs
                   14773:           where key = uniqueID:scope_end_start
                   14774:                 value = UNIX time record was last updated
                   14775: 
                   14776:           Used to improve speed of look-ups of access controls for each file.  
                   14777:  
                   14778:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14779: 
1.1198    raeburn  14780: =item *
                   14781: 
1.749     raeburn  14782: modify_access_controls():
                   14783: 
                   14784: Modifies access controls for a portfolio file
                   14785: Args
                   14786: 1. file name
                   14787: 2. reference to hash of required changes,
                   14788: 3. domain
                   14789: 4. username
                   14790:   where domain,username are the domain of the portfolio owner 
                   14791:   (either a user or a course) 
                   14792: 
                   14793: Returns:
                   14794: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14795: 2. result of deletions ('ok' or 'error', with error message).
                   14796: 3. reference to hash of any new or updated access controls.
                   14797: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14798:    key = integer (inbound ID)
1.1198    raeburn  14799:    value = uniqueID
                   14800: 
                   14801: =item *
                   14802: 
                   14803: get_timebased_id():
                   14804: 
                   14805: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   14806: course via the Course Editor (e.g., folders, composite pages, 
                   14807: group bulletin boards).
                   14808: 
                   14809: Args: (first three required; six others optional)
                   14810: 
                   14811: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14812:    docssequence, or name of group
                   14813: 
                   14814: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14815:    e.g., num, boardids
                   14816: 
                   14817: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   14818:    file will be named nohist_namespace.db
                   14819: 
                   14820: 4. cdom: domain of course; default is current course domain from %env
                   14821: 
                   14822: 5. cnum: course number; default is current course number from %env
                   14823: 
                   14824: 6. idtype: set to concat if an additional digit is to be appended to the 
                   14825:    unix timestamp to form the suffix, if the plain timestamp is already
                   14826:    in use.  Default is to not do this, but simply increment the unix 
                   14827:    timestamp by 1 until a unique key is obtained.
                   14828: 
                   14829: 7. who: holder of locking key; defaults to user:domain for user.
                   14830: 
                   14831: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   14832:    retrying); default is 3.
                   14833: 
                   14834: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   14835: 
                   14836: Returns:
                   14837: 
                   14838: 1. suffix obtained (numeric)
                   14839: 
                   14840: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14841: 
                   14842: 3. error: contains (localized) error message if an error occurred.
                   14843: 
1.747     albertel 14844: 
1.608     albertel 14845: =back
                   14846: 
1.243     albertel 14847: =head2 HTTP Helper Routines
                   14848: 
                   14849: =over 4
                   14850: 
1.191     harris41 14851: =item *
                   14852: 
                   14853: escape() : unpack non-word characters into CGI-compatible hex codes
                   14854: 
                   14855: =item *
                   14856: 
                   14857: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14858: 
1.243     albertel 14859: =back
                   14860: 
                   14861: =head1 PRIVATE SUBROUTINES
                   14862: 
                   14863: =head2 Underlying communication routines (Shouldn't call)
                   14864: 
                   14865: =over 4
                   14866: 
                   14867: =item *
                   14868: 
                   14869: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14870: 
                   14871: =item *
                   14872: 
                   14873: reply() : uses subreply to send a message to remote machine, logs all failures
                   14874: 
                   14875: =item *
                   14876: 
                   14877: critical() : passes a critical message to another server; if cannot
                   14878: get through then place message in connection buffer directory and
                   14879: returns con_delayed, if incapable of saving message, returns
                   14880: con_failed
                   14881: 
                   14882: =item *
                   14883: 
                   14884: reconlonc() : tries to reconnect lonc client processes.
                   14885: 
                   14886: =back
                   14887: 
                   14888: =head2 Resource Access Logging
                   14889: 
                   14890: =over 4
                   14891: 
                   14892: =item *
                   14893: 
                   14894: flushcourselogs() : flush (save) buffer logs and access logs
                   14895: 
                   14896: =item *
                   14897: 
                   14898: courselog($what) : save message for course in hash
                   14899: 
                   14900: =item *
                   14901: 
                   14902: courseacclog($what) : save message for course using &courselog().  Perform
                   14903: special processing for specific resource types (problems, exams, quizzes, etc).
                   14904: 
1.191     harris41 14905: =item *
                   14906: 
                   14907: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14908: as a PerlChildExitHandler
1.243     albertel 14909: 
                   14910: =back
                   14911: 
                   14912: =head2 Other
                   14913: 
                   14914: =over 4
                   14915: 
                   14916: =item *
                   14917: 
                   14918: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14919: 
                   14920: =back
                   14921: 
                   14922: =cut
1.877     foxr     14923: 

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