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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1266  ! raeburn     4: # $Id: lonnet.pm,v 1.1265 2014/07/29 05:49:32 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1182    foxr       78: 
1.1173    foxr       79: use Encode;
                     80: 
1.1245    raeburn    81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     83:             %managerstab);
1.871     albertel   84: 
                     85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        88:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        89: 
1.1       albertel   90: use IO::Socket;
1.31      www        91: use GDBM_File;
1.208     albertel   92: use HTML::LCParser;
1.88      www        93: use Fcntl qw(:flock);
1.870     albertel   94: use Storable qw(thaw nfreeze);
1.539     albertel   95: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   96: use Cache::Memcached;
1.676     albertel   97: use Digest::MD5;
1.790     albertel   98: use Math::Random;
1.1024    raeburn    99: use File::MMagic;
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1167    droeschl  103: use LONCAPA::Lond;
1.1117    foxr      104: 
1.1090    raeburn   105: use File::Copy;
1.676     albertel  106: 
1.195     www       107: my $readit;
1.550     foxr      108: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  109: 
1.619     albertel  110: require Exporter;
                    111: 
                    112: our @ISA = qw (Exporter);
                    113: our @EXPORT = qw(%env);
                    114: 
1.449     matthew   115: 
1.1187    raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1187    raeburn   119:     sub write_log {
1.1188    raeburn   120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1184    raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   130:         my $logentry = { 
                    131:                           $id => {
                    132:                                    'exe_uname' => $env{'user.name'},
                    133:                                    'exe_udom'  => $env{'user.domain'},
                    134:                                    'exe_time'  => $now,
                    135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    136:                                    'delflag'   => $delflag,
                    137:                                    'logentry'  => $storehash,
                    138:                                    'uname'     => $uname,
                    139:                                    'udom'      => $udom,
                    140:                                   }
                    141:                        };
                    142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       143:     }
                    144: }
1.1       albertel  145: 
1.163     harris41  146: sub logtouch {
                    147:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  148:     unless (-e "$execdir/logs/lonnet.log") {	
                    149: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  150: 	close $fh;
                    151:     }
                    152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    154: }
                    155: 
1.1       albertel  156: sub logthis {
                    157:     my $message=shift;
                    158:     my $execdir=$perlvar{'lonDaemons'};
                    159:     my $now=time;
                    160:     my $local=localtime($now);
1.448     albertel  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    163: 	print $fh $logstring;
1.448     albertel  164: 	close($fh);
                    165:     }
1.1       albertel  166:     return 1;
                    167: }
                    168: 
                    169: sub logperm {
                    170:     my $message=shift;
                    171:     my $execdir=$perlvar{'lonDaemons'};
                    172:     my $now=time;
                    173:     my $local=localtime($now);
1.448     albertel  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    175: 	print $fh "$now:$message:$local\n";
                    176: 	close($fh);
                    177:     }
1.1       albertel  178:     return 1;
                    179: }
                    180: 
1.850     albertel  181: sub create_connection {
1.853     albertel  182:     my ($hostname,$lonid) = @_;
1.851     albertel  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  184: 				     Type    => SOCK_STREAM,
                    185: 				     Timeout => 10);
                    186:     return 0 if (!$client);
1.890     albertel  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  188:     my $result = <$client>;
                    189:     chomp($result);
                    190:     return 1 if ($result eq 'done');
                    191:     return 0;
                    192: }
                    193: 
1.983     raeburn   194: sub get_server_timezone {
                    195:     my ($cnum,$cdom) = @_;
                    196:     my $home=&homeserver($cnum,$cdom);
                    197:     if ($home ne 'no_host') {
                    198:         my $cachetime = 24*3600;
                    199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    200:         if (defined($cached)) {
                    201:             return $timezone;
                    202:         } else {
                    203:             my $timezone = &reply('servertimezone',$home);
                    204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    205:         }
                    206:     }
                    207: }
1.850     albertel  208: 
1.1106    raeburn   209: sub get_server_distarch {
                    210:     my ($lonhost,$ignore_cache) = @_;
                    211:     if (defined($lonhost)) {
                    212:         if (!defined(&hostname($lonhost))) {
                    213:             return;
                    214:         }
                    215:         my $cachetime = 12*3600;
                    216:         if (!$ignore_cache) {
                    217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    218:             if (defined($cached)) {
                    219:                 return $distarch;
                    220:             }
                    221:         }
                    222:         my $rep = &reply('serverdistarch',$lonhost);
                    223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    225:                 $rep eq '') {
                    226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    227:         }
                    228:     }
                    229:     return;
                    230: }
                    231: 
1.993     raeburn   232: sub get_server_loncaparev {
1.1073    raeburn   233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   234:     if (defined($lonhost)) {
                    235:         if (!defined(&hostname($lonhost))) {
                    236:             undef($lonhost);
                    237:         }
                    238:     }
                    239:     if (!defined($lonhost)) {
                    240:         if (defined(&domain($dom,'primary'))) {
                    241:             $lonhost=&domain($dom,'primary');
                    242:             if ($lonhost eq 'no_host') {
                    243:                 undef($lonhost);
                    244:             }
                    245:         }
                    246:     }
                    247:     if (defined($lonhost)) {
1.1073    raeburn   248:         my $cachetime = 12*3600;
                    249:         if (!$ignore_cache) {
                    250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    251:             if (defined($cached)) {
                    252:                 return $loncaparev;
                    253:             }
                    254:         }
                    255:         my ($answer,$loncaparev);
                    256:         my @ids=&current_machine_ids();
                    257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    258:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   260:                 $loncaparev = $1;
                    261:             }
                    262:         } else {
                    263:             $answer = &reply('serverloncaparev',$lonhost);
                    264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    265:                 if ($caller eq 'loncron') {
                    266:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   267:                     $ua->timeout(4);
1.1073    raeburn   268:                     my $protocol = $protocol{$lonhost};
                    269:                     $protocol = 'http' if ($protocol ne 'https');
                    270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    271:                     my $request=new HTTP::Request('GET',$url);
                    272:                     my $response=$ua->request($request);
                    273:                     unless ($response->is_error()) {
                    274:                         my $content = $response->content;
1.1081    raeburn   275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   276:                             $loncaparev = $1;
                    277:                         }
                    278:                     }
                    279:                 } else {
                    280:                     $loncaparev = $loncaparevs{$lonhost};
                    281:                 }
1.1081    raeburn   282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   283:                 $loncaparev = $1;
                    284:             }
1.993     raeburn   285:         }
1.1073    raeburn   286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   287:     }
                    288: }
                    289: 
1.1074    raeburn   290: sub get_server_homeID {
                    291:     my ($hostname,$ignore_cache,$caller) = @_;
                    292:     unless ($ignore_cache) {
                    293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    294:         if (defined($cached)) {
                    295:             return $serverhomeID;
                    296:         }
                    297:     }
                    298:     my $cachetime = 12*3600;
                    299:     my $serverhomeID;
                    300:     if ($caller eq 'loncron') { 
                    301:         my @machine_ids = &machine_ids($hostname);
                    302:         foreach my $id (@machine_ids) {
                    303:             my $response = &reply('serverhomeID',$id);
                    304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    305:                 $serverhomeID = $response;
                    306:                 last;
                    307:             }
                    308:         }
                    309:         if ($serverhomeID eq '') {
                    310:             $serverhomeID = $machine_ids[-1];
                    311:         }
                    312:     } else {
                    313:         $serverhomeID = $serverhomeIDs{$hostname};
                    314:     }
                    315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    316: }
                    317: 
1.1121    raeburn   318: sub get_remote_globals {
                    319:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   320:     my ($result,%returnhash,%whatneeded);
                    321:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   322:         foreach my $what (sort(keys(%{$whathash}))) {
                    323:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   324:             my ($response,$cached);
1.1121    raeburn   325:             unless ($ignore_cache) {
1.1125    raeburn   326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   327:             }
                    328:             if (defined($cached)) {
1.1125    raeburn   329:                 $returnhash{$what} = $response;
1.1121    raeburn   330:             } else {
1.1125    raeburn   331:                 $whatneeded{$what} = 1;
1.1121    raeburn   332:             }
                    333:         }
1.1125    raeburn   334:         if (keys(%whatneeded) == 0) {
                    335:             $result = 'ok';
                    336:         } else {
1.1121    raeburn   337:             my $requested = &freeze_escape(\%whatneeded);
                    338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    340:                 ($rep eq 'unknown_cmd')) {
                    341:                 $result = $rep;
                    342:             } else {
                    343:                 $result = 'ok';
1.1121    raeburn   344:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   345:                 foreach my $item (@pairs) {
                    346:                     my ($key,$value)=split(/=/,$item,2);
                    347:                     my $what = &unescape($key);
                    348:                     my $hashid = $lonhost.'-'.$what;
                    349:                     $returnhash{$what}=&thaw_unescape($value);
                    350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   351:                 }
                    352:             }
                    353:         }
                    354:     }
1.1125    raeburn   355:     return ($result,\%returnhash);
1.1121    raeburn   356: }
                    357: 
1.1124    raeburn   358: sub remote_devalidate_cache {
1.1241    raeburn   359:     my ($lonhost,$cachekeys) = @_;
                    360:     my $items;
                    361:     return unless (ref($cachekeys) eq 'ARRAY');
                    362:     my $cachestr = join('&',@{$cachekeys});
                    363:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   364:     return $response;
                    365: }
                    366: 
1.1       albertel  367: # -------------------------------------------------- Non-critical communication
                    368: sub subreply {
                    369:     my ($cmd,$server)=@_;
1.838     albertel  370:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      371:     #
                    372:     #  With loncnew process trimming, there's a timing hole between lonc server
                    373:     #  process exit and the master server picking up the listen on the AF_UNIX
                    374:     #  socket.  In that time interval, a lock file will exist:
                    375: 
                    376:     my $lockfile=$peerfile.".lock";
                    377:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    378: 	sleep(1);
                    379:     }
                    380:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      381:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      382:     #
1.550     foxr      383:     #   We'll give the connection a few tries before abandoning it.  If
                    384:     #   connection is not possible, we'll con_lost back to the client.
                    385:     #   
                    386:     my $client;
                    387:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    388: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    389: 				      Type    => SOCK_STREAM,
                    390: 				      Timeout => 10);
1.869     albertel  391: 	if ($client) {
1.550     foxr      392: 	    last;		# Connected!
1.850     albertel  393: 	} else {
1.853     albertel  394: 	    &create_connection(&hostname($server),$server);
1.550     foxr      395: 	}
1.850     albertel  396:         sleep(1);		# Try again later if failed connection.
1.550     foxr      397:     }
                    398:     my $answer;
                    399:     if ($client) {
1.704     albertel  400: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      401: 	$answer=<$client>;
                    402: 	if (!$answer) { $answer="con_lost"; }
                    403: 	chomp($answer);
                    404:     } else {
                    405: 	$answer = 'con_lost';	# Failed connection.
                    406:     }
1.1       albertel  407:     return $answer;
                    408: }
                    409: 
                    410: sub reply {
                    411:     my ($cmd,$server)=@_;
1.838     albertel  412:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  413:     my $answer=subreply($cmd,$server);
1.65      www       414:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  415:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       416:                 " $cmd to $server returned $answer</font>");
                    417:     }
1.1       albertel  418:     return $answer;
                    419: }
                    420: 
                    421: # ----------------------------------------------------------- Send USR1 to lonc
                    422: 
                    423: sub reconlonc {
1.891     albertel  424:     my ($lonid) = @_;
                    425:     my $hostname = &hostname($lonid);
                    426:     if ($lonid) {
                    427: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    428: 	if ($hostname && -e $peerfile) {
                    429: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    430: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    431: 					     Type    => SOCK_STREAM,
                    432: 					     Timeout => 10);
                    433: 	    if ($client) {
                    434: 		print $client ("reset_retries\n");
                    435: 		my $answer=<$client>;
                    436: 		#reset just this one.
                    437: 	    }
                    438: 	}
                    439: 	return;
                    440:     }
                    441: 
1.836     www       442:     &logthis("Trying to reconnect lonc");
1.1       albertel  443:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  444:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  445: 	my $loncpid=<$fh>;
                    446:         chomp($loncpid);
                    447:         if (kill 0 => $loncpid) {
                    448: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    449:             kill USR1 => $loncpid;
                    450:             sleep 1;
1.836     www       451:          } else {
1.12      www       452: 	    &logthis(
1.672     albertel  453:                "<font color=\"blue\">WARNING:".
1.12      www       454:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  455:         }
                    456:     } else {
1.836     www       457: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  458:     }
                    459: }
                    460: 
                    461: # ------------------------------------------------------ Critical communication
1.12      www       462: 
1.1       albertel  463: sub critical {
                    464:     my ($cmd,$server)=@_;
1.838     albertel  465:     unless (&hostname($server)) {
1.672     albertel  466:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       467:                " Critical message to unknown server ($server)</font>");
                    468:         return 'no_such_host';
                    469:     }
1.1       albertel  470:     my $answer=reply($cmd,$server);
                    471:     if ($answer eq 'con_lost') {
                    472: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  473: 	my $answer=reply($cmd,$server);
1.1       albertel  474:         if ($answer eq 'con_lost') {
                    475:             my $now=time;
                    476:             my $middlename=$cmd;
1.5       www       477:             $middlename=substr($middlename,0,16);
1.1       albertel  478:             $middlename=~s/\W//g;
                    479:             my $dfilename=
1.305     www       480:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    481:             $dumpcount++;
1.1       albertel  482:             {
1.448     albertel  483: 		my $dfh;
                    484: 		if (open($dfh,">$dfilename")) {
                    485: 		    print $dfh "$cmd\n"; 
                    486: 		    close($dfh);
                    487: 		}
1.1       albertel  488:             }
                    489:             sleep 2;
                    490:             my $wcmd='';
                    491:             {
1.448     albertel  492: 		my $dfh;
                    493: 		if (open($dfh,"<$dfilename")) {
                    494: 		    $wcmd=<$dfh>; 
                    495: 		    close($dfh);
                    496: 		}
1.1       albertel  497:             }
                    498:             chomp($wcmd);
1.7       www       499:             if ($wcmd eq $cmd) {
1.672     albertel  500: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       501:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  502:                 &logperm("D:$server:$cmd");
                    503: 	        return 'con_delayed';
                    504:             } else {
1.672     albertel  505:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       506:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  507:                 &logperm("F:$server:$cmd");
                    508:                 return 'con_failed';
                    509:             }
                    510:         }
                    511:     }
                    512:     return $answer;
1.405     albertel  513: }
                    514: 
1.755     albertel  515: # ------------------------------------------- check if return value is an error
                    516: 
                    517: sub error {
                    518:     my ($result) = @_;
1.756     albertel  519:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  520: 	if ($2 == 2) { return undef; }
                    521: 	return $1;
                    522:     }
                    523:     return undef;
                    524: }
                    525: 
1.783     albertel  526: sub convert_and_load_session_env {
                    527:     my ($lonidsdir,$handle)=@_;
                    528:     my @profile;
                    529:     {
1.917     albertel  530: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    531: 	if (!$opened) {
1.915     albertel  532: 	    return 0;
                    533: 	}
1.783     albertel  534: 	flock($idf,LOCK_SH);
                    535: 	@profile=<$idf>;
                    536: 	close($idf);
                    537:     }
                    538:     my %temp_env;
                    539:     foreach my $line (@profile) {
1.786     albertel  540: 	if ($line !~ m/=/) {
                    541: 	    return 0;
                    542: 	}
1.783     albertel  543: 	chomp($line);
                    544: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    545: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    546:     }
                    547:     unlink("$lonidsdir/$handle.id");
                    548:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    549: 	    0640)) {
                    550: 	%disk_env = %temp_env;
                    551: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    552: 	untie(%disk_env);
                    553:     }
1.786     albertel  554:     return 1;
1.783     albertel  555: }
                    556: 
1.374     www       557: # ------------------------------------------- Transfer profile into environment
1.780     albertel  558: my $env_loaded;
                    559: sub transfer_profile_to_env {
1.788     albertel  560:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    561:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       562: 
1.720     albertel  563:     if (!defined($lonidsdir)) {
                    564: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    565:     }
                    566:     if (!defined($handle)) {
                    567:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    568:     }
                    569: 
1.786     albertel  570:     my $convert;
                    571:     {
1.917     albertel  572:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    573: 	if (!$opened) {
1.915     albertel  574: 	    return;
                    575: 	}
1.786     albertel  576: 	flock($idf,LOCK_SH);
                    577: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    578: 		&GDBM_READER(),0640)) {
                    579: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    580: 	    untie(%disk_env);
                    581: 	} else {
                    582: 	    $convert = 1;
                    583: 	}
                    584:     }
                    585:     if ($convert) {
                    586: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    587: 	    &logthis("Failed to load session, or convert session.");
                    588: 	}
1.374     www       589:     }
1.783     albertel  590: 
1.786     albertel  591:     my %remove;
1.783     albertel  592:     while ( my $envname = each(%env) ) {
1.433     matthew   593:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    594:             if ($time < time-300) {
1.783     albertel  595:                 $remove{$key}++;
1.433     matthew   596:             }
                    597:         }
                    598:     }
1.783     albertel  599: 
1.619     albertel  600:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  601:     $env_loaded=1;
1.783     albertel  602:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   603:         &delenv($expired_key);
1.374     www       604:     }
1.1       albertel  605: }
                    606: 
1.916     albertel  607: # ---------------------------------------------------- Check for valid session 
                    608: sub check_for_valid_session {
1.1245    raeburn   609:     my ($r,$name,$userhashref) = @_;
1.916     albertel  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   611:     if ($name eq '') {
                    612:         $name = 'lonID';
                    613:     }
                    614:     my $lonid=$cookies{$name};
1.916     albertel  615:     return undef if (!$lonid);
                    616: 
                    617:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   618:     my $lonidsdir;
                    619:     if ($name eq 'lonDAV') {
                    620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    621:     } else {
                    622:         $lonidsdir=$r->dir_config('lonIDsDir');
                    623:     }
1.916     albertel  624:     return undef if (!-e "$lonidsdir/$handle.id");
                    625: 
1.917     albertel  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    627:     return undef if (!$opened);
1.916     albertel  628: 
                    629:     flock($idf,LOCK_SH);
                    630:     my %disk_env;
                    631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    632: 	    &GDBM_READER(),0640)) {
                    633: 	return undef;	
                    634:     }
                    635: 
                    636:     if (!defined($disk_env{'user.name'})
                    637: 	|| !defined($disk_env{'user.domain'})) {
                    638: 	return undef;
                    639:     }
1.1245    raeburn   640: 
                    641:     if (ref($userhashref) eq 'HASH') {
                    642:         $userhashref->{'name'} = $disk_env{'user.name'};
                    643:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212    raeburn   644:     }
1.1245    raeburn   645: 
1.916     albertel  646:     return $handle;
                    647: }
                    648: 
1.830     albertel  649: sub timed_flock {
                    650:     my ($file,$lock_type) = @_;
                    651:     my $failed=0;
                    652:     eval {
                    653: 	local $SIG{__DIE__}='DEFAULT';
                    654: 	local $SIG{ALRM}=sub {
                    655: 	    $failed=1;
                    656: 	    die("failed lock");
                    657: 	};
                    658: 	alarm(13);
                    659: 	flock($file,$lock_type);
                    660: 	alarm(0);
                    661:     };
                    662:     if ($failed) {
                    663: 	return undef;
                    664:     } else {
                    665: 	return 1;
                    666:     }
                    667: }
                    668: 
1.5       www       669: # ---------------------------------------------------------- Append Environment
                    670: 
                    671: sub appenv {
1.949     raeburn   672:     my ($newenv,$roles) = @_;
                    673:     if (ref($newenv) eq 'HASH') {
                    674:         foreach my $key (keys(%{$newenv})) {
                    675:             my $refused = 0;
                    676: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    677:                 $refused = 1;
                    678:                 if (ref($roles) eq 'ARRAY') {
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'} }) {
                    852:                 if ($uint_dom) {
                    853:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    854:                                                  $try_server));
                    855:                 }
                    856: 	        ($spare_server, $lowest_load) =
                    857: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    858:             }
1.1083    raeburn   859:         }
1.784     albertel  860: 
1.1123    raeburn   861:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    862: 
                    863:         if (!$found_server) {
                    864:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    865: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    866:                     if ($uint_dom) {
                    867:                         next unless (&spare_can_host($udom,$uint_dom,
                    868:                                                      $remotesessions,$try_server));
                    869:                     }
                    870: 	            ($spare_server, $lowest_load) =
                    871: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    872:                 }
                    873: 	    }
                    874:         }
1.784     albertel  875:     }
                    876: 
                    877:     if (!$want_server_name) {
1.968     raeburn   878:         my $protocol = 'http';
                    879:         if ($protocol{$spare_server} eq 'https') {
                    880:             $protocol = $protocol{$spare_server};
                    881:         }
1.1001    raeburn   882:         if (defined($spare_server)) {
                    883:             my $hostname = &hostname($spare_server);
1.1083    raeburn   884:             if (defined($hostname)) {
1.1001    raeburn   885: 	        $spare_server = $protocol.'://'.$hostname;
                    886:             }
                    887:         }
1.784     albertel  888:     }
                    889:     return $spare_server;
                    890: }
                    891: 
                    892: sub compare_server_load {
1.1253    raeburn   893:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    894: 
                    895:     if ($required) {
                    896:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    897:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    898:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    899:         if (($major eq '' && $minor eq '') ||
                    900:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    901:             return ($spare_server,$lowest_load);
                    902:         }
                    903:     }
1.784     albertel  904: 
                    905:     my $loadans     = &reply('load',    $try_server);
                    906:     my $userloadans = &reply('userload',$try_server);
                    907: 
                    908:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   909: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  910:     }
                    911: 
                    912:     my $load;
                    913:     if ($loadans =~ /\d/) {
                    914: 	if ($userloadans =~ /\d/) {
                    915: 	    #both are numbers, pick the bigger one
                    916: 	    $load = ($loadans > $userloadans) ? $loadans 
                    917: 		                              : $userloadans;
1.411     albertel  918: 	} else {
1.784     albertel  919: 	    $load = $loadans;
1.411     albertel  920: 	}
1.784     albertel  921:     } else {
                    922: 	$load = $userloadans;
                    923:     }
                    924: 
                    925:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    926: 	$spare_server = $try_server;
                    927: 	$lowest_load  = $load;
1.370     albertel  928:     }
1.784     albertel  929:     return ($spare_server,$lowest_load);
1.202     matthew   930: }
1.914     albertel  931: 
                    932: # --------------------------- ask offload servers if user already has a session
                    933: sub find_existing_session {
                    934:     my ($udom,$uname) = @_;
1.1123    raeburn   935:     my $spareshash = &this_host_spares($udom);
                    936:     if (ref($spareshash) eq 'HASH') {
                    937:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    938:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    939:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    940:             }
                    941:         }
                    942:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    943:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    944:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    945:             }
                    946:         }
1.914     albertel  947:     }
                    948:     return;
                    949: }
                    950: 
                    951: # -------------------------------- ask if server already has a session for user
                    952: sub has_user_session {
                    953:     my ($lonid,$udom,$uname) = @_;
                    954:     my $result = &reply(join(':','userhassession',
                    955: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    956:     return 1 if ($result eq 'ok');
                    957: 
                    958:     return 0;
                    959: }
                    960: 
1.1076    raeburn   961: # --------- determine least loaded server in a user's domain which allows login
                    962: 
                    963: sub choose_server {
1.1259    raeburn   964:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   965:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   966:     my %servers = &get_servers($udom);
1.1076    raeburn   967:     my $lowest_load = 30000;
1.1259    raeburn   968:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    969:     if ($skiploadbal) {
                    970:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    971:         unless (defined($cached)) {
                    972:             my $cachetime = 60*60*24;
                    973:             my %domconfig =
                    974:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    975:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    976:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    977:                                            $cachetime);
                    978:             }
                    979:         }
                    980:     }
1.1076    raeburn   981:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn   982:         if ($skiploadbal) {
                    983:             if (ref($balancers) eq 'HASH') {
                    984:                 next if (exists($balancers->{$lonhost}));
                    985:             }
                    986:         }   
1.1115    raeburn   987:         my $loginvia;
                    988:         if ($checkloginvia) {
                    989:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   990:             if ($loginvia) {
                    991:                 my ($server,$path) = split(/:/,$loginvia);
                    992:                 ($login_host, $lowest_load) =
1.1253    raeburn   993:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   994:                 if ($login_host eq $server) {
                    995:                     $portal_path = $path;
1.1151    raeburn   996:                     $isredirect = 1;
1.1116    raeburn   997:                 }
                    998:             } else {
                    999:                 ($login_host, $lowest_load) =
1.1253    raeburn  1000:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1001:                 if ($login_host eq $lonhost) {
                   1002:                     $portal_path = '';
1.1151    raeburn  1003:                     $isredirect = ''; 
1.1116    raeburn  1004:                 }
                   1005:             }
                   1006:         } else {
1.1076    raeburn  1007:             ($login_host, $lowest_load) =
1.1253    raeburn  1008:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1009:         }
                   1010:     }
                   1011:     if ($login_host ne '') {
1.1116    raeburn  1012:         $hostname = &hostname($login_host);
1.1076    raeburn  1013:     }
1.1151    raeburn  1014:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn  1015: }
                   1016: 
1.202     matthew  1017: # --------------------------------------------- Try to change a user's password
                   1018: 
                   1019: sub changepass {
1.799     raeburn  1020:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1021:     $currentpass = &escape($currentpass);
                   1022:     $newpass     = &escape($newpass);
1.1030    raeburn  1023:     my $lonhost = $perlvar{'lonHostID'};
                   1024:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1025: 		       $server);
                   1026:     if (! $answer) {
                   1027: 	&logthis("No reply on password change request to $server ".
                   1028: 		 "by $uname in domain $udom.");
                   1029:     } elsif ($answer =~ "^ok") {
                   1030:         &logthis("$uname in $udom successfully changed their password ".
                   1031: 		 "on $server.");
                   1032:     } elsif ($answer =~ "^pwchange_failure") {
                   1033: 	&logthis("$uname in $udom was unable to change their password ".
                   1034: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1035: 		 "or pwchange");
                   1036:     } elsif ($answer =~ "^non_authorized") {
                   1037:         &logthis("$uname in $udom did not get their password correct when ".
                   1038: 		 "attempting to change it on $server.");
                   1039:     } elsif ($answer =~ "^auth_mode_error") {
                   1040:         &logthis("$uname in $udom attempted to change their password despite ".
                   1041: 		 "not being locally or internally authenticated on $server.");
                   1042:     } elsif ($answer =~ "^unknown_user") {
                   1043:         &logthis("$uname in $udom attempted to change their password ".
                   1044: 		 "on $server but were unable to because $server is not ".
                   1045: 		 "their home server.");
                   1046:     } elsif ($answer =~ "^refused") {
                   1047: 	&logthis("$server refused to change $uname in $udom password because ".
                   1048: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1049:     } elsif ($answer =~ "invalid_client") {
                   1050:         &logthis("$server refused to change $uname in $udom password because ".
                   1051:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1052:     }
                   1053:     return $answer;
1.1       albertel 1054: }
                   1055: 
1.169     harris41 1056: # ----------------------- Try to determine user's current authentication scheme
                   1057: 
                   1058: sub queryauthenticate {
                   1059:     my ($uname,$udom)=@_;
1.456     albertel 1060:     my $uhome=&homeserver($uname,$udom);
                   1061:     if (!$uhome) {
                   1062: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1063: 	return 'no_host';
                   1064:     }
                   1065:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1066:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1067: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1068:     }
1.456     albertel 1069:     return $answer;
1.169     harris41 1070: }
                   1071: 
1.1       albertel 1072: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1073: 
1.1       albertel 1074: sub authenticate {
1.1073    raeburn  1075:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1076:     $upass=&escape($upass);
                   1077:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1078:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1079:     my $newhome;
1.836     www      1080:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1081: # Maybe the machine was offline and only re-appeared again recently?
                   1082:         &reconlonc();
                   1083: # One more
1.952     raeburn  1084: 	$uhome=&homeserver($uname,$udom,1);
                   1085:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1086:             if (defined(&domain($udom,'primary'))) {
                   1087:                 $newhome=&domain($udom,'primary');
                   1088:             }
                   1089:             if ($newhome ne '') {
                   1090:                 $uhome = $newhome;
                   1091:             }
                   1092:         }
1.836     www      1093: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1094: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1095: 	    return 'no_host';
                   1096:         }
1.1       albertel 1097:     }
1.1073    raeburn  1098:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1099:     if ($answer eq 'authorized') {
1.952     raeburn  1100:         if ($newhome) {
                   1101:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1102:             return 'no_account_on_host'; 
                   1103:         } else {
                   1104:             &logthis("User $uname at $udom authorized by $uhome");
                   1105:             return $uhome;
                   1106:         }
1.471     albertel 1107:     }
                   1108:     if ($answer eq 'non_authorized') {
                   1109: 	&logthis("User $uname at $udom rejected by $uhome");
                   1110: 	return 'no_host'; 
1.9       www      1111:     }
1.471     albertel 1112:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1113:     return 'no_host';
                   1114: }
                   1115: 
1.1073    raeburn  1116: sub can_host_session {
1.1074    raeburn  1117:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1118:     my $canhost = 1;
1.1074    raeburn  1119:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1120:     if (ref($remotesessions) eq 'HASH') {
                   1121:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1122:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1123:                 $canhost = 0;
                   1124:             } else {
                   1125:                 $canhost = 1;
                   1126:             }
                   1127:         }
                   1128:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1129:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1130:                 $canhost = 1;
                   1131:             } else {
                   1132:                 $canhost = 0;
                   1133:             }
                   1134:         }
                   1135:         if ($canhost) {
                   1136:             if ($remotesessions->{'version'} ne '') {
                   1137:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1138:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1139:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1140:                         my $major = $1;
                   1141:                         my $minor = $2;
                   1142:                         if (($major < $reqmajor ) ||
                   1143:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1144:                             $canhost = 0;
                   1145:                         }
                   1146:                     } else {
                   1147:                         $canhost = 0;
                   1148:                     }
                   1149:                 }
                   1150:             }
                   1151:         }
                   1152:     }
                   1153:     if ($canhost) {
                   1154:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1155:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1156:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1157:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1158:                 if (($uint_dom ne '') && 
                   1159:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1160:                     $canhost = 0;
                   1161:                 } else {
                   1162:                     $canhost = 1;
                   1163:                 }
                   1164:             }
                   1165:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1166:                 if (($uint_dom ne '') && 
                   1167:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1168:                     $canhost = 1;
                   1169:                 } else {
                   1170:                     $canhost = 0;
                   1171:                 }
                   1172:             }
                   1173:         }
                   1174:     }
                   1175:     return $canhost;
                   1176: }
                   1177: 
1.1083    raeburn  1178: sub spare_can_host {
                   1179:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1180:     my $canhost=1;
                   1181:     my @intdoms;
                   1182:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1183:     if (ref($internet_names) eq 'ARRAY') {
                   1184:         @intdoms = @{$internet_names};
                   1185:     }
                   1186:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1187:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1188:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1189:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1190:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1191:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1192:                                      $remotesessions,
                   1193:                                      $defdomdefaults{'hostedsessions'});
                   1194:     }
                   1195:     return $canhost;
                   1196: }
                   1197: 
1.1123    raeburn  1198: sub this_host_spares {
                   1199:     my ($dom) = @_;
1.1126    raeburn  1200:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1201:     my @hosts = &current_machine_ids();
                   1202:     foreach my $lonhost (@hosts) {
                   1203:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1204:             $dom_in_use = $dom;
                   1205:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1206:             last;
                   1207:         }
                   1208:     }
1.1126    raeburn  1209:     if ($dom_in_use ne '') {
                   1210:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1211:     }
                   1212:     if (ref($result) ne 'HASH') {
                   1213:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1214:         $dom_in_use = &host_domain($lonhost_in_use);
                   1215:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1216:         if (ref($result) ne 'HASH') {
                   1217:             $result = \%spareid;
                   1218:         }
                   1219:     }
                   1220:     return $result;
                   1221: }
                   1222: 
                   1223: sub spares_for_offload  {
                   1224:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1225:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1226:     if (defined($cached)) {
                   1227:         return $result;
                   1228:     } else {
1.1126    raeburn  1229:         my $cachetime = 60*60*24;
                   1230:         my %domconfig =
                   1231:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1232:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1233:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1234:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1235:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1236:                 }
                   1237:             }
                   1238:         }
                   1239:     }
1.1126    raeburn  1240:     return;
1.1123    raeburn  1241: }
                   1242: 
1.1129    raeburn  1243: sub get_lonbalancer_config {
                   1244:     my ($servers) = @_;
                   1245:     my ($currbalancer,$currtargets);
                   1246:     if (ref($servers) eq 'HASH') {
                   1247:         foreach my $server (keys(%{$servers})) {
                   1248:             my %what = (
                   1249:                          spareid => 1,
                   1250:                          perlvar => 1,
                   1251:                        );
                   1252:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1253:             if ($result eq 'ok') {
                   1254:                 if (ref($returnhash) eq 'HASH') {
                   1255:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1256:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1257:                             $currbalancer = $server;
                   1258:                             $currtargets = {};
                   1259:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1260:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1261:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1262:                                 }
                   1263:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1264:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1265:                                 }
                   1266:                             }
                   1267:                             last;
                   1268:                         }
                   1269:                     }
                   1270:                 }
                   1271:             }
                   1272:         }
                   1273:     }
                   1274:     return ($currbalancer,$currtargets);
                   1275: }
                   1276: 
                   1277: sub check_loadbalancing {
                   1278:     my ($uname,$udom) = @_;
1.1191    raeburn  1279:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1280:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1281:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1282:     my @hosts = &current_machine_ids();
1.1129    raeburn  1283:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1284:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1285:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1286:     my $serverhomedom = &host_domain($lonhost);
                   1287: 
                   1288:     my $cachetime = 60*60*24;
                   1289: 
                   1290:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1291:         $dom_in_use = $udom;
                   1292:         $homeintdom = 1;
                   1293:     } else {
                   1294:         $dom_in_use = $serverhomedom;
                   1295:     }
                   1296:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1297:     unless (defined($cached)) {
                   1298:         my %domconfig =
                   1299:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1300:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1301:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1302:         }
                   1303:     }
                   1304:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1305:         ($is_balancer,$currtargets,$currrules) = 
                   1306:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1307:         if ($is_balancer) {
                   1308:             if (ref($currrules) eq 'HASH') {
                   1309:                 if ($homeintdom) {
                   1310:                     if ($uname ne '') {
                   1311:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1312:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1313:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1314:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1315:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1316:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1317:                             }
                   1318:                         }
                   1319:                         if ($rule_in_effect eq '') {
                   1320:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1321:                             if ($userenv{'inststatus'} ne '') {
                   1322:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1323:                                 my ($othertitle,$usertypes,$types) =
                   1324:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1325:                                 if (ref($types) eq 'ARRAY') {
                   1326:                                     foreach my $type (@{$types}) {
                   1327:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1328:                                             if (exists($currrules->{$type})) {
                   1329:                                                 $rule_in_effect = $currrules->{$type};
                   1330:                                             }
                   1331:                                         }
                   1332:                                     }
                   1333:                                 }
                   1334:                             } else {
                   1335:                                 if (exists($currrules->{'default'})) {
                   1336:                                     $rule_in_effect = $currrules->{'default'};
                   1337:                                 }
                   1338:                             }
                   1339:                         }
                   1340:                     } else {
                   1341:                         if (exists($currrules->{'default'})) {
                   1342:                             $rule_in_effect = $currrules->{'default'};
                   1343:                         }
                   1344:                     }
                   1345:                 } else {
                   1346:                     if ($currrules->{'_LC_external'} ne '') {
                   1347:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1348:                     }
                   1349:                 }
                   1350:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1351:                                                        $uname,$udom);
                   1352:             }
                   1353:         }
                   1354:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1355:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1356:         unless (defined($cached)) {
                   1357:             my %domconfig =
                   1358:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1359:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1360:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1361:             }
                   1362:         }
                   1363:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1364:             ($is_balancer,$currtargets,$currrules) = 
                   1365:                 &check_balancer_result($result,@hosts);
                   1366:             if ($is_balancer) {
1.1129    raeburn  1367:                 if (ref($currrules) eq 'HASH') {
                   1368:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1369:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1370:                     }
                   1371:                 }
                   1372:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1373:                                                        $uname,$udom);
                   1374:             }
                   1375:         } else {
                   1376:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1377:                 $is_balancer = 1;
                   1378:                 $offloadto = &this_host_spares($dom_in_use);
                   1379:             }
                   1380:         }
                   1381:     } else {
                   1382:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1383:             $is_balancer = 1;
                   1384:             $offloadto = &this_host_spares($dom_in_use);
                   1385:         }
                   1386:     }
1.1176    raeburn  1387:     if ($is_balancer) {
                   1388:         my $lowest_load = 30000;
                   1389:         if (ref($offloadto) eq 'HASH') {
                   1390:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1391:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1392:                     ($otherserver,$lowest_load) =
                   1393:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1394:                 }
1.1129    raeburn  1395:             }
1.1176    raeburn  1396:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1397: 
1.1176    raeburn  1398:             if (!$found_server) {
                   1399:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1400:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1401:                         ($otherserver,$lowest_load) =
                   1402:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1403:                     }
                   1404:                 }
                   1405:             }
                   1406:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1407:             if (@{$offloadto} == 1) {
                   1408:                 $otherserver = $offloadto->[0];
                   1409:             } elsif (@{$offloadto} > 1) {
                   1410:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1411:                     ($otherserver,$lowest_load) =
                   1412:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1413:                 }
                   1414:             }
                   1415:         }
1.1176    raeburn  1416:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1417:             $is_balancer = 0;
                   1418:             if ($uname ne '' && $udom ne '') {
                   1419:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1420:                     
                   1421:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1422:                              'user.loadbalcheck.time' => time});
                   1423:                 }
1.1129    raeburn  1424:             }
                   1425:         }
                   1426:     }
                   1427:     return ($is_balancer,$otherserver);
                   1428: }
                   1429: 
1.1191    raeburn  1430: sub check_balancer_result {
                   1431:     my ($result,@hosts) = @_;
                   1432:     my ($is_balancer,$currtargets,$currrules);
                   1433:     if (ref($result) eq 'HASH') {
                   1434:         if ($result->{'lonhost'} ne '') {
                   1435:             my $currbalancer = $result->{'lonhost'};
                   1436:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1437:                 $is_balancer = 1;
                   1438:                 $currtargets = $result->{'targets'};
                   1439:                 $currrules = $result->{'rules'};
                   1440:             }
                   1441:         } else {
                   1442:             foreach my $key (keys(%{$result})) {
                   1443:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1444:                     (ref($result->{$key}) eq 'HASH')) {
                   1445:                     $is_balancer = 1;
                   1446:                     $currrules = $result->{$key}{'rules'};
                   1447:                     $currtargets = $result->{$key}{'targets'};
                   1448:                     last;
                   1449:                 }
                   1450:             }
                   1451:         }
                   1452:     }
                   1453:     return ($is_balancer,$currtargets,$currrules);
                   1454: }
                   1455: 
1.1129    raeburn  1456: sub get_loadbalancer_targets {
                   1457:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1458:     my $offloadto;
1.1175    raeburn  1459:     if ($rule_in_effect eq 'none') {
                   1460:         return [$perlvar{'lonHostID'}];
                   1461:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1462:         $offloadto = $currtargets;
                   1463:     } else {
                   1464:         if ($rule_in_effect eq 'homeserver') {
                   1465:             my $homeserver = &homeserver($uname,$udom);
                   1466:             if ($homeserver ne 'no_host') {
                   1467:                 $offloadto = [$homeserver];
                   1468:             }
                   1469:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1470:             my %domconfig =
                   1471:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1472:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1473:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1474:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1475:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1476:                     }
                   1477:                 }
                   1478:             } else {
1.1178    raeburn  1479:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1480:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1481:                 if (&hostname($remotebalancer) ne '') {
                   1482:                     $offloadto = [$remotebalancer];
                   1483:                 }
                   1484:             }
                   1485:         } elsif (&hostname($rule_in_effect) ne '') {
                   1486:             $offloadto = [$rule_in_effect];
                   1487:         }
                   1488:     }
                   1489:     return $offloadto;
                   1490: }
                   1491: 
1.1127    raeburn  1492: sub internet_dom_servers {
                   1493:     my ($dom) = @_;
                   1494:     my (%uniqservers,%servers);
                   1495:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1496:     my @machinedoms = &machine_domains($primaryserver);
                   1497:     foreach my $mdom (@machinedoms) {
                   1498:         my %currservers = %servers;
                   1499:         my %server = &get_servers($mdom);
                   1500:         %servers = (%currservers,%server);
                   1501:     }
                   1502:     my %by_hostname;
                   1503:     foreach my $id (keys(%servers)) {
                   1504:         push(@{$by_hostname{$servers{$id}}},$id);
                   1505:     }
                   1506:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1507:         if (@{$by_hostname{$hostname}} > 1) {
                   1508:             my $match = 0;
                   1509:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1510:                 if (&host_domain($id) eq $dom) {
                   1511:                     $uniqservers{$id} = $hostname;
                   1512:                     $match = 1;
                   1513:                 }
                   1514:             }
                   1515:             unless ($match) {
                   1516:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1517:             }
                   1518:         } else {
                   1519:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1520:         }
                   1521:     }
                   1522:     return %uniqservers;
                   1523: }
                   1524: 
1.1       albertel 1525: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1526: 
1.599     albertel 1527: my %homecache;
1.1       albertel 1528: sub homeserver {
1.230     stredwic 1529:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1530:     my $index="$uname:$udom";
1.426     albertel 1531: 
1.599     albertel 1532:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1533: 
                   1534:     my %servers = &get_servers($udom,'library');
                   1535:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1536:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1537: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1538: 
                   1539: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1540: 	if ($answer eq 'found') {
                   1541: 	    delete($badServerCache{$tryserver}); 
                   1542: 	    return $homecache{$index}=$tryserver;
                   1543: 	} elsif ($answer eq 'no_host') {
                   1544: 	    $badServerCache{$tryserver}=1;
                   1545: 	}
1.1       albertel 1546:     }    
                   1547:     return 'no_host';
1.70      www      1548: }
                   1549: 
                   1550: # ------------------------------------- Find the usernames behind a list of IDs
                   1551: 
                   1552: sub idget {
                   1553:     my ($udom,@ids)=@_;
                   1554:     my %returnhash=();
                   1555:     
1.841     albertel 1556:     my %servers = &get_servers($udom,'library');
                   1557:     foreach my $tryserver (keys(%servers)) {
                   1558: 	my $idlist=join('&',@ids);
                   1559: 	$idlist=~tr/A-Z/a-z/; 
                   1560: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1561: 	my @answer=();
                   1562: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1563: 	    @answer=split(/\&/,$reply);
                   1564: 	}                    ;
                   1565: 	my $i;
                   1566: 	for ($i=0;$i<=$#ids;$i++) {
                   1567: 	    if ($answer[$i]) {
                   1568: 		$returnhash{$ids[$i]}=$answer[$i];
                   1569: 	    } 
                   1570: 	}
                   1571:     } 
1.70      www      1572:     return %returnhash;
                   1573: }
                   1574: 
                   1575: # ------------------------------------- Find the IDs behind a list of usernames
                   1576: 
                   1577: sub idrget {
                   1578:     my ($udom,@unames)=@_;
                   1579:     my %returnhash=();
1.800     albertel 1580:     foreach my $uname (@unames) {
                   1581:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1582:     }
1.70      www      1583:     return %returnhash;
                   1584: }
                   1585: 
                   1586: # ------------------------------- Store away a list of names and associated IDs
                   1587: 
                   1588: sub idput {
                   1589:     my ($udom,%ids)=@_;
                   1590:     my %servers=();
1.800     albertel 1591:     foreach my $uname (keys(%ids)) {
                   1592: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1593:         my $uhom=&homeserver($uname,$udom);
1.70      www      1594:         if ($uhom ne 'no_host') {
1.800     albertel 1595:             my $id=&escape($ids{$uname});
1.70      www      1596:             $id=~tr/A-Z/a-z/;
1.800     albertel 1597:             my $esc_unam=&escape($uname);
1.70      www      1598: 	    if ($servers{$uhom}) {
1.800     albertel 1599: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1600:             } else {
1.800     albertel 1601:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1602:             }
                   1603:         }
1.191     harris41 1604:     }
1.800     albertel 1605:     foreach my $server (keys(%servers)) {
                   1606:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1607:     }
1.344     www      1608: }
                   1609: 
1.1231    raeburn  1610: # ---------------------------------------- Delete unwanted IDs from ids.db file 
                   1611: 
                   1612: sub iddel {
                   1613:     my ($udom,$idshashref,$uhome)=@_;
                   1614:     my %result=();
                   1615:     unless (ref($idshashref) eq 'HASH') {
                   1616:         return %result;
                   1617:     }
                   1618:     my %servers=();
                   1619:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1620:         my $uhom;
                   1621:         if ($uhome) {
                   1622:             $uhom = $uhome;
                   1623:         } else {
                   1624:             $uhom=&homeserver($uname,$udom);
                   1625:         }
                   1626:         if ($uhom ne 'no_host') {
                   1627:             if ($servers{$uhom}) {
                   1628:                 $servers{$uhom}.='&'.&escape($id);
                   1629:             } else {
                   1630:                 $servers{$uhom}=&escape($id);
                   1631:             }
                   1632:         }
                   1633:     }
                   1634:     foreach my $server (keys(%servers)) {
                   1635:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1636:     }
                   1637:     return %result;
                   1638: }
                   1639: 
1.1023    raeburn  1640: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1641: sub dump_dom {
1.1165    droeschl 1642:     my ($namespace, $udom, $regexp) = @_;
                   1643: 
                   1644:     $udom ||= $env{'user.domain'};
                   1645: 
                   1646:     return () unless $udom;
                   1647: 
                   1648:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1649: }
                   1650: 
1.1023    raeburn  1651: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1652: 
                   1653: sub get_dom {
1.860     raeburn  1654:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1655:     my $items='';
                   1656:     foreach my $item (@$storearr) {
                   1657:         $items.=&escape($item).'&';
                   1658:     }
                   1659:     $items=~s/\&$//;
1.860     raeburn  1660:     if (!$udom) {
                   1661:         $udom=$env{'user.domain'};
                   1662:         if (defined(&domain($udom,'primary'))) {
                   1663:             $uhome=&domain($udom,'primary');
                   1664:         } else {
1.874     albertel 1665:             undef($uhome);
1.860     raeburn  1666:         }
                   1667:     } else {
                   1668:         if (!$uhome) {
                   1669:             if (defined(&domain($udom,'primary'))) {
                   1670:                 $uhome=&domain($udom,'primary');
                   1671:             }
                   1672:         }
                   1673:     }
                   1674:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1675:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1676:         my %returnhash;
1.875     albertel 1677:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1678:             return %returnhash;
                   1679:         }
1.806     raeburn  1680:         my @pairs=split(/\&/,$rep);
                   1681:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1682:             return @pairs;
                   1683:         }
                   1684:         my $i=0;
                   1685:         foreach my $item (@$storearr) {
                   1686:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1687:             $i++;
                   1688:         }
                   1689:         return %returnhash;
                   1690:     } else {
1.880     banghart 1691:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1692:     }
                   1693: }
                   1694: 
                   1695: # -------------------------------------------- put items in domain db files 
                   1696: 
                   1697: sub put_dom {
1.860     raeburn  1698:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1699:     if (!$udom) {
                   1700:         $udom=$env{'user.domain'};
                   1701:         if (defined(&domain($udom,'primary'))) {
                   1702:             $uhome=&domain($udom,'primary');
                   1703:         } else {
1.874     albertel 1704:             undef($uhome);
1.860     raeburn  1705:         }
                   1706:     } else {
                   1707:         if (!$uhome) {
                   1708:             if (defined(&domain($udom,'primary'))) {
                   1709:                 $uhome=&domain($udom,'primary');
                   1710:             }
                   1711:         }
                   1712:     } 
                   1713:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1714:         my $items='';
                   1715:         foreach my $item (keys(%$storehash)) {
                   1716:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1717:         }
                   1718:         $items=~s/\&$//;
                   1719:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1720:     } else {
1.860     raeburn  1721:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1722:     }
                   1723: }
                   1724: 
1.1023    raeburn  1725: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1726: sub newput_dom {
1.1023    raeburn  1727:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1728:     my $result;
                   1729:     if (!$udom) {
                   1730:         $udom=$env{'user.domain'};
                   1731:     }
1.1023    raeburn  1732:     if ($udom) {
                   1733:         my $uname = &get_domainconfiguser($udom);
                   1734:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1735:     }
                   1736:     return $result;
                   1737: }
                   1738: 
1.1023    raeburn  1739: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1740: sub del_dom {
1.1023    raeburn  1741:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1742:     if (ref($storearr) eq 'ARRAY') {
                   1743:         if (!$udom) {
                   1744:             $udom=$env{'user.domain'};
                   1745:         }
1.1023    raeburn  1746:         if ($udom) {
                   1747:             my $uname = &get_domainconfiguser($udom); 
                   1748:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1749:         }
                   1750:     }
                   1751: }
                   1752: 
1.1023    raeburn  1753: # ----------------------------------construct domainconfig user for a domain 
                   1754: sub get_domainconfiguser {
                   1755:     my ($udom) = @_;
                   1756:     return $udom.'-domainconfig';
                   1757: }
                   1758: 
1.837     raeburn  1759: sub retrieve_inst_usertypes {
                   1760:     my ($udom) = @_;
                   1761:     my (%returnhash,@order);
1.989     raeburn  1762:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1763:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1764:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  1765:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1766:     } else {
                   1767:         if (defined(&domain($udom,'primary'))) {
                   1768:             my $uhome=&domain($udom,'primary');
                   1769:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1770:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  1771:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1772:                 return (\%returnhash,\@order);
                   1773:             }
                   1774:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1775:             my @pairs=split(/\&/,$hashitems);
                   1776:             foreach my $item (@pairs) {
                   1777:                 my ($key,$value)=split(/=/,$item,2);
                   1778:                 $key = &unescape($key);
                   1779:                 next if ($key =~ /^error: 2 /);
                   1780:                 $returnhash{$key}=&thaw_unescape($value);
                   1781:             }
                   1782:             my @esc_order = split(/\&/,$orderitems);
                   1783:             foreach my $item (@esc_order) {
                   1784:                 push(@order,&unescape($item));
                   1785:             }
                   1786:         } else {
1.1256    raeburn  1787:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1788:         }
1.1256    raeburn  1789:         return (\%returnhash,\@order);
1.837     raeburn  1790:     }
                   1791: }
                   1792: 
1.868     raeburn  1793: sub is_domainimage {
                   1794:     my ($url) = @_;
                   1795:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1796:         if (&domain($1) ne '') {
                   1797:             return '1';
                   1798:         }
                   1799:     }
                   1800:     return;
                   1801: }
                   1802: 
1.899     raeburn  1803: sub inst_directory_query {
                   1804:     my ($srch) = @_;
                   1805:     my $udom = $srch->{'srchdomain'};
                   1806:     my %results;
                   1807:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1808:     my $outcome;
1.899     raeburn  1809:     if ($homeserver ne '') {
1.904     albertel 1810: 	my $queryid=&reply("querysend:instdirsearch:".
                   1811: 			   &escape($srch->{'srchby'}).':'.
                   1812: 			   &escape($srch->{'srchterm'}).':'.
                   1813: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1814: 	my $host=&hostname($homeserver);
                   1815: 	if ($queryid !~/^\Q$host\E\_/) {
                   1816: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1817: 	    return;
                   1818: 	}
                   1819: 	my $response = &get_query_reply($queryid);
                   1820: 	my $maxtries = 5;
                   1821: 	my $tries = 1;
                   1822: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1823: 	    $response = &get_query_reply($queryid);
                   1824: 	    $tries ++;
                   1825: 	}
                   1826: 
                   1827:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1828:             if ($response eq 'unavailable') {
                   1829:                 $outcome = $response;
                   1830:             } else {
                   1831:                 $outcome = 'ok';
                   1832:                 my @matches = split(/\n/,$response);
                   1833:                 foreach my $match (@matches) {
                   1834:                     my ($key,$value) = split(/=/,$match);
                   1835:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1836:                 }
1.899     raeburn  1837:             }
                   1838:         }
                   1839:     }
1.909     raeburn  1840:     return ($outcome,%results);
1.899     raeburn  1841: }
                   1842: 
                   1843: sub usersearch {
                   1844:     my ($srch) = @_;
                   1845:     my $dom = $srch->{'srchdomain'};
                   1846:     my %results;
                   1847:     my %libserv = &all_library();
                   1848:     my $query = 'usersearch';
                   1849:     foreach my $tryserver (keys(%libserv)) {
                   1850:         if (&host_domain($tryserver) eq $dom) {
                   1851:             my $host=&hostname($tryserver);
                   1852:             my $queryid=
1.911     raeburn  1853:                 &reply("querysend:".&escape($query).':'.
                   1854:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1855:                        &escape($srch->{'srchtype'}).':'.
                   1856:                        &escape($srch->{'srchterm'}),$tryserver);
                   1857:             if ($queryid !~/^\Q$host\E\_/) {
                   1858:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1859:                 next;
1.899     raeburn  1860:             }
                   1861:             my $reply = &get_query_reply($queryid);
                   1862:             my $maxtries = 1;
                   1863:             my $tries = 1;
                   1864:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1865:                 $reply = &get_query_reply($queryid);
                   1866:                 $tries ++;
                   1867:             }
                   1868:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1869:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1870:             } else {
1.911     raeburn  1871:                 my @matches;
                   1872:                 if ($reply =~ /\n/) {
                   1873:                     @matches = split(/\n/,$reply);
                   1874:                 } else {
                   1875:                     @matches = split(/\&/,$reply);
                   1876:                 }
1.899     raeburn  1877:                 foreach my $match (@matches) {
                   1878:                     my ($uname,$udom,%userhash);
1.911     raeburn  1879:                     foreach my $entry (split(/:/,$match)) {
                   1880:                         my ($key,$value) =
                   1881:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1882:                         $userhash{$key} = $value;
                   1883:                         if ($key eq 'username') {
                   1884:                             $uname = $value;
                   1885:                         } elsif ($key eq 'domain') {
                   1886:                             $udom = $value;
1.911     raeburn  1887:                         }
1.899     raeburn  1888:                     }
                   1889:                     $results{$uname.':'.$udom} = \%userhash;
                   1890:                 }
                   1891:             }
                   1892:         }
                   1893:     }
                   1894:     return %results;
                   1895: }
                   1896: 
1.912     raeburn  1897: sub get_instuser {
                   1898:     my ($udom,$uname,$id) = @_;
                   1899:     my $homeserver = &domain($udom,'primary');
                   1900:     my ($outcome,%results);
                   1901:     if ($homeserver ne '') {
                   1902:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1903:                            &escape($id).':'.&escape($udom),$homeserver);
                   1904:         my $host=&hostname($homeserver);
                   1905:         if ($queryid !~/^\Q$host\E\_/) {
                   1906:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1907:             return;
                   1908:         }
                   1909:         my $response = &get_query_reply($queryid);
                   1910:         my $maxtries = 5;
                   1911:         my $tries = 1;
                   1912:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1913:             $response = &get_query_reply($queryid);
                   1914:             $tries ++;
                   1915:         }
                   1916:         if (!&error($response) && $response ne 'refused') {
                   1917:             if ($response eq 'unavailable') {
                   1918:                 $outcome = $response;
                   1919:             } else {
                   1920:                 $outcome = 'ok';
                   1921:                 my @matches = split(/\n/,$response);
                   1922:                 foreach my $match (@matches) {
                   1923:                     my ($key,$value) = split(/=/,$match);
                   1924:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1925:                 }
                   1926:             }
                   1927:         }
                   1928:     }
                   1929:     my %userinfo;
                   1930:     if (ref($results{$uname}) eq 'HASH') {
                   1931:         %userinfo = %{$results{$uname}};
                   1932:     } 
                   1933:     return ($outcome,%userinfo);
                   1934: }
                   1935: 
                   1936: sub inst_rulecheck {
1.923     raeburn  1937:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1938:     my %returnhash;
                   1939:     if ($udom ne '') {
                   1940:         if (ref($rules) eq 'ARRAY') {
                   1941:             @{$rules} = map {&escape($_);} (@{$rules});
                   1942:             my $rulestr = join(':',@{$rules});
                   1943:             my $homeserver=&domain($udom,'primary');
                   1944:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1945:                 my $response;
                   1946:                 if ($item eq 'username') {                
                   1947:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1948:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1949:                                               $homeserver));
1.923     raeburn  1950:                 } elsif ($item eq 'id') {
                   1951:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1952:                                               ':'.&escape($id).':'.$rulestr,
                   1953:                                               $homeserver));
1.945     raeburn  1954:                 } elsif ($item eq 'selfcreate') {
                   1955:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1956:                                                &escape($udom).':'.&escape($uname).
                   1957:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1958:                 }
1.912     raeburn  1959:                 if ($response ne 'refused') {
                   1960:                     my @pairs=split(/\&/,$response);
                   1961:                     foreach my $item (@pairs) {
                   1962:                         my ($key,$value)=split(/=/,$item,2);
                   1963:                         $key = &unescape($key);
                   1964:                         next if ($key =~ /^error: 2 /);
                   1965:                         $returnhash{$key}=&thaw_unescape($value);
                   1966:                     }
                   1967:                 }
                   1968:             }
                   1969:         }
                   1970:     }
                   1971:     return %returnhash;
                   1972: }
                   1973: 
                   1974: sub inst_userrules {
1.923     raeburn  1975:     my ($udom,$check) = @_;
1.912     raeburn  1976:     my (%ruleshash,@ruleorder);
                   1977:     if ($udom ne '') {
                   1978:         my $homeserver=&domain($udom,'primary');
                   1979:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1980:             my $response;
                   1981:             if ($check eq 'id') {
                   1982:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1983:                                  $homeserver);
1.943     raeburn  1984:             } elsif ($check eq 'email') {
                   1985:                 $response=&reply('instemailrules:'.&escape($udom),
                   1986:                                  $homeserver);
1.923     raeburn  1987:             } else {
                   1988:                 $response=&reply('instuserrules:'.&escape($udom),
                   1989:                                  $homeserver);
                   1990:             }
1.912     raeburn  1991:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1992:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1993:                 ($response ne 'no_such_host')) {
                   1994:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1995:                 my @pairs=split(/\&/,$hashitems);
                   1996:                 foreach my $item (@pairs) {
                   1997:                     my ($key,$value)=split(/=/,$item,2);
                   1998:                     $key = &unescape($key);
                   1999:                     next if ($key =~ /^error: 2 /);
                   2000:                     $ruleshash{$key}=&thaw_unescape($value);
                   2001:                 }
                   2002:                 my @esc_order = split(/\&/,$orderitems);
                   2003:                 foreach my $item (@esc_order) {
                   2004:                     push(@ruleorder,&unescape($item));
                   2005:                 }
                   2006:             }
                   2007:         }
                   2008:     }
                   2009:     return (\%ruleshash,\@ruleorder);
                   2010: }
                   2011: 
1.976     raeburn  2012: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2013: 
                   2014: sub get_domain_defaults {
1.1240    raeburn  2015:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2016:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2017:     my $cachetime = 60*60*24;
1.1240    raeburn  2018:     unless ($ignore_cache) {
                   2019:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2020:         if (defined($cached)) {
                   2021:             if (ref($result) eq 'HASH') {
                   2022:                 return %{$result};
                   2023:             }
1.943     raeburn  2024:         }
                   2025:     }
                   2026:     my %domdefaults;
                   2027:     my %domconfig =
1.989     raeburn  2028:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2029:                                   'requestcourses','inststatus',
1.1183    raeburn  2030:                                   'coursedefaults','usersessions',
1.1258    raeburn  2031:                                   'requestauthor','selfenrollment',
                   2032:                                   'coursecategories'],$domain);
1.1254    raeburn  2033:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2034:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2035:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2036:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2037:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2038:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2039:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2040:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2041:     } else {
                   2042:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2043:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2044:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2045:     }
1.976     raeburn  2046:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2047:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2048:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2049:         } else {
                   2050:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2051:         }
1.1177    raeburn  2052:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2053:         foreach my $item (@usertools) {
                   2054:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2055:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2056:             }
                   2057:         }
1.1229    raeburn  2058:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2059:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2060:         }
1.976     raeburn  2061:     }
1.985     raeburn  2062:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246    raeburn  2063:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2064:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2065:         }
                   2066:     }
1.1183    raeburn  2067:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2068:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2069:     }
1.989     raeburn  2070:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2071:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2072:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2073:         }
                   2074:     }
1.1047    raeburn  2075:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2076:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1254    raeburn  2077:         foreach my $type (@coursetypes) {
                   2078:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2079:                 unless ($type eq 'community') {
                   2080:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2081:                 }
                   2082:             }
                   2083:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2084:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2085:             }
1.1230    raeburn  2086:         }
1.1047    raeburn  2087:     }
1.1073    raeburn  2088:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2089:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2090:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2091:         }
                   2092:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2093:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2094:         }
                   2095:     }
1.1254    raeburn  2096:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2097:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2098:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2099:                             'approval','limit');
                   2100:             foreach my $type (@coursetypes) {
                   2101:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2102:                     my @mgrdc = ();
                   2103:                     foreach my $item (@settings) {
                   2104:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2105:                             push(@mgrdc,$item);
                   2106:                         }
                   2107:                     }
                   2108:                     if (@mgrdc) {
                   2109:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2110:                     }
                   2111:                 }
                   2112:             }
                   2113:         }
                   2114:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2115:             foreach my $type (@coursetypes) {
                   2116:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2117:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2118:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2119:                     }
                   2120:                 }
                   2121:             }
                   2122:         }
                   2123:     }
1.1258    raeburn  2124:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2125:         $domdefaults{'catauth'} = 'std';
                   2126:         $domdefaults{'catunauth'} = 'std';
                   2127:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2128:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2129:         }
                   2130:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2131:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2132:         }
                   2133:     }
1.1219    raeburn  2134:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2135:     return %domdefaults;
                   2136: }
                   2137: 
1.344     www      2138: # --------------------------------------------------- Assign a key to a student
                   2139: 
                   2140: sub assign_access_key {
1.364     www      2141: #
                   2142: # a valid key looks like uname:udom#comments
                   2143: # comments are being appended
                   2144: #
1.498     www      2145:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2146:     $kdom=
1.620     albertel 2147:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2148:     $knum=
1.620     albertel 2149:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2150:     $cdom=
1.620     albertel 2151:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2152:     $cnum=
1.620     albertel 2153:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2154:     $udom=$env{'user.name'} unless (defined($udom));
                   2155:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2156:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2157:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2158:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2159:                                                   # assigned to this person
                   2160:                                                   # - this should not happen,
1.345     www      2161:                                                   # unless something went wrong
                   2162:                                                   # the first time around
                   2163: # ready to assign
1.364     www      2164:         $logentry=$1.'; '.$logentry;
1.496     www      2165:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2166:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2167: # key now belongs to user
1.346     www      2168: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2169:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2170:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2171:                 return 'ok';
                   2172:             } else {
                   2173:                 return 
                   2174:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2175: 	    }
                   2176:         } else {
                   2177:             return 'error: Could not assign key, try again later.';
                   2178:         }
1.364     www      2179:     } elsif (!$existing{$ckey}) {
1.345     www      2180: # the key does not exist
                   2181: 	return 'error: The key does not exist';
                   2182:     } else {
                   2183: # the key is somebody else's
                   2184: 	return 'error: The key is already in use';
                   2185:     }
1.344     www      2186: }
                   2187: 
1.364     www      2188: # ------------------------------------------ put an additional comment on a key
                   2189: 
                   2190: sub comment_access_key {
                   2191: #
                   2192: # a valid key looks like uname:udom#comments
                   2193: # comments are being appended
                   2194: #
                   2195:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2196:     $cdom=
1.620     albertel 2197:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2198:     $cnum=
1.620     albertel 2199:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2200:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2201:     if ($existing{$ckey}) {
                   2202:         $existing{$ckey}.='; '.$logentry;
                   2203: # ready to assign
1.367     www      2204:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2205:                                                  $cdom,$cnum) eq 'ok') {
                   2206: 	    return 'ok';
                   2207:         } else {
                   2208: 	    return 'error: Count not store comment.';
                   2209:         }
                   2210:     } else {
                   2211: # the key does not exist
                   2212: 	return 'error: The key does not exist';
                   2213:     }
                   2214: }
                   2215: 
1.344     www      2216: # ------------------------------------------------------ Generate a set of keys
                   2217: 
                   2218: sub generate_access_keys {
1.364     www      2219:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2220:     $cdom=
1.620     albertel 2221:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2222:     $cnum=
1.620     albertel 2223:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2224:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2225:     unless (($cdom) && ($cnum)) { return 0; }
                   2226:     if ($number>10000) { return 0; }
                   2227:     sleep(2); # make sure don't get same seed twice
                   2228:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2229:     my $total=0;
                   2230:     for (my $i=1;$i<=$number;$i++) {
                   2231:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2232:                   sprintf("%lx",int(100000*rand)).'-'.
                   2233:                   sprintf("%lx",int(100000*rand));
                   2234:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2235:        $newkey=~s/0/h/g; # and also 0 and O
                   2236:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2237:        if ($existing{$newkey}) {
                   2238:            $i--;
                   2239:        } else {
1.364     www      2240: 	  if (&put('accesskeys',
                   2241:               { $newkey => '# generated '.localtime().
1.620     albertel 2242:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2243:                            '; '.$logentry },
                   2244: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2245:               $total++;
                   2246: 	  }
                   2247:        }
                   2248:     }
1.620     albertel 2249:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2250:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2251:     return $total;
                   2252: }
                   2253: 
                   2254: # ------------------------------------------------------- Validate an accesskey
                   2255: 
                   2256: sub validate_access_key {
                   2257:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2258:     $cdom=
1.620     albertel 2259:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2260:     $cnum=
1.620     albertel 2261:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2262:     $udom=$env{'user.domain'} unless (defined($udom));
                   2263:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2264:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2265:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2266: }
                   2267: 
                   2268: # ------------------------------------- Find the section of student in a course
1.652     albertel 2269: sub devalidate_getsection_cache {
                   2270:     my ($udom,$unam,$courseid)=@_;
                   2271:     my $hashid="$udom:$unam:$courseid";
                   2272:     &devalidate_cache_new('getsection',$hashid);
                   2273: }
1.298     matthew  2274: 
1.815     albertel 2275: sub courseid_to_courseurl {
                   2276:     my ($courseid) = @_;
                   2277:     #already url style courseid
                   2278:     return $courseid if ($courseid =~ m{^/});
                   2279: 
                   2280:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2281: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2282: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2283: 	return "/$cdom/$cnum";
                   2284:     }
                   2285: 
                   2286:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2287:     if (exists($courseinfo{'num'})) {
                   2288: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2289:     }
                   2290: 
                   2291:     return undef;
                   2292: }
                   2293: 
1.298     matthew  2294: sub getsection {
                   2295:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2296:     my $cachetime=1800;
1.551     albertel 2297: 
                   2298:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2299:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2300:     if (defined($cached)) { return $result; }
                   2301: 
1.298     matthew  2302:     my %Pending; 
                   2303:     my %Expired;
                   2304:     #
                   2305:     # Each role can either have not started yet (pending), be active, 
                   2306:     #    or have expired.
                   2307:     #
                   2308:     # If there is an active role, we are done.
                   2309:     #
                   2310:     # If there is more than one role which has not started yet, 
                   2311:     #     choose the one which will start sooner
                   2312:     # If there is one role which has not started yet, return it.
                   2313:     #
                   2314:     # If there is more than one expired role, choose the one which ended last.
                   2315:     # If there is a role which has expired, return it.
                   2316:     #
1.815     albertel 2317:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2318:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2319:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2320:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2321:         my $section=$1;
                   2322:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2323:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2324:         my $now=time;
1.548     albertel 2325:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2326:             $Expired{$end}=$section;
                   2327:             next;
                   2328:         }
1.548     albertel 2329:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2330:             $Pending{$start}=$section;
                   2331:             next;
                   2332:         }
1.599     albertel 2333:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2334:     }
                   2335:     #
                   2336:     # Presumedly there will be few matching roles from the above
                   2337:     # loop and the sorting time will be negligible.
                   2338:     if (scalar(keys(%Pending))) {
                   2339:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2340:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2341:     } 
                   2342:     if (scalar(keys(%Expired))) {
                   2343:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2344:         my $time = pop(@sorted);
1.599     albertel 2345:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2346:     }
1.599     albertel 2347:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2348: }
1.70      www      2349: 
1.599     albertel 2350: sub save_cache {
                   2351:     &purge_remembered();
1.722     albertel 2352:     #&Apache::loncommon::validate_page();
1.620     albertel 2353:     undef(%env);
1.780     albertel 2354:     undef($env_loaded);
1.599     albertel 2355: }
1.452     albertel 2356: 
1.599     albertel 2357: my $to_remember=-1;
                   2358: my %remembered;
                   2359: my %accessed;
                   2360: my $kicks=0;
                   2361: my $hits=0;
1.849     albertel 2362: sub make_key {
                   2363:     my ($name,$id) = @_;
1.872     albertel 2364:     if (length($id) > 65 
                   2365: 	&& length(&escape($id)) > 200) {
                   2366: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2367:     }
1.849     albertel 2368:     return &escape($name.':'.$id);
                   2369: }
                   2370: 
1.599     albertel 2371: sub devalidate_cache_new {
                   2372:     my ($name,$id,$debug) = @_;
                   2373:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2374:     $id=&make_key($name,$id);
1.599     albertel 2375:     $memcache->delete($id);
                   2376:     delete($remembered{$id});
                   2377:     delete($accessed{$id});
                   2378: }
                   2379: 
                   2380: sub is_cached_new {
                   2381:     my ($name,$id,$debug) = @_;
1.849     albertel 2382:     $id=&make_key($name,$id);
1.599     albertel 2383:     if (exists($remembered{$id})) {
1.1133    foxr     2384: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2385: 	$accessed{$id}=[&gettimeofday()];
                   2386: 	$hits++;
                   2387: 	return ($remembered{$id},1);
                   2388:     }
                   2389:     my $value = $memcache->get($id);
                   2390:     if (!(defined($value))) {
                   2391: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2392: 	return (undef,undef);
1.416     albertel 2393:     }
1.599     albertel 2394:     if ($value eq '__undef__') {
                   2395: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2396: 	$value=undef;
                   2397:     }
                   2398:     &make_room($id,$value,$debug);
                   2399:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2400:     return ($value,1);
                   2401: }
                   2402: 
                   2403: sub do_cache_new {
                   2404:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2405:     $id=&make_key($name,$id);
1.599     albertel 2406:     my $setvalue=$value;
                   2407:     if (!defined($setvalue)) {
                   2408: 	$setvalue='__undef__';
                   2409:     }
1.623     albertel 2410:     if (!defined($time) ) {
                   2411: 	$time=600;
                   2412:     }
1.599     albertel 2413:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2414:     my $result = $memcache->set($id,$setvalue,$time);
                   2415:     if (! $result) {
1.872     albertel 2416: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2417: 	$memcache->disconnect_all();
1.872     albertel 2418:     }
1.600     albertel 2419:     # need to make a copy of $value
1.919     albertel 2420:     &make_room($id,$value,$debug);
1.599     albertel 2421:     return $value;
                   2422: }
                   2423: 
                   2424: sub make_room {
                   2425:     my ($id,$value,$debug)=@_;
1.919     albertel 2426: 
                   2427:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2428:                                     : $value;
1.599     albertel 2429:     if ($to_remember<0) { return; }
                   2430:     $accessed{$id}=[&gettimeofday()];
                   2431:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2432:     my $to_kick;
                   2433:     my $max_time=0;
                   2434:     foreach my $other (keys(%accessed)) {
                   2435: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2436: 	    $to_kick=$other;
                   2437: 	    $max_time=&tv_interval($accessed{$other});
                   2438: 	}
                   2439:     }
                   2440:     delete($remembered{$to_kick});
                   2441:     delete($accessed{$to_kick});
                   2442:     $kicks++;
                   2443:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2444:     return;
                   2445: }
                   2446: 
1.599     albertel 2447: sub purge_remembered {
1.604     albertel 2448:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2449:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2450:     undef(%remembered);
                   2451:     undef(%accessed);
1.428     albertel 2452: }
1.70      www      2453: # ------------------------------------- Read an entry from a user's environment
                   2454: 
                   2455: sub userenvironment {
                   2456:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2457:     my $items;
                   2458:     foreach my $item (@what) {
                   2459:         $items.=&escape($item).'&';
                   2460:     }
                   2461:     $items=~s/\&$//;
1.70      www      2462:     my %returnhash=();
1.1009    raeburn  2463:     my $uhome = &homeserver($unam,$udom);
                   2464:     unless ($uhome eq 'no_host') {
                   2465:         my @answer=split(/\&/, 
                   2466:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2467:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2468:             return %returnhash;
                   2469:         }
1.1009    raeburn  2470:         my $i;
                   2471:         for ($i=0;$i<=$#what;$i++) {
                   2472: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2473:         }
1.70      www      2474:     }
                   2475:     return %returnhash;
1.1       albertel 2476: }
                   2477: 
1.617     albertel 2478: # ---------------------------------------------------------- Get a studentphoto
                   2479: sub studentphoto {
                   2480:     my ($udom,$unam,$ext) = @_;
                   2481:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2482:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2483:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2484:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2485:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2486:             } else {
                   2487:                 my ($result,$perm_reqd)=
1.707     albertel 2488: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2489:                 if ($result eq 'ok') {
                   2490:                     if (!($perm_reqd eq 'yes')) {
                   2491:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2492:                     }
                   2493:                 }
                   2494:             }
                   2495:         }
                   2496:     } else {
                   2497:         my ($result,$perm_reqd) = 
1.707     albertel 2498: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2499:         if ($result eq 'ok') {
                   2500:             if (!($perm_reqd eq 'yes')) {
                   2501:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2502:             }
                   2503:         }
                   2504:     }
                   2505:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2506: }
                   2507: 
                   2508: sub retrievestudentphoto {
                   2509:     my ($udom,$unam,$ext,$type) = @_;
                   2510:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2511:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2512:     if ($ret eq 'ok') {
                   2513:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2514:         if ($type eq 'thumbnail') {
                   2515:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2516:         }
                   2517:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2518:         return $tokenurl;
                   2519:     } else {
                   2520:         if ($type eq 'thumbnail') {
                   2521:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2522:         } else { 
                   2523:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2524:         }
1.617     albertel 2525:     }
                   2526: }
                   2527: 
1.263     www      2528: # -------------------------------------------------------------------- New chat
                   2529: 
                   2530: sub chatsend {
1.724     raeburn  2531:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2532:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2533:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2534:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2535:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2536: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2537: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2538: }
                   2539: 
                   2540: # ------------------------------------------ Find current version of a resource
                   2541: 
                   2542: sub getversion {
                   2543:     my $fname=&clutter(shift);
1.1189    raeburn  2544:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2545:     return &currentversion(&filelocation('',$fname));
                   2546: }
                   2547: 
                   2548: sub currentversion {
                   2549:     my $fname=shift;
                   2550:     my $author=$fname;
                   2551:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2552:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2553:     my $home=&homeserver($uname,$udom);
1.292     www      2554:     if ($home eq 'no_host') { 
                   2555:         return -1; 
                   2556:     }
1.1112    www      2557:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2558:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2559: 	return -1;
                   2560:     }
1.1112    www      2561:     return $answer;
1.263     www      2562: }
                   2563: 
1.1111    www      2564: #
                   2565: # Return special version number of resource if set by override, empty otherwise
                   2566: #
                   2567: sub usedversion {
                   2568:     my $fname=shift;
                   2569:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2570:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2571:     if ($urlversion) { return $urlversion; }
                   2572:     return '';
                   2573: }
                   2574: 
1.1       albertel 2575: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2576: 
1.1       albertel 2577: sub subscribe {
                   2578:     my $fname=shift;
1.761     raeburn  2579:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2580:     $fname=~s/[\n\r]//g;
1.1       albertel 2581:     my $author=$fname;
                   2582:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2583:     my ($udom,$uname)=split(/\//,$author);
                   2584:     my $home=homeserver($uname,$udom);
1.335     albertel 2585:     if ($home eq 'no_host') {
                   2586:         return 'not_found';
1.1       albertel 2587:     }
                   2588:     my $answer=reply("sub:$fname",$home);
1.64      www      2589:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2590: 	$answer.=' by '.$home;
                   2591:     }
1.1       albertel 2592:     return $answer;
                   2593: }
                   2594:     
1.8       www      2595: # -------------------------------------------------------------- Replicate file
                   2596: 
                   2597: sub repcopy {
                   2598:     my $filename=shift;
1.23      www      2599:     $filename=~s/\/+/\//g;
1.1142    raeburn  2600:     my $londocroot = $perlvar{'lonDocRoot'};
                   2601:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2602:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2603:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2604: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2605: 	return &repcopy_userfile($filename);
                   2606:     }
1.532     albertel 2607:     $filename=~s/[\n\r]//g;
1.8       www      2608:     my $transname="$filename.in.transfer";
1.828     www      2609: # FIXME: this should flock
1.607     raeburn  2610:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2611:     my $remoteurl=subscribe($filename);
1.64      www      2612:     if ($remoteurl =~ /^con_lost by/) {
                   2613: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2614:            return 'unavailable';
1.8       www      2615:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2616: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2617: 	   return 'not_found';
1.64      www      2618:     } elsif ($remoteurl =~ /^rejected by/) {
                   2619: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2620:            return 'forbidden';
1.20      www      2621:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2622:            return 'ok';
1.8       www      2623:     } else {
1.290     www      2624:         my $author=$filename;
                   2625:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2626:         my ($udom,$uname)=split(/\//,$author);
                   2627:         my $home=homeserver($uname,$udom);
                   2628:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2629:            my @parts=split(/\//,$filename);
                   2630:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2631:            if ($path ne "$londocroot/res") {
1.8       www      2632:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2633: 	       return 'bad_request';
1.8       www      2634:            }
                   2635:            my $count;
                   2636:            for ($count=5;$count<$#parts;$count++) {
                   2637:                $path.="/$parts[$count]";
                   2638:                if ((-e $path)!=1) {
                   2639: 		   mkdir($path,0777);
                   2640:                }
                   2641:            }
                   2642:            my $ua=new LWP::UserAgent;
                   2643:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2644:            my $response=$ua->request($request,$transname);
                   2645:            if ($response->is_error()) {
                   2646: 	       unlink($transname);
                   2647:                my $message=$response->status_line;
1.672     albertel 2648:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2649:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2650:                return 'unavailable';
1.8       www      2651:            } else {
1.16      www      2652: 	       if ($remoteurl!~/\.meta$/) {
                   2653:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2654:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2655:                   if ($mresponse->is_error()) {
                   2656: 		      unlink($filename.'.meta');
                   2657:                       &logthis(
1.672     albertel 2658:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2659:                   }
                   2660: 	       }
1.8       www      2661:                rename($transname,$filename);
1.607     raeburn  2662:                return 'ok';
1.8       www      2663:            }
1.290     www      2664:        }
1.8       www      2665:     }
1.330     www      2666: }
                   2667: 
                   2668: # ------------------------------------------------ Get server side include body
                   2669: sub ssi_body {
1.381     albertel 2670:     my ($filelink,%form)=@_;
1.606     matthew  2671:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2672:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2673:     }
1.953     www      2674:     my $output='';
                   2675:     my $response;
1.980     raeburn  2676:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2677:        ($output,$response)=&externalssi($filelink);
1.953     www      2678:     } else {
1.1004    droeschl 2679:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2680:        $filelink .= 'inhibitmenu=yes';
1.953     www      2681:        ($output,$response)=&ssi($filelink,%form);
                   2682:     }
1.778     albertel 2683:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2684:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2685:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2686:     if (wantarray) {
                   2687:         return ($output, $response);
                   2688:     } else {
                   2689:         return $output;
                   2690:     }
1.8       www      2691: }
                   2692: 
1.15      www      2693: # --------------------------------------------------------- Server Side Include
                   2694: 
1.782     albertel 2695: sub absolute_url {
                   2696:     my ($host_name) = @_;
                   2697:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2698:     if ($host_name eq '') {
                   2699: 	$host_name = $ENV{'SERVER_NAME'};
                   2700:     }
                   2701:     return $protocol.$host_name;
                   2702: }
                   2703: 
1.942     foxr     2704: #
                   2705: #   Server side include.
                   2706: # Parameters:
                   2707: #  fn     Possibly encrypted resource name/id.
                   2708: #  form   Hash that describes how the rendering should be done
                   2709: #         and other things.
1.944     foxr     2710: # Returns:
1.950     raeburn  2711: #   Scalar context: The content of the response.
                   2712: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2713: #     
1.15      www      2714: sub ssi {
                   2715: 
1.944     foxr     2716:     my ($fn,%form)=@_;
1.15      www      2717:     my $ua=new LWP::UserAgent;
1.23      www      2718:     my $request;
1.711     albertel 2719: 
                   2720:     $form{'no_update_last_known'}=1;
1.895     albertel 2721:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2722:     if (%form) {
1.782     albertel 2723:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2724:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2725:     } else {
1.782     albertel 2726:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2727:     }
                   2728: 
1.15      www      2729:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2730:     my $response= $ua->request($request);
1.1182    foxr     2731:     my $content = $response->content;
                   2732: 
                   2733: 
1.944     foxr     2734:     if (wantarray) {
1.1173    foxr     2735: 	return ($content, $response);
1.944     foxr     2736:     } else {
1.1173    foxr     2737: 	return $content;
1.942     foxr     2738:     }
1.324     www      2739: }
                   2740: 
                   2741: sub externalssi {
                   2742:     my ($url)=@_;
                   2743:     my $ua=new LWP::UserAgent;
                   2744:     my $request=new HTTP::Request('GET',$url);
                   2745:     my $response=$ua->request($request);
1.954     raeburn  2746:     if (wantarray) {
                   2747:         return ($response->content, $response);
                   2748:     } else {
                   2749:         return $response->content;
                   2750:     }
1.15      www      2751: }
1.254     www      2752: 
1.492     albertel 2753: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2754: 
                   2755: sub allowuploaded {
                   2756:     my ($srcurl,$url)=@_;
                   2757:     $url=&clutter(&declutter($url));
                   2758:     my $dir=$url;
                   2759:     $dir=~s/\/[^\/]+$//;
                   2760:     my %httpref=();
                   2761:     my $httpurl=&hreflocation('',$url);
                   2762:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2763:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2764: }
1.477     raeburn  2765: 
1.1193    raeburn  2766: #
                   2767: # Determine if the current user should be able to edit a particular resource,
                   2768: # when viewing in course context.
                   2769: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2770: #     Functions.
                   2771: # (b) When displaying folder contents in course editor, used to determine if
                   2772: #     "Edit" link will be displayed alongside resource.
                   2773: #
1.1196    raeburn  2774: #  input: six args -- filename (decluttered), course number, course domain,
                   2775: #                   url, symb (if registered) and group (if this is a group
                   2776: #                   item -- e.g., bulletin board, group page etc.).
                   2777: #  output: array of five scalars -- 
1.1193    raeburn  2778: #          $cfile -- url for file editing if editable on current server
                   2779: #          $home -- homeserver of resource (i.e., for author if published,
                   2780: #                                           or course if uploaded.).
                   2781: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  2782: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   2783: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  2784: #
                   2785: 
                   2786: sub can_edit_resource {
1.1194    raeburn  2787:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2788:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2789: #
                   2790: # For aboutme pages user can only edit his/her own.
                   2791: #
1.1199    raeburn  2792:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  2793:         my ($sdom,$sname) = ($1,$2);
                   2794:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2795:             $home = $env{'user.home'};
                   2796:             $cfile = $resurl;
                   2797:             if ($env{'form.forceedit'}) {
                   2798:                 $forceview = 1;
                   2799:             } else {
                   2800:                 $forceedit = 1;
                   2801:             }
                   2802:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2803:         } else {
                   2804:             return;
                   2805:         }
                   2806:     }
                   2807: 
                   2808:     if ($env{'request.course.id'}) {
                   2809:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2810:         if ($group ne '') {
                   2811: # if this is a group homepage or group bulletin board, check group privs
                   2812:             my $allowed = 0;
1.1197    raeburn  2813:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2814:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  2815:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  2816:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2817:                     $allowed = 1;
                   2818:                 }
1.1197    raeburn  2819:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2820:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2821:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  2822:                     $allowed = 1;
                   2823:                 }
                   2824:             }
                   2825:             if ($allowed) {
                   2826:                 $home=&homeserver($cnum,$cdom);
                   2827:                 if ($env{'form.forceedit'}) {
                   2828:                     $forceview = 1;
                   2829:                 } else {
                   2830:                     $forceedit = 1;
                   2831:                 }
                   2832:                 $cfile = $resurl;
                   2833:             } else {
                   2834:                 return;
                   2835:             }
                   2836:         } else {
1.1208    raeburn  2837:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2838:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2839:                     return;
                   2840:                 }
                   2841:             } elsif (!$crsedit) {
1.1194    raeburn  2842: #
                   2843: # No edit allowed where CC has switched to student role.
                   2844: #
                   2845:                 return;
                   2846:             }
                   2847:         }
                   2848:     }
                   2849: 
1.1193    raeburn  2850:     if ($file ne '') {
                   2851:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  2852:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2853:                 $uploaded = 1;
                   2854:                 $incourse = 1;
1.1193    raeburn  2855:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2856:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  2857:                     if ($env{'form.forceedit'}) {
                   2858:                         $forceview = 1;
                   2859:                     } else {
                   2860:                         $forceedit = 1;
                   2861:                     }
1.1194    raeburn  2862:                 }
                   2863:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2864:                 $incourse = 1;
                   2865:                 if ($env{'form.forceedit'}) {
                   2866:                     $forceview = 1;
                   2867:                 } else {
                   2868:                     $forceedit = 1;
                   2869:                 }
                   2870:                 $cfile = $resurl;
                   2871:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   2872:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2873:                     $incourse = 1;
                   2874:                     if ($env{'form.forceedit'}) {
                   2875:                         $forceview = 1;
                   2876:                     } else {
                   2877:                         $forceedit = 1;
                   2878:                     }
                   2879:                     $cfile = $resurl;
1.1199    raeburn  2880:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  2881:                     $incourse = 1;
                   2882:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  2883:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  2884:                     $incourse = 1;
1.1199    raeburn  2885:                     if ($env{'form.forceedit'}) {
                   2886:                         $forceview = 1;
                   2887:                     } else {
                   2888:                         $forceedit = 1;
                   2889:                     }
                   2890:                     $cfile = $resurl;
1.1208    raeburn  2891:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2892:                     $incourse = 1;
                   2893:                     if ($env{'form.forceedit'}) {
                   2894:                         $forceview = 1;
                   2895:                     } else {
                   2896:                         $forceedit = 1;
                   2897:                     }
                   2898:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  2899:                 }
                   2900:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2901:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2902:                 if (&is_on_map($template)) { 
                   2903:                     $incourse = 1;
                   2904:                     $forceview = 1;
                   2905:                     $cfile = $template;
1.1193    raeburn  2906:                 }
1.1199    raeburn  2907:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2908:                     $incourse = 1;
                   2909:                     if ($env{'form.forceedit'}) {
                   2910:                         $forceview = 1;
                   2911:                     } else {
                   2912:                         $forceedit = 1;
                   2913:                     }
                   2914:                     $cfile = $resurl;
                   2915:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2916:                 $incourse = 1;
                   2917:                 $forceview = 1;
                   2918:                 if ($symb) {
                   2919:                     my ($map,$id,$res)=&decode_symb($symb);
                   2920:                     $env{'request.symb'} = $symb;
                   2921:                     $cfile = &clutter($res);
                   2922:                 } else {
                   2923:                     $cfile = $env{'form.suppurl'};
                   2924:                     $cfile =~ s{^http://}{};
                   2925:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2926:                 }
1.1234    raeburn  2927:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2928:                 if ($env{'form.forceedit'}) {
                   2929:                     $forceview = 1;
                   2930:                 } else {
                   2931:                     $forceedit = 1;
                   2932:                 }
                   2933:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  2934:             }
                   2935:         }
1.1194    raeburn  2936:         if ($uploaded || $incourse) {
                   2937:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  2938:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  2939:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2940:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2941:             # Check that the user has permission to edit this resource
                   2942:             my $setpriv = 1;
                   2943:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2944:             if (defined($cfudom)) {
                   2945:                 $home=&homeserver($cfuname,$cfudom);
                   2946:                 $cfile=$file;
                   2947:             }
                   2948:         }
1.1194    raeburn  2949:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   2950:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  2951:             my @ids=&current_machine_ids();
                   2952:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2953:                 $switchserver=1;
                   2954:             }
                   2955:         }
                   2956:     }
1.1194    raeburn  2957:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  2958: }
                   2959: 
                   2960: sub is_course_upload {
                   2961:     my ($file,$cnum,$cdom) = @_;
                   2962:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2963:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  2964:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2965:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  2966:         return 1;
                   2967:     }
                   2968:     return;
                   2969: }
                   2970: 
1.1194    raeburn  2971: sub in_course {
1.1195    raeburn  2972:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2973:     if ($hideprivileged) {
                   2974:         my $skipuser;
1.1219    raeburn  2975:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2976:         my @possdoms = ($cdom);  
                   2977:         if ($coursehash{'checkforpriv'}) { 
                   2978:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   2979:         }
                   2980:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  2981:             $skipuser = 1;
                   2982:             if ($coursehash{'nothideprivileged'}) {
                   2983:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2984:                     my $user;
                   2985:                     if ($item =~ /:/) {
                   2986:                         $user = $item;
                   2987:                     } else {
                   2988:                         $user = join(':',split(/[\@]/,$item));
                   2989:                     }
                   2990:                     if ($user eq $uname.':'.$udom) {
                   2991:                         undef($skipuser);
                   2992:                         last;
                   2993:                     }
                   2994:                 }
                   2995:             }
                   2996:             if ($skipuser) {
                   2997:                 return 0;
                   2998:             }
                   2999:         }
                   3000:     }
1.1194    raeburn  3001:     $type ||= 'any';
                   3002:     if (!defined($cdom) || !defined($cnum)) {
                   3003:         my $cid  = $env{'request.course.id'};
                   3004:         $cdom = $env{'course.'.$cid.'.domain'};
                   3005:         $cnum = $env{'course.'.$cid.'.num'};
                   3006:     }
                   3007:     my $typesref;
1.1195    raeburn  3008:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3009:         $typesref = ['active','previous','future'];
                   3010:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3011:         $typesref = [$type];
                   3012:     }
                   3013:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3014:                               $typesref,undef,[$cdom]);
                   3015:     my ($tmp) = keys(%roles);
                   3016:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3017:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3018:     if (@course_roles > 0) {
                   3019:         return 1;
                   3020:     }
                   3021:     return 0;
                   3022: }
                   3023: 
1.478     albertel 3024: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3025: # input: action, courseID, current domain, intended
1.637     raeburn  3026: #        path to file, source of file, instruction to parse file for objects,
                   3027: #        ref to hash for embedded objects,
                   3028: #        ref to hash for codebase of java objects.
1.1095    raeburn  3029: #        reference to scalar to accommodate mime type determined
                   3030: #          from File::MMagic if $parser = parse.
1.637     raeburn  3031: #
1.485     raeburn  3032: # output: url to file (if action was uploaddoc), 
                   3033: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3034: #
1.478     albertel 3035: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3036: # course.
1.477     raeburn  3037: #
1.478     albertel 3038: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3039: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3040: #          course's home server.
1.477     raeburn  3041: #
1.478     albertel 3042: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3043: #          be copied from $source (current location) to 
                   3044: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3045: #         and will then be copied to
                   3046: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3047: #         course's home server.
1.485     raeburn  3048: #
1.481     raeburn  3049: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3050: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3051: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3052: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3053: #         in course's home server.
1.637     raeburn  3054: #
1.477     raeburn  3055: 
                   3056: sub process_coursefile {
1.1095    raeburn  3057:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3058:         $mimetype)=@_;
1.477     raeburn  3059:     my $fetchresult;
1.638     albertel 3060:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3061:     if ($action eq 'propagate') {
1.638     albertel 3062:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3063: 			     $home);
1.481     raeburn  3064:     } else {
1.477     raeburn  3065:         my $fpath = '';
                   3066:         my $fname = $file;
1.478     albertel 3067:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3068:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3069:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3070:         if ($action eq 'copy') {
                   3071:             if ($source eq '') {
                   3072:                 $fetchresult = 'no source file';
                   3073:                 return $fetchresult;
                   3074:             } else {
                   3075:                 my $destination = $filepath.'/'.$fname;
                   3076:                 rename($source,$destination);
                   3077:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3078:                                  $home);
1.481     raeburn  3079:             }
                   3080:         } elsif ($action eq 'uploaddoc') {
                   3081:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3082:             print $fh $env{'form.'.$source};
1.481     raeburn  3083:             close($fh);
1.637     raeburn  3084:             if ($parser eq 'parse') {
1.1024    raeburn  3085:                 my $mm = new File::MMagic;
1.1095    raeburn  3086:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3087:                 if ($type eq 'text/html') {
1.1024    raeburn  3088:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3089:                     unless ($parse_result eq 'ok') {
                   3090:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3091:                     }
1.637     raeburn  3092:                 }
1.1095    raeburn  3093:                 if (ref($mimetype)) {
                   3094:                     $$mimetype = $type;
                   3095:                 } 
1.637     raeburn  3096:             }
1.477     raeburn  3097:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3098:                                  $home);
1.481     raeburn  3099:             if ($fetchresult eq 'ok') {
                   3100:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3101:             } else {
                   3102:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3103:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3104:                 return '/adm/notfound.html';
                   3105:             }
1.477     raeburn  3106:         }
                   3107:     }
1.485     raeburn  3108:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3109:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3110:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3111:     }
                   3112:     return $fetchresult;
                   3113: }
                   3114: 
1.637     raeburn  3115: sub build_filepath {
                   3116:     my ($fpath) = @_;
                   3117:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3118:     unless ($fpath eq '') {
                   3119:         my @parts=split('/',$fpath);
                   3120:         foreach my $part (@parts) {
                   3121:             $filepath.= '/'.$part;
                   3122:             if ((-e $filepath)!=1) {
                   3123:                 mkdir($filepath,0777);
                   3124:             }
                   3125:         }
                   3126:     }
                   3127:     return $filepath;
                   3128: }
                   3129: 
                   3130: sub store_edited_file {
1.638     albertel 3131:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3132:     my $file = $primary_url;
                   3133:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3134:     my $fpath = '';
                   3135:     my $fname = $file;
                   3136:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3137:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3138:     my $filepath = &build_filepath($fpath);
                   3139:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3140:     print $fh $content;
                   3141:     close($fh);
1.638     albertel 3142:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3143:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3144: 			  $home);
1.637     raeburn  3145:     if ($$fetchresult eq 'ok') {
                   3146:         return '/uploaded/'.$fpath.'/'.$fname;
                   3147:     } else {
1.638     albertel 3148:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3149: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3150:         return '/adm/notfound.html';
                   3151:     }
                   3152: }
                   3153: 
1.531     albertel 3154: sub clean_filename {
1.831     albertel 3155:     my ($fname,$args)=@_;
1.315     www      3156: # Replace Windows backslashes by forward slashes
1.257     www      3157:     $fname=~s/\\/\//g;
1.831     albertel 3158:     if (!$args->{'keep_path'}) {
                   3159:         # Get rid of everything but the actual filename
                   3160: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3161:     }
1.315     www      3162: # Replace spaces by underscores
                   3163:     $fname=~s/\s+/\_/g;
                   3164: # Replace all other weird characters by nothing
1.831     albertel 3165:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3166: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3167: # numbers
                   3168:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3169:     return $fname;
                   3170: }
1.1051    raeburn  3171: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3172: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3173: # image with the same aspect ratio as the original, but with dimensions which do 
                   3174: # not exceed $resizewidth and $resizeheight.
                   3175:  
1.984     neumanie 3176: sub resizeImage {
1.1051    raeburn  3177:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3178:     my $ima = Image::Magick->new;
                   3179:     my $resized;
                   3180:     if (-e $img_path) {
                   3181:         $ima->Read($img_path);
                   3182:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3183:             my $width = $ima->Get('width');
                   3184:             my $height = $ima->Get('height');
                   3185:             if ($width > $resizewidth) {
                   3186: 	        my $factor = $width/$resizewidth;
                   3187:                 my $newheight = $height/$factor;
                   3188:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3189:                 $resized = 1;
                   3190:             }
                   3191:         }
                   3192:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3193:             my $width = $ima->Get('width');
                   3194:             my $height = $ima->Get('height');
                   3195:             if ($height > $resizeheight) {
                   3196:                 my $factor = $height/$resizeheight;
                   3197:                 my $newwidth = $width/$factor;
                   3198:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3199:                 $resized = 1;
                   3200:             }
                   3201:         }
                   3202:         if ($resized) {
                   3203:             $ima->Write($img_path);
                   3204:         }
                   3205:     }
                   3206:     return;
1.977     amueller 3207: }
                   3208: 
1.608     albertel 3209: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3210: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3211: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3212: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3213: #                                    canceloverwrite, or ''. 
                   3214: #                   if 'coursedoc': upload to the current course
                   3215: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3216: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3217: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3218: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3219: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3220: #        $allfiles - reference to hash for embedded objects
                   3221: #        $codebase - reference to hash for codebase of java objects
                   3222: #        $desuname - username for permanent storage of uploaded file
                   3223: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3224: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3225: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3226: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3227: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3228: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3229: #                    from File::MMagic.
1.858     raeburn  3230: # 
1.686     albertel 3231: # output: url of file in userspace, or error: <message> 
                   3232: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3233: 
1.531     albertel 3234: sub userfileupload {
1.1090    raeburn  3235:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3236:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3237:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3238:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3239:     $fname=&clean_filename($fname);
1.1090    raeburn  3240:     # See if there is anything left
1.257     www      3241:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3242:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3243:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3244:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3245:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3246:         my $now = time;
1.1090    raeburn  3247:         my $filepath;
1.1095    raeburn  3248:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3249:              $filepath = 'tmp/helprequests/'.$now;
                   3250:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3251:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3252:                          '_'.$env{'user.domain'}.'/pending';
                   3253:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3254:             my ($docuname,$docudom);
                   3255:             if ($destudom) {
                   3256:                 $docudom = $destudom;
                   3257:             } else {
                   3258:                 $docudom = $env{'user.domain'};
                   3259:             }
                   3260:             if ($destuname) {
                   3261:                 $docuname = $destuname;
                   3262:             } else {
                   3263:                 $docuname = $env{'user.name'};
                   3264:             }
                   3265:             if (exists($env{'form.group'})) {
                   3266:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3267:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3268:             }
                   3269:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3270:             if ($context eq 'canceloverwrite') {
                   3271:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3272:                 if (-e  $tempfile) {
                   3273:                     my @info = stat($tempfile);
                   3274:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3275:                         unlink($tempfile);
                   3276:                     }
                   3277:                 }
                   3278:                 return;
1.523     raeburn  3279:             }
                   3280:         }
1.1090    raeburn  3281:         # Create the directory if not present
1.741     raeburn  3282:         my @parts=split(/\//,$filepath);
                   3283:         my $fullpath = $perlvar{'lonDaemons'};
                   3284:         for (my $i=0;$i<@parts;$i++) {
                   3285:             $fullpath .= '/'.$parts[$i];
                   3286:             if ((-e $fullpath)!=1) {
                   3287:                 mkdir($fullpath,0777);
                   3288:             }
                   3289:         }
                   3290:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3291:         print $fh $env{'form.'.$formname};
                   3292:         close($fh);
1.1090    raeburn  3293:         if ($context eq 'existingfile') {
                   3294:             my @info = stat($fullpath.'/'.$fname);
                   3295:             return ($fullpath.'/'.$fname,$info[9]);
                   3296:         } else {
                   3297:             return $fullpath.'/'.$fname;
                   3298:         }
1.523     raeburn  3299:     }
1.995     raeburn  3300:     if ($subdir eq 'scantron') {
                   3301:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3302:     } else {
1.995     raeburn  3303:         $fname="$subdir/$fname";
                   3304:     }
1.1090    raeburn  3305:     if ($context eq 'coursedoc') {
1.638     albertel 3306: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3307: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3308:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3309:             return &finishuserfileupload($docuname,$docudom,
                   3310: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3311: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3312:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3313:         } else {
1.1218    raeburn  3314:             if ($env{'form.folder'}) {
                   3315:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3316:             }
1.638     albertel 3317:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3318: 				       $fname,$formname,$parser,
1.1095    raeburn  3319: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3320:         }
1.719     banghart 3321:     } elsif (defined($destuname)) {
                   3322:         my $docuname=$destuname;
                   3323:         my $docudom=$destudom;
1.860     raeburn  3324: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3325: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3326:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3327:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3328:     } else {
1.638     albertel 3329:         my $docuname=$env{'user.name'};
                   3330:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3331:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3332:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3333:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3334:         }
1.860     raeburn  3335: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3336: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3337:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3338:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3339:     }
1.271     www      3340: }
                   3341: 
                   3342: sub finishuserfileupload {
1.860     raeburn  3343:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3344:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3345:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3346:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3347:   
1.860     raeburn  3348:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3349:     $file=$fname;
                   3350:     if ($fname=~m|/|) {
                   3351:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3352: 	$path.=$fnamepath.'/';
                   3353:     }
1.259     www      3354:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3355:     my $count;
                   3356:     for ($count=4;$count<=$#parts;$count++) {
                   3357:         $filepath.="/$parts[$count]";
                   3358:         if ((-e $filepath)!=1) {
                   3359: 	    mkdir($filepath,0777);
                   3360:         }
                   3361:     }
1.984     neumanie 3362: 
1.258     www      3363: # Save the file
                   3364:     {
1.701     albertel 3365: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3366: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3367: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3368: 	    return '/adm/notfound.html';
                   3369: 	}
1.1090    raeburn  3370:         if ($context eq 'overwrite') {
1.1117    foxr     3371:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3372:             my $target = $filepath.'/'.$file;
                   3373:             if (-e $source) {
                   3374:                 my @info = stat($source);
                   3375:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3376:                     unless (&File::Copy::move($source,$target)) {
                   3377:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3378:                         return "Moving from $source failed";
                   3379:                     }
                   3380:                 } else {
                   3381:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3382:                 }
                   3383:             } else {
                   3384:                 return "Temporary file: $source missing";
                   3385:             }
                   3386:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3387: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3388: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3389: 	    return '/adm/notfound.html';
                   3390: 	}
1.570     albertel 3391: 	close(FH);
1.1051    raeburn  3392:         if ($resizewidth && $resizeheight) {
                   3393:             my $mm = new File::MMagic;
                   3394:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3395:             if ($mime_type =~ m{^image/}) {
                   3396: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3397:             }  
1.977     amueller 3398: 	}
1.258     www      3399:     }
1.1152    raeburn  3400:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3401:         if (ref($mimetype)) {
                   3402:             if ($$mimetype eq '') {
                   3403:                 my $mm = new File::MMagic;
                   3404:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3405:                 $$mimetype = $type;
                   3406:             }
                   3407:         }
                   3408:     }
1.637     raeburn  3409:     if ($parser eq 'parse') {
1.1152    raeburn  3410:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3411:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3412:                                                        $allfiles,$codebase);
                   3413:             unless ($parse_result eq 'ok') {
                   3414:                 &logthis('Failed to parse '.$filepath.$file.
                   3415: 	   	         ' for embedded media: '.$parse_result); 
                   3416:             }
1.637     raeburn  3417:         }
                   3418:     }
1.860     raeburn  3419:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3420:         my $input = $filepath.'/'.$file;
                   3421:         my $output = $filepath.'/'.'tn-'.$file;
                   3422:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3423:         system("convert -sample $thumbsize $input $output");
                   3424:         if (-e $filepath.'/'.'tn-'.$file) {
                   3425:             $fetchthumb  = 1; 
                   3426:         }
                   3427:     }
1.858     raeburn  3428:  
1.259     www      3429: # Notify homeserver to grep it
                   3430: #
1.984     neumanie 3431:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3432:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3433:     if ($fetchresult eq 'ok') {
1.860     raeburn  3434:         if ($fetchthumb) {
                   3435:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3436:             if ($thumbresult ne 'ok') {
                   3437:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3438:                          $docuhome.': '.$thumbresult);
                   3439:             }
                   3440:         }
1.259     www      3441: #
1.258     www      3442: # Return the URL to it
1.494     albertel 3443:         return '/uploaded/'.$path.$file;
1.263     www      3444:     } else {
1.494     albertel 3445:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3446: 		 ': '.$fetchresult);
1.263     www      3447:         return '/adm/notfound.html';
1.858     raeburn  3448:     }
1.493     albertel 3449: }
                   3450: 
1.637     raeburn  3451: sub extract_embedded_items {
1.961     raeburn  3452:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3453:     my @state = ();
1.1164    raeburn  3454:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3455:     my %javafiles = (
                   3456:                       codebase => '',
                   3457:                       code => '',
                   3458:                       archive => ''
                   3459:                     );
                   3460:     my %mediafiles = (
                   3461:                       src => '',
                   3462:                       movie => '',
                   3463:                      );
1.648     raeburn  3464:     my $p;
                   3465:     if ($content) {
                   3466:         $p = HTML::LCParser->new($content);
                   3467:     } else {
1.961     raeburn  3468:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3469:     }
1.641     albertel 3470:     while (my $t=$p->get_token()) {
1.640     albertel 3471: 	if ($t->[0] eq 'S') {
                   3472: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3473: 	    push(@state, $tagname);
1.648     raeburn  3474:             if (lc($tagname) eq 'allow') {
                   3475:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3476:             }
1.640     albertel 3477: 	    if (lc($tagname) eq 'img') {
                   3478: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3479: 	    }
1.886     albertel 3480: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3481:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3482:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3483:                 }
1.886     albertel 3484: 	    }
1.645     raeburn  3485:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3486:                 my $src;
1.645     raeburn  3487:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3488:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3489:                 } else {
1.1164    raeburn  3490:                     if ($attr->{'src'} ne '') {
                   3491:                         $src = $attr->{'src'};
                   3492:                         &add_filetype($allfiles,$src,'src');
                   3493:                     }
                   3494:                 }
                   3495:                 my $text = $p->get_trimmed_text();
                   3496:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3497:                     my @swfargs = split(/,/,$1);
                   3498:                     foreach my $item (@swfargs) {
                   3499:                         $item =~ s/["']//g;
                   3500:                         $item =~ s/^\s+//;
                   3501:                         $item =~ s/\s+$//;
                   3502:                     }
                   3503:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3504:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3505:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3506:                         } else {
                   3507:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3508:                         }
                   3509:                     }
1.645     raeburn  3510:                 }
                   3511:             }
                   3512:             if (lc($tagname) eq 'link') {
                   3513:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3514:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3515:                 }
                   3516:             }
1.640     albertel 3517: 	    if (lc($tagname) eq 'object' ||
                   3518: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3519: 		foreach my $item (keys(%javafiles)) {
                   3520: 		    $javafiles{$item} = '';
                   3521: 		}
1.1164    raeburn  3522:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3523:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3524:                 }
1.640     albertel 3525: 	    }
                   3526: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3527: 		my $name = lc($attr->{'name'});
                   3528: 		foreach my $item (keys(%javafiles)) {
                   3529: 		    if ($name eq $item) {
                   3530: 			$javafiles{$item} = $attr->{'value'};
                   3531: 			last;
                   3532: 		    }
                   3533: 		}
1.1164    raeburn  3534:                 my $pathfrom;
1.640     albertel 3535: 		foreach my $item (keys(%mediafiles)) {
                   3536: 		    if ($name eq $item) {
1.1164    raeburn  3537:                         $pathfrom = $attr->{'value'};
                   3538:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3539: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3540: 			last;
                   3541: 		    }
                   3542: 		}
1.1164    raeburn  3543:                 if ($name eq 'flashvars') {
                   3544:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3545:                 }
                   3546:                 if ($pathfrom ne '') {
                   3547:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3548:                                          $pathfrom);
                   3549:                 }
1.640     albertel 3550: 	    }
                   3551: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3552: 		foreach my $item (keys(%javafiles)) {
                   3553: 		    if ($attr->{$item}) {
                   3554: 			$javafiles{$item} = $attr->{$item};
                   3555: 			last;
                   3556: 		    }
                   3557: 		}
                   3558: 		foreach my $item (keys(%mediafiles)) {
                   3559: 		    if ($attr->{$item}) {
                   3560: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3561: 			last;
                   3562: 		    }
                   3563: 		}
1.1164    raeburn  3564:                 if (lc($tagname) eq 'embed') {
                   3565:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3566:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3567:                                              $attr->{'src'});
                   3568:                     }
                   3569:                 }
1.640     albertel 3570: 	    }
1.1243    raeburn  3571:             if (lc($tagname) eq 'iframe') {
                   3572:                 my $src = $attr->{'src'} ;
                   3573:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3574:                     &add_filetype($allfiles,$src,'src');
                   3575:                 } elsif ($src =~ m{^/}) {
                   3576:                     if ($env{'request.course.id'}) {
                   3577:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3578:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3579:                         my $url = &hreflocation('',$fullpath);
                   3580:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3581:                             my $relpath = $1;
                   3582:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3583:                                 &add_filetype($allfiles,$1,'src');
                   3584:                             }
                   3585:                         }
                   3586:                     }
                   3587:                 }
                   3588:             }
1.1164    raeburn  3589:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3590:                 pop(@state);
1.1164    raeburn  3591:             }
1.640     albertel 3592: 	} elsif ($t->[0] eq 'E') {
                   3593: 	    my ($tagname) = ($t->[1]);
                   3594: 	    if ($javafiles{'codebase'} ne '') {
                   3595: 		$javafiles{'codebase'} .= '/';
                   3596: 	    }  
                   3597: 	    if (lc($tagname) eq 'applet' ||
                   3598: 		lc($tagname) eq 'object' ||
                   3599: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3600: 		) {
                   3601: 		foreach my $item (keys(%javafiles)) {
                   3602: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3603: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3604: 			&add_filetype($allfiles,$file,$item);
                   3605: 		    }
                   3606: 		}
                   3607: 	    } 
                   3608: 	    pop @state;
                   3609: 	}
                   3610:     }
1.1164    raeburn  3611:     foreach my $id (sort(keys(%flashvars))) {
                   3612:         if ($shockwave{$id} ne '') {
                   3613:             my @pairs = split(/\&/,$flashvars{$id});
                   3614:             foreach my $pair (@pairs) {
                   3615:                 my ($key,$value) = split(/\=/,$pair);
                   3616:                 if ($key eq 'thumb') {
                   3617:                     &add_filetype($allfiles,$value,$key);
                   3618:                 } elsif ($key eq 'content') {
                   3619:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3620:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3621:                     if ($ext ne '') {
                   3622:                         &add_filetype($allfiles,$path.$value,$ext);
                   3623:                     }
                   3624:                 }
                   3625:             }
                   3626:         }
                   3627:     }
1.637     raeburn  3628:     return 'ok';
                   3629: }
                   3630: 
1.639     albertel 3631: sub add_filetype {
                   3632:     my ($allfiles,$file,$type)=@_;
                   3633:     if (exists($allfiles->{$file})) {
                   3634: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3635: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3636: 	}
                   3637:     } else {
                   3638: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3639:     }
                   3640: }
                   3641: 
1.1164    raeburn  3642: sub embedded_dependency {
                   3643:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3644:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3645:         if (($identifier ne '') &&
                   3646:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3647:             ($pathfrom ne '')) {
                   3648:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3649:             foreach my $dep (@{$related->{$identifier}}) {
                   3650:                 &add_filetype($allfiles,$path.$dep,'object');
                   3651:             }
                   3652:         }
                   3653:     }
                   3654:     return;
                   3655: }
                   3656: 
1.493     albertel 3657: sub removeuploadedurl {
1.984     neumanie 3658:     my ($url)=@_;	
                   3659:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3660:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3661: }
                   3662: 
                   3663: sub removeuserfile {
                   3664:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3665:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3666:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3667:     if ($result eq 'ok') {	
1.798     raeburn  3668:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3669:             my $metafile = $fname.'.meta';
                   3670:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3671: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3672:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3673:             my $sqlresult = 
1.823     albertel 3674:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3675:                                         'portfolio_metadata',$group,
                   3676:                                         'delete');
1.798     raeburn  3677:         }
                   3678:     }
                   3679:     return $result;
1.257     www      3680: }
1.15      www      3681: 
1.530     albertel 3682: sub mkdiruserfile {
                   3683:     my ($docuname,$docudom,$dir)=@_;
                   3684:     my $home=&homeserver($docuname,$docudom);
                   3685:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3686: }
                   3687: 
1.531     albertel 3688: sub renameuserfile {
                   3689:     my ($docuname,$docudom,$old,$new)=@_;
                   3690:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3691:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3692:                         &escape("$old").':'.&escape("$new"),$home);
                   3693:     if ($result eq 'ok') {
                   3694:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3695:             my $oldmeta = $old.'.meta';
                   3696:             my $newmeta = $new.'.meta';
                   3697:             my $metaresult = 
                   3698:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3699: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3700:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3701:             my $sqlresult = 
1.823     albertel 3702:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3703:                                         'portfolio_metadata',$group,
                   3704:                                         'delete');
1.798     raeburn  3705:         }
                   3706:     }
                   3707:     return $result;
1.531     albertel 3708: }
                   3709: 
1.14      www      3710: # ------------------------------------------------------------------------- Log
                   3711: 
                   3712: sub log {
                   3713:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3714:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3715: }
                   3716: 
                   3717: # ------------------------------------------------------------------ Course Log
1.352     www      3718: #
                   3719: # This routine flushes several buffers of non-mission-critical nature
                   3720: #
1.157     www      3721: 
                   3722: sub flushcourselogs {
1.352     www      3723:     &logthis('Flushing log buffers');
                   3724: #
                   3725: # course logs
                   3726: # This is a log of all transactions in a course, which can be used
                   3727: # for data mining purposes
                   3728: #
                   3729: # It also collects the courseid database, which lists last transaction
                   3730: # times and course titles for all courseids
                   3731: #
                   3732:     my %courseidbuffer=();
1.921     raeburn  3733:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3734:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3735: 		          &escape($courselogs{$crsid}),
                   3736: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3737: 	    delete $courselogs{$crsid};
                   3738:         } else {
                   3739:             &logthis('Failed to flush log buffer for '.$crsid);
                   3740:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3741:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3742:                         " exceeded maximum size, deleting.</font>");
                   3743:                delete $courselogs{$crsid};
                   3744:             }
1.352     www      3745:         }
1.920     raeburn  3746:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3747:             'description' => $coursedescrbuf{$crsid},
                   3748:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3749:             'type'        => $coursetypebuf{$crsid},
                   3750:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3751:         };
1.191     harris41 3752:     }
1.352     www      3753: #
                   3754: # Write course id database (reverse lookup) to homeserver of courses 
                   3755: # Is used in pickcourse
                   3756: #
1.840     albertel 3757:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3758:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3759:                                     $courseidbuffer{$crs_home},
                   3760:                                     $crs_home,'timeonly');
1.352     www      3761:     }
                   3762: #
                   3763: # File accesses
                   3764: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3765: #
1.449     matthew  3766:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3767:         if ($entry =~ /___count$/) {
                   3768:             my ($dom,$name);
1.807     albertel 3769:             ($dom,$name,undef)=
1.811     albertel 3770: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3771:             if (! defined($dom) || $dom eq '' || 
                   3772:                 ! defined($name) || $name eq '') {
1.620     albertel 3773:                 my $cid = $env{'request.course.id'};
                   3774:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3775:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3776:             }
1.450     matthew  3777:             my $value = $accesshash{$entry};
                   3778:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3779:             my %temphash=($url => $value);
1.449     matthew  3780:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3781:             if ($result eq 'ok') {
                   3782:                 delete $accesshash{$entry};
                   3783:             }
                   3784:         } else {
1.811     albertel 3785:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3786:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3787:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3788:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3789:                 delete $accesshash{$entry};
                   3790:             }
1.185     www      3791:         }
1.191     harris41 3792:     }
1.352     www      3793: #
                   3794: # Roles
                   3795: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3796: #
1.800     albertel 3797:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3798:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3799: 	    split(/\:/,$entry);
                   3800:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3801:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3802:                 $rudom,$runame) eq 'ok') {
                   3803: 	    delete $userrolehash{$entry};
                   3804:         }
                   3805:     }
1.662     raeburn  3806: #
                   3807: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3808: #
                   3809:     my %domrolebuffer = ();
1.1000    raeburn  3810:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3811:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3812:         if ($domrolebuffer{$rudom}) {
                   3813:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3814:                       '='.&escape($domainrolehash{$entry});
                   3815:         } else {
                   3816:             $domrolebuffer{$rudom}.=&escape($entry).
                   3817:                       '='.&escape($domainrolehash{$entry});
                   3818:         }
                   3819:         delete $domainrolehash{$entry};
                   3820:     }
                   3821:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3822: 	my %servers = &get_servers($dom,'library');
                   3823: 	foreach my $tryserver (keys(%servers)) {
                   3824: 	    unless (&reply('domroleput:'.$dom.':'.
                   3825: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3826: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3827: 	    }
1.662     raeburn  3828:         }
                   3829:     }
1.186     www      3830:     $dumpcount++;
1.157     www      3831: }
                   3832: 
                   3833: sub courselog {
                   3834:     my $what=shift;
1.158     www      3835:     $what=time.':'.$what;
1.620     albertel 3836:     unless ($env{'request.course.id'}) { return ''; }
                   3837:     $coursedombuf{$env{'request.course.id'}}=
                   3838:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3839:     $coursenumbuf{$env{'request.course.id'}}=
                   3840:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3841:     $coursehombuf{$env{'request.course.id'}}=
                   3842:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3843:     $coursedescrbuf{$env{'request.course.id'}}=
                   3844:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3845:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3846:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3847:     $courseownerbuf{$env{'request.course.id'}}=
                   3848:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3849:     $coursetypebuf{$env{'request.course.id'}}=
                   3850:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3851:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3852: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3853:     } else {
1.620     albertel 3854: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3855:     }
1.620     albertel 3856:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3857: 	&flushcourselogs();
                   3858:     }
1.158     www      3859: }
                   3860: 
                   3861: sub courseacclog {
                   3862:     my $fnsymb=shift;
1.620     albertel 3863:     unless ($env{'request.course.id'}) { return ''; }
                   3864:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3865:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3866:         $what.=':POST';
1.583     matthew  3867:         # FIXME: Probably ought to escape things....
1.800     albertel 3868: 	foreach my $key (keys(%env)) {
                   3869:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3870:                 my $formitem = $1;
                   3871:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3872:                     $what.=':'.$formitem.'='.$env{$key};
                   3873:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3874:                     $what.=':'.$formitem.'='.$env{$key};
                   3875:                 }
1.158     www      3876:             }
1.191     harris41 3877:         }
1.583     matthew  3878:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3879:         # FIXME: We should not be depending on a form parameter that someone
                   3880:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3881:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3882:             $what.= ':POST';
                   3883:             # FIXME: Probably ought to escape things....
                   3884:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3885:                                  'crsdiscuss') {
1.620     albertel 3886:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3887:             }
                   3888:         }
1.158     www      3889:     }
                   3890:     &courselog($what);
1.149     www      3891: }
                   3892: 
1.185     www      3893: sub countacc {
                   3894:     my $url=&declutter(shift);
1.458     matthew  3895:     return if (! defined($url) || $url eq '');
1.620     albertel 3896:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3897: #
                   3898: # Mark that this url was used in this course
                   3899: #
1.620     albertel 3900:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3901: #
                   3902: # Increase the access count for this resource in this child process
                   3903: #
1.281     www      3904:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3905:     $accesshash{$key}++;
1.185     www      3906: }
1.349     www      3907: 
1.361     www      3908: sub linklog {
                   3909:     my ($from,$to)=@_;
                   3910:     $from=&declutter($from);
                   3911:     $to=&declutter($to);
                   3912:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3913:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3914: }
1.1160    www      3915: 
                   3916: sub statslog {
                   3917:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3918:     if ($users<2) { return; }
                   3919:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3920:             'course'       => $env{'request.course.id'},
                   3921:             'sections'     => '"all"',
                   3922:             'num_students' => $users,
                   3923:             'part'         => $part,
                   3924:             'symb'         => $symb,
                   3925:             'mean_tries'   => $av_attempts,
                   3926:             'deg_of_diff'  => $degdiff});
                   3927:     foreach my $key (keys(%dynstore)) {
                   3928:         $accesshash{$key}=$dynstore{$key};
                   3929:     }
                   3930: }
1.361     www      3931:   
1.349     www      3932: sub userrolelog {
                   3933:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3934:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3935:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3936:        $userrolehash
                   3937:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3938:                     =$tend.':'.$tstart;
1.662     raeburn  3939:     }
1.1169    droeschl 3940:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3941:        $userrolehash
                   3942:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3943:                     =$tend.':'.$tstart;
                   3944:     }
1.1169    droeschl 3945:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3946:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3947:        $domainrolehash
                   3948:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3949:                     = $tend.':'.$tstart;
                   3950:     }
1.351     www      3951: }
                   3952: 
1.957     raeburn  3953: sub courserolelog {
                   3954:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  3955:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3956:         my $cdom = $1;
                   3957:         my $cnum = $2;
                   3958:         my $sec = $3;
                   3959:         my $namespace = 'rolelog';
                   3960:         my %storehash = (
                   3961:                            role    => $trole,
                   3962:                            start   => $tstart,
                   3963:                            end     => $tend,
                   3964:                            selfenroll => $selfenroll,
                   3965:                            context    => $context,
                   3966:                         );
                   3967:         if ($trole eq 'gr') {
                   3968:             $namespace = 'groupslog';
                   3969:             $storehash{'group'} = $sec;
                   3970:         } else {
                   3971:             $storehash{'section'} = $sec;
                   3972:         }
1.1188    raeburn  3973:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3974:                    $domain,$cnum,$cdom);
1.1184    raeburn  3975:         if (($trole ne 'st') || ($sec ne '')) {
                   3976:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3977:         }
                   3978:     }
                   3979:     return;
                   3980: }
                   3981: 
1.1184    raeburn  3982: sub domainrolelog {
                   3983:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3984:     if ($area =~ m{^/($match_domain)/$}) {
                   3985:         my $cdom = $1;
                   3986:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3987:         my $namespace = 'rolelog';
                   3988:         my %storehash = (
                   3989:                            role    => $trole,
                   3990:                            start   => $tstart,
                   3991:                            end     => $tend,
                   3992:                            context => $context,
                   3993:                         );
1.1188    raeburn  3994:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3995:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  3996:     }
                   3997:     return;
                   3998: 
                   3999: }
                   4000: 
                   4001: sub coauthorrolelog {
                   4002:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4003:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4004:         my $audom = $1;
                   4005:         my $auname = $2;
                   4006:         my $namespace = 'rolelog';
                   4007:         my %storehash = (
                   4008:                            role    => $trole,
                   4009:                            start   => $tstart,
                   4010:                            end     => $tend,
                   4011:                            context => $context,
                   4012:                         );
1.1188    raeburn  4013:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4014:                    $domain,$auname,$audom);
1.1184    raeburn  4015:     }
                   4016:     return;
                   4017: }
                   4018: 
1.351     www      4019: sub get_course_adv_roles {
1.948     raeburn  4020:     my ($cid,$codes) = @_;
1.620     albertel 4021:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4022:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4023:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4024:     my %nothide=();
1.800     albertel 4025:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4026:         if ($user !~ /:/) {
                   4027: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4028:         } else {
                   4029:             $nothide{$user}=1;
                   4030:         }
1.470     www      4031:     }
1.1219    raeburn  4032:     my @possdoms = ($coursehash{'domain'});
                   4033:     if ($coursehash{'checkforpriv'}) {
                   4034:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4035:     }
1.351     www      4036:     my %returnhash=();
                   4037:     my %dumphash=
                   4038:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4039:     my $now=time;
1.997     raeburn  4040:     my %privileged;
1.1000    raeburn  4041:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4042: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4043:         if (($tstart) && ($tstart<0)) { next; }
                   4044:         if (($tend) && ($tend<$now)) { next; }
                   4045:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4046:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4047: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4048:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4049:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4050: 	if ($role eq 'cr') { next; }
1.948     raeburn  4051:         if ($codes) {
                   4052:             if ($section) { $role .= ':'.$section; }
                   4053:             if ($returnhash{$role}) {
                   4054:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4055:             } else {
                   4056:                 $returnhash{$role}=$username.':'.$domain;
                   4057:             }
1.351     www      4058:         } else {
1.988     raeburn  4059:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4060:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4061:             if ($returnhash{$key}) {
                   4062: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4063:             } else {
                   4064:                 $returnhash{$key}=$username.':'.$domain;
                   4065:             }
1.351     www      4066:         }
1.948     raeburn  4067:     }
1.400     www      4068:     return %returnhash;
                   4069: }
                   4070: 
                   4071: sub get_my_roles {
1.937     raeburn  4072:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4073:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4074:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4075:     my (%dumphash,%nothide);
1.1086    raeburn  4076:     if ($context eq 'userroles') {
1.1166    raeburn  4077:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4078:     } else {
1.1219    raeburn  4079:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4080:         if ($hidepriv) {
                   4081:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4082:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4083:                 if ($user !~ /:/) {
                   4084:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4085:                 } else {
                   4086:                     $nothide{$user} = 1;
                   4087:                 }
                   4088:             }
                   4089:         }
1.858     raeburn  4090:     }
1.400     www      4091:     my %returnhash=();
                   4092:     my $now=time;
1.999     raeburn  4093:     my %privileged;
1.800     albertel 4094:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4095:         my ($role,$tend,$tstart);
                   4096:         if ($context eq 'userroles') {
1.1149    raeburn  4097:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4098: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4099:         } else {
                   4100:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4101:         }
1.400     www      4102:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4103:         my $status = 'active';
1.939     raeburn  4104:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4105:             $status = 'previous';
                   4106:         } 
                   4107:         if (($tstart) && ($now<$tstart)) {
                   4108:             $status = 'future';
                   4109:         }
                   4110:         if (ref($types) eq 'ARRAY') {
                   4111:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4112:                 next;
                   4113:             } 
                   4114:         } else {
                   4115:             if ($status ne 'active') {
                   4116:                 next;
                   4117:             }
                   4118:         }
1.867     raeburn  4119:         my ($rolecode,$username,$domain,$section,$area);
                   4120:         if ($context eq 'userroles') {
1.1186    raeburn  4121:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4122:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4123:         } else {
                   4124:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4125:         }
1.832     raeburn  4126:         if (ref($roledoms) eq 'ARRAY') {
                   4127:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4128:                 next;
                   4129:             }
                   4130:         }
                   4131:         if (ref($roles) eq 'ARRAY') {
                   4132:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4133:                 if ($role =~ /^cr\//) {
                   4134:                     if (!grep(/^cr$/,@{$roles})) {
                   4135:                         next;
                   4136:                     }
1.1104    raeburn  4137:                 } elsif ($role =~ /^gr\//) {
                   4138:                     if (!grep(/^gr$/,@{$roles})) {
                   4139:                         next;
                   4140:                     }
1.922     raeburn  4141:                 } else {
                   4142:                     next;
                   4143:                 }
1.832     raeburn  4144:             }
1.867     raeburn  4145:         }
1.937     raeburn  4146:         if ($hidepriv) {
1.1219    raeburn  4147:             my @privroles = ('dc','su');
1.999     raeburn  4148:             if ($context eq 'userroles') {
1.1219    raeburn  4149:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4150:             } else {
1.1219    raeburn  4151:                 my $possdoms = [$domain];
                   4152:                 if (ref($roledoms) eq 'ARRAY') {
                   4153:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4154:                 }
1.1219    raeburn  4155:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4156:                     if (!$nothide{$username.':'.$domain}) {
                   4157:                         next;
                   4158:                     }
                   4159:                 }
1.937     raeburn  4160:             }
                   4161:         }
1.933     raeburn  4162:         if ($withsec) {
                   4163:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4164:                 $tstart.':'.$tend;
                   4165:         } else {
                   4166:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4167:         }
1.832     raeburn  4168:     }
1.373     www      4169:     return %returnhash;
1.399     www      4170: }
                   4171: 
                   4172: # ----------------------------------------------------- Frontpage Announcements
                   4173: #
                   4174: #
                   4175: 
                   4176: sub postannounce {
                   4177:     my ($server,$text)=@_;
1.844     albertel 4178:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4179:     unless ($text=~/\w/) { $text=''; }
                   4180:     return &reply('setannounce:'.&escape($text),$server);
                   4181: }
                   4182: 
                   4183: sub getannounce {
1.448     albertel 4184: 
                   4185:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4186: 	my $announcement='';
1.800     albertel 4187: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4188: 	close($fh);
1.399     www      4189: 	if ($announcement=~/\w/) { 
                   4190: 	    return 
                   4191:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4192:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4193: 	} else {
                   4194: 	    return '';
                   4195: 	}
                   4196:     } else {
                   4197: 	return '';
                   4198:     }
1.351     www      4199: }
1.353     www      4200: 
                   4201: # ---------------------------------------------------------- Course ID routines
                   4202: # Deal with domain's nohist_courseid.db files
                   4203: #
                   4204: 
                   4205: sub courseidput {
1.921     raeburn  4206:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4207:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4208:     my $outcome;
                   4209:     if ($caller eq 'timeonly') {
                   4210:         my $cids = '';
                   4211:         foreach my $item (keys(%$storehash)) {
                   4212:             $cids.=&escape($item).'&';
                   4213:         }
                   4214:         $cids=~s/\&$//;
                   4215:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4216:                           $coursehome);       
                   4217:     } else {
                   4218:         my $items = '';
                   4219:         foreach my $item (keys(%$storehash)) {
                   4220:             $items.= &escape($item).'='.
                   4221:                      &freeze_escape($$storehash{$item}).'&';
                   4222:         }
                   4223:         $items=~s/\&$//;
                   4224:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4225:                           $coursehome);
1.918     raeburn  4226:     }
                   4227:     if ($outcome eq 'unknown_cmd') {
                   4228:         my $what;
                   4229:         foreach my $cid (keys(%$storehash)) {
                   4230:             $what .= &escape($cid).'=';
1.921     raeburn  4231:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4232:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4233:             }
                   4234:             $what =~ s/\:$/&/;
                   4235:         }
                   4236:         $what =~ s/\&$//;  
                   4237:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4238:     } else {
                   4239:         return $outcome;
                   4240:     }
1.353     www      4241: }
                   4242: 
                   4243: sub courseiddump {
1.921     raeburn  4244:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4245:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4246:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4247:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
                   4248:         $hasuniquecode)=@_;
1.918     raeburn  4249:     my $as_hash = 1;
                   4250:     my %returnhash;
                   4251:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4252:     my %libserv = &all_library();
                   4253:     foreach my $tryserver (keys(%libserv)) {
                   4254:         if ( (  $hostidflag == 1 
                   4255: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4256: 	     || (!defined($hostidflag)) ) {
                   4257: 
1.918     raeburn  4258: 	    if (($domfilter eq '') ||
                   4259: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4260:                 my $rep;
                   4261:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4262:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4263:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4264:                                 &escape($descfilter), &escape($instcodefilter), 
                   4265:                                 &escape($ownerfilter), &escape($coursefilter),
                   4266:                                 &escape($typefilter), &escape($regexp_ok), 
                   4267:                                 $as_hash, &escape($selfenrollonly), 
                   4268:                                 &escape($catfilter), $showhidden, $caller, 
                   4269:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4270:                                 &escape($createdbefore), &escape($createdafter), 
1.1247    raeburn  4271:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1180    droeschl 4272:                 } else {
                   4273:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4274:                              $sincefilter.':'.&escape($descfilter).':'.
                   4275:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4276:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4277:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4278:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4279:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4280:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4281:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1247    raeburn  4282:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1180    droeschl 4283:                              $tryserver);
                   4284:                 }
                   4285:                      
1.918     raeburn  4286:                 my @pairs=split(/\&/,$rep);
                   4287:                 foreach my $item (@pairs) {
                   4288:                     my ($key,$value)=split(/\=/,$item,2);
                   4289:                     $key = &unescape($key);
                   4290:                     next if ($key =~ /^error: 2 /);
                   4291:                     my $result = &thaw_unescape($value);
                   4292:                     if (ref($result) eq 'HASH') {
                   4293:                         $returnhash{$key}=$result;
                   4294:                     } else {
1.921     raeburn  4295:                         my @responses = split(/:/,$value);
                   4296:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4297:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4298:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4299:                         }
1.1008    raeburn  4300:                     }
1.353     www      4301:                 }
                   4302:             }
                   4303:         }
                   4304:     }
                   4305:     return %returnhash;
                   4306: }
                   4307: 
1.1055    raeburn  4308: sub courselastaccess {
                   4309:     my ($cdom,$cnum,$hostidref) = @_;
                   4310:     my %returnhash;
                   4311:     if ($cdom && $cnum) {
                   4312:         my $chome = &homeserver($cnum,$cdom);
                   4313:         if ($chome ne 'no_host') {
                   4314:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4315:             &extract_lastaccess(\%returnhash,$rep);
                   4316:         }
                   4317:     } else {
                   4318:         if (!$cdom) { $cdom=''; }
                   4319:         my %libserv = &all_library();
                   4320:         foreach my $tryserver (keys(%libserv)) {
                   4321:             if (ref($hostidref) eq 'ARRAY') {
                   4322:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4323:             } 
                   4324:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4325:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4326:                 &extract_lastaccess(\%returnhash,$rep);
                   4327:             }
                   4328:         }
                   4329:     }
                   4330:     return %returnhash;
                   4331: }
                   4332: 
                   4333: sub extract_lastaccess {
                   4334:     my ($returnhash,$rep) = @_;
                   4335:     if (ref($returnhash) eq 'HASH') {
                   4336:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4337:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4338:                  $rep eq '') {
                   4339:             my @pairs=split(/\&/,$rep);
                   4340:             foreach my $item (@pairs) {
                   4341:                 my ($key,$value)=split(/\=/,$item,2);
                   4342:                 $key = &unescape($key);
                   4343:                 next if ($key =~ /^error: 2 /);
                   4344:                 $returnhash->{$key} = &thaw_unescape($value);
                   4345:             }
                   4346:         }
                   4347:     }
                   4348:     return;
                   4349: }
                   4350: 
1.658     raeburn  4351: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4352: 
                   4353: sub dcmailput {
1.685     raeburn  4354:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4355:     my $status = &Apache::lonnet::critical(
1.740     www      4356:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4357:        &escape($message),$server);
1.662     raeburn  4358:     return $status;
                   4359: }
                   4360: 
1.658     raeburn  4361: sub dcmaildump {
                   4362:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4363:     my %returnhash=();
1.846     albertel 4364: 
                   4365:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4366:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4367:                                                          &escape($enddate).':';
                   4368: 	my @esc_senders=map { &escape($_)} @$senders;
                   4369: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4370: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4371:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4372:             if (($key) && ($value)) {
                   4373:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4374:             }
                   4375:         }
                   4376:     }
                   4377:     return %returnhash;
                   4378: }
1.662     raeburn  4379: # ---------------------------------------------------------- Domain roles
                   4380: 
                   4381: sub get_domain_roles {
                   4382:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4383:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4384:         $startdate = '.';
                   4385:     }
1.1018    raeburn  4386:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4387:         $enddate = '.';
                   4388:     }
1.922     raeburn  4389:     my $rolelist;
                   4390:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4391:         $rolelist = join('&',@{$roles});
1.922     raeburn  4392:     }
1.662     raeburn  4393:     my %personnel = ();
1.841     albertel 4394: 
                   4395:     my %servers = &get_servers($dom,'library');
                   4396:     foreach my $tryserver (keys(%servers)) {
                   4397: 	%{$personnel{$tryserver}}=();
                   4398: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4399: 					    &escape($startdate).':'.
                   4400: 					    &escape($enddate).':'.
                   4401: 					    &escape($rolelist), $tryserver))) {
                   4402: 	    my ($key,$value) = split(/\=/,$line,2);
                   4403: 	    if (($key) && ($value)) {
                   4404: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4405: 	    }
                   4406: 	}
1.662     raeburn  4407:     }
                   4408:     return %personnel;
                   4409: }
1.658     raeburn  4410: 
1.1057    www      4411: # ----------------------------------------------------------- Interval timing 
1.149     www      4412: 
1.1153    www      4413: {
                   4414: # Caches needed for speedup of navmaps
                   4415: # We don't want to cache this for very long at all (5 seconds at most)
                   4416: # 
                   4417: # The user for whom we cache
                   4418: my $cachedkey='';
                   4419: # The cached times for this user
                   4420: my %cachedtimes=();
                   4421: # When this was last done
                   4422: my $cachedtime=();
                   4423: 
                   4424: sub load_all_first_access {
1.1154    raeburn  4425:     my ($uname,$udom)=@_;
1.1156    www      4426:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4427:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4428:         return;
                   4429:     }
                   4430:     $cachedtime=time;
                   4431:     $cachedkey=$uname.':'.$udom;
                   4432:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4433: }
                   4434: 
1.504     albertel 4435: sub get_first_access {
1.1162    raeburn  4436:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4437:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4438:     if ($argsymb) { $symb=$argsymb; }
                   4439:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4440:     if ($argmap) { $map = $argmap; }
1.926     albertel 4441:     if ($type eq 'course') {
                   4442: 	$res='course';
                   4443:     } elsif ($type eq 'map') {
1.588     albertel 4444: 	$res=&symbread($map);
                   4445:     } else {
                   4446: 	$res=$symb;
                   4447:     }
1.1153    www      4448:     &load_all_first_access($uname,$udom);
                   4449:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4450: }
                   4451: 
                   4452: sub set_first_access {
1.1162    raeburn  4453:     my ($type,$interval)=@_;
1.790     albertel 4454:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4455:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4456:     if ($type eq 'course') {
                   4457: 	$res='course';
                   4458:     } elsif ($type eq 'map') {
1.588     albertel 4459: 	$res=&symbread($map);
                   4460:     } else {
                   4461: 	$res=$symb;
                   4462:     }
1.1153    www      4463:     $cachedkey='';
1.1162    raeburn  4464:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4465:     if (!$firstaccess) {
1.1162    raeburn  4466:         my $start = time;
                   4467: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4468:                           $udom,$uname);
                   4469:         if ($putres eq 'ok') {
                   4470:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4471:                  $udom,$uname); 
                   4472:             &appenv(
                   4473:                      {
                   4474:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4475:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4476:                      }
                   4477:                   );
                   4478:         }
                   4479:         return $putres;
1.505     albertel 4480:     }
                   4481:     return 'already_set';
1.504     albertel 4482: }
1.1153    www      4483: }
1.110     www      4484: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4485: 
                   4486: sub expirespread {
                   4487:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4488:     my $cid=$env{'request.course.id'}; 
1.110     www      4489:     if ($cid) {
                   4490:        my $now=time;
                   4491:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4492:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4493:                             $env{'course.'.$cid.'.num'}.
1.110     www      4494: 	        	    ':nohist_expirationdates:'.
                   4495:                             &escape($key).'='.$now,
1.620     albertel 4496:                             $env{'course.'.$cid.'.home'})
1.110     www      4497:     }
                   4498:     return 'ok';
1.14      www      4499: }
                   4500: 
1.109     www      4501: # ----------------------------------------------------- Devalidate Spreadsheets
                   4502: 
                   4503: sub devalidate {
1.325     www      4504:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4505:     my $cid=$env{'request.course.id'}; 
1.109     www      4506:     if ($cid) {
1.391     matthew  4507:         # delete the stored spreadsheets for
                   4508:         # - the student level sheet of this user in course's homespace
                   4509:         # - the assessment level sheet for this resource 
                   4510:         #   for this user in user's homespace
1.553     albertel 4511: 	# - current conditional state info
1.325     www      4512: 	my $key=$uname.':'.$udom.':';
1.109     www      4513:         my $status=
1.299     matthew  4514: 	    &del('nohist_calculatedsheets',
1.391     matthew  4515: 		 [$key.'studentcalc:'],
1.620     albertel 4516: 		 $env{'course.'.$cid.'.domain'},
                   4517: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4518: 		.' '.
                   4519: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4520: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4521:         unless ($status eq 'ok ok') {
                   4522:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4523:                     $uname.' at '.$udom.' for '.
1.109     www      4524: 		    $symb.': '.$status);
1.133     albertel 4525:         }
1.553     albertel 4526: 	&delenv('user.state.'.$cid);
1.109     www      4527:     }
                   4528: }
                   4529: 
1.265     albertel 4530: sub get_scalar {
                   4531:     my ($string,$end) = @_;
                   4532:     my $value;
                   4533:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4534: 	$value = $1;
                   4535:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4536: 	$value = $1;
                   4537:     }
                   4538:     return &unescape($value);
                   4539: }
                   4540: 
                   4541: sub array2str {
                   4542:   my (@array) = @_;
                   4543:   my $result=&arrayref2str(\@array);
                   4544:   $result=~s/^__ARRAY_REF__//;
                   4545:   $result=~s/__END_ARRAY_REF__$//;
                   4546:   return $result;
                   4547: }
                   4548: 
1.204     albertel 4549: sub arrayref2str {
                   4550:   my ($arrayref) = @_;
1.265     albertel 4551:   my $result='__ARRAY_REF__';
1.204     albertel 4552:   foreach my $elem (@$arrayref) {
1.265     albertel 4553:     if(ref($elem) eq 'ARRAY') {
                   4554:       $result.=&arrayref2str($elem).'&';
                   4555:     } elsif(ref($elem) eq 'HASH') {
                   4556:       $result.=&hashref2str($elem).'&';
                   4557:     } elsif(ref($elem)) {
                   4558:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4559:     } else {
                   4560:       $result.=&escape($elem).'&';
                   4561:     }
                   4562:   }
                   4563:   $result=~s/\&$//;
1.265     albertel 4564:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4565:   return $result;
                   4566: }
                   4567: 
1.168     albertel 4568: sub hash2str {
1.204     albertel 4569:   my (%hash) = @_;
                   4570:   my $result=&hashref2str(\%hash);
1.265     albertel 4571:   $result=~s/^__HASH_REF__//;
                   4572:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4573:   return $result;
                   4574: }
                   4575: 
                   4576: sub hashref2str {
                   4577:   my ($hashref)=@_;
1.265     albertel 4578:   my $result='__HASH_REF__';
1.800     albertel 4579:   foreach my $key (sort(keys(%$hashref))) {
                   4580:     if (ref($key) eq 'ARRAY') {
                   4581:       $result.=&arrayref2str($key).'=';
                   4582:     } elsif (ref($key) eq 'HASH') {
                   4583:       $result.=&hashref2str($key).'=';
                   4584:     } elsif (ref($key)) {
1.265     albertel 4585:       $result.='=';
1.800     albertel 4586:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4587:     } else {
1.1132    raeburn  4588: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4589:     }
                   4590: 
1.800     albertel 4591:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4592:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4593:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4594:       $result.=&hashref2str($hashref->{$key}).'&';
                   4595:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4596:        $result.='&';
1.800     albertel 4597:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4598:     } else {
1.800     albertel 4599:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4600:     }
                   4601:   }
1.168     albertel 4602:   $result=~s/\&$//;
1.265     albertel 4603:   $result .= '__END_HASH_REF__';
1.168     albertel 4604:   return $result;
                   4605: }
                   4606: 
                   4607: sub str2hash {
1.265     albertel 4608:     my ($string)=@_;
                   4609:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4610:     return %$hash;
                   4611: }
                   4612: 
                   4613: sub str2hashref {
1.168     albertel 4614:   my ($string) = @_;
1.265     albertel 4615: 
                   4616:   my %hash;
                   4617: 
                   4618:   if($string !~ /^__HASH_REF__/) {
                   4619:       if (! ($string eq '' || !defined($string))) {
                   4620: 	  $hash{'error'}='Not hash reference';
                   4621:       }
                   4622:       return (\%hash, $string);
                   4623:   }
                   4624: 
                   4625:   $string =~ s/^__HASH_REF__//;
                   4626: 
                   4627:   while($string !~ /^__END_HASH_REF__/) {
                   4628:       #key
                   4629:       my $key='';
                   4630:       if($string =~ /^__HASH_REF__/) {
                   4631:           ($key, $string)=&str2hashref($string);
                   4632:           if(defined($key->{'error'})) {
                   4633:               $hash{'error'}='Bad data';
                   4634:               return (\%hash, $string);
                   4635:           }
                   4636:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4637:           ($key, $string)=&str2arrayref($string);
                   4638:           if($key->[0] eq 'Array reference error') {
                   4639:               $hash{'error'}='Bad data';
                   4640:               return (\%hash, $string);
                   4641:           }
                   4642:       } else {
                   4643:           $string =~ s/^(.*?)=//;
1.267     albertel 4644: 	  $key=&unescape($1);
1.265     albertel 4645:       }
                   4646:       $string =~ s/^=//;
                   4647: 
                   4648:       #value
                   4649:       my $value='';
                   4650:       if($string =~ /^__HASH_REF__/) {
                   4651:           ($value, $string)=&str2hashref($string);
                   4652:           if(defined($value->{'error'})) {
                   4653:               $hash{'error'}='Bad data';
                   4654:               return (\%hash, $string);
                   4655:           }
                   4656:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4657:           ($value, $string)=&str2arrayref($string);
                   4658:           if($value->[0] eq 'Array reference error') {
                   4659:               $hash{'error'}='Bad data';
                   4660:               return (\%hash, $string);
                   4661:           }
                   4662:       } else {
                   4663: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4664:       }
                   4665:       $string =~ s/^&//;
                   4666: 
                   4667:       $hash{$key}=$value;
1.204     albertel 4668:   }
1.265     albertel 4669: 
                   4670:   $string =~ s/^__END_HASH_REF__//;
                   4671: 
                   4672:   return (\%hash, $string);
1.204     albertel 4673: }
                   4674: 
                   4675: sub str2array {
1.265     albertel 4676:     my ($string)=@_;
                   4677:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4678:     return @$array;
                   4679: }
                   4680: 
                   4681: sub str2arrayref {
1.204     albertel 4682:   my ($string) = @_;
1.265     albertel 4683:   my @array;
                   4684: 
                   4685:   if($string !~ /^__ARRAY_REF__/) {
                   4686:       if (! ($string eq '' || !defined($string))) {
                   4687: 	  $array[0]='Array reference error';
                   4688:       }
                   4689:       return (\@array, $string);
                   4690:   }
                   4691: 
                   4692:   $string =~ s/^__ARRAY_REF__//;
                   4693: 
                   4694:   while($string !~ /^__END_ARRAY_REF__/) {
                   4695:       my $value='';
                   4696:       if($string =~ /^__HASH_REF__/) {
                   4697:           ($value, $string)=&str2hashref($string);
                   4698:           if(defined($value->{'error'})) {
                   4699:               $array[0] ='Array reference error';
                   4700:               return (\@array, $string);
                   4701:           }
                   4702:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4703:           ($value, $string)=&str2arrayref($string);
                   4704:           if($value->[0] eq 'Array reference error') {
                   4705:               $array[0] ='Array reference error';
                   4706:               return (\@array, $string);
                   4707:           }
                   4708:       } else {
                   4709: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4710:       }
                   4711:       $string =~ s/^&//;
                   4712: 
                   4713:       push(@array, $value);
1.191     harris41 4714:   }
1.265     albertel 4715: 
                   4716:   $string =~ s/^__END_ARRAY_REF__//;
                   4717: 
                   4718:   return (\@array, $string);
1.168     albertel 4719: }
                   4720: 
1.167     albertel 4721: # -------------------------------------------------------------------Temp Store
                   4722: 
1.168     albertel 4723: sub tmpreset {
                   4724:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4725:   if (!$symb) {
                   4726:     $symb=&symbread();
1.620     albertel 4727:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4728:   }
                   4729:   $symb=escape($symb);
                   4730: 
1.620     albertel 4731:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4732:   $namespace=~s/\//\_/g;
                   4733:   $namespace=~s/\W//g;
                   4734: 
1.620     albertel 4735:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4736:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4737:   if ($domain eq 'public' && $stuname eq 'public') {
                   4738:       $stuname=$ENV{'REMOTE_ADDR'};
                   4739:   }
1.1117    foxr     4740:   my $path=LONCAPA::tempdir();
1.168     albertel 4741:   my %hash;
                   4742:   if (tie(%hash,'GDBM_File',
                   4743: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4744: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4745:     foreach my $key (keys(%hash)) {
1.180     albertel 4746:       if ($key=~ /:$symb/) {
1.168     albertel 4747: 	delete($hash{$key});
                   4748:       }
                   4749:     }
                   4750:   }
                   4751: }
                   4752: 
1.167     albertel 4753: sub tmpstore {
1.168     albertel 4754:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4755: 
                   4756:   if (!$symb) {
                   4757:     $symb=&symbread();
1.620     albertel 4758:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4759:   }
                   4760:   $symb=escape($symb);
                   4761: 
                   4762:   if (!$namespace) {
                   4763:     # I don't think we would ever want to store this for a course.
                   4764:     # it seems this will only be used if we don't have a course.
1.620     albertel 4765:     #$namespace=$env{'request.course.id'};
1.168     albertel 4766:     #if (!$namespace) {
1.620     albertel 4767:       $namespace=$env{'request.state'};
1.168     albertel 4768:     #}
                   4769:   }
                   4770:   $namespace=~s/\//\_/g;
                   4771:   $namespace=~s/\W//g;
1.620     albertel 4772:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4773:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4774:   if ($domain eq 'public' && $stuname eq 'public') {
                   4775:       $stuname=$ENV{'REMOTE_ADDR'};
                   4776:   }
1.168     albertel 4777:   my $now=time;
                   4778:   my %hash;
1.1117    foxr     4779:   my $path=LONCAPA::tempdir();
1.168     albertel 4780:   if (tie(%hash,'GDBM_File',
                   4781: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4782: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4783:     $hash{"version:$symb"}++;
                   4784:     my $version=$hash{"version:$symb"};
                   4785:     my $allkeys=''; 
                   4786:     foreach my $key (keys(%$storehash)) {
                   4787:       $allkeys.=$key.':';
1.591     albertel 4788:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4789:     }
                   4790:     $hash{"$version:$symb:timestamp"}=$now;
                   4791:     $allkeys.='timestamp';
                   4792:     $hash{"$version:keys:$symb"}=$allkeys;
                   4793:     if (untie(%hash)) {
                   4794:       return 'ok';
                   4795:     } else {
                   4796:       return "error:$!";
                   4797:     }
                   4798:   } else {
                   4799:     return "error:$!";
                   4800:   }
                   4801: }
1.167     albertel 4802: 
1.168     albertel 4803: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4804: 
1.168     albertel 4805: sub tmprestore {
                   4806:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4807: 
1.168     albertel 4808:   if (!$symb) {
                   4809:     $symb=&symbread();
1.620     albertel 4810:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4811:   }
                   4812:   $symb=escape($symb);
                   4813: 
1.620     albertel 4814:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4815: 
1.620     albertel 4816:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4817:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4818:   if ($domain eq 'public' && $stuname eq 'public') {
                   4819:       $stuname=$ENV{'REMOTE_ADDR'};
                   4820:   }
1.168     albertel 4821:   my %returnhash;
                   4822:   $namespace=~s/\//\_/g;
                   4823:   $namespace=~s/\W//g;
                   4824:   my %hash;
1.1117    foxr     4825:   my $path=LONCAPA::tempdir();
1.168     albertel 4826:   if (tie(%hash,'GDBM_File',
                   4827: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4828: 	  &GDBM_READER(),0640)) {
1.168     albertel 4829:     my $version=$hash{"version:$symb"};
                   4830:     $returnhash{'version'}=$version;
                   4831:     my $scope;
                   4832:     for ($scope=1;$scope<=$version;$scope++) {
                   4833:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4834:       my @keys=split(/:/,$vkeys);
                   4835:       my $key;
                   4836:       $returnhash{"$scope:keys"}=$vkeys;
                   4837:       foreach $key (@keys) {
1.591     albertel 4838: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4839: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4840:       }
                   4841:     }
1.168     albertel 4842:     if (!(untie(%hash))) {
                   4843:       return "error:$!";
                   4844:     }
                   4845:   } else {
                   4846:     return "error:$!";
                   4847:   }
                   4848:   return %returnhash;
1.167     albertel 4849: }
                   4850: 
1.9       www      4851: # ----------------------------------------------------------------------- Store
                   4852: 
                   4853: sub store {
1.124     www      4854:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4855:     my $home='';
                   4856: 
1.168     albertel 4857:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4858: 
1.213     www      4859:     $symb=&symbclean($symb);
1.122     albertel 4860:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4861: 
1.620     albertel 4862:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4863:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4864: 
                   4865:     &devalidate($symb,$stuname,$domain);
1.109     www      4866: 
                   4867:     $symb=escape($symb);
1.187     www      4868:     if (!$namespace) { 
1.620     albertel 4869:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4870:           return ''; 
                   4871:        } 
                   4872:     }
1.620     albertel 4873:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4874: 
                   4875:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4876:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4877: 
1.12      www      4878:     my $namevalue='';
1.800     albertel 4879:     foreach my $key (keys(%$storehash)) {
                   4880:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4881:     }
1.12      www      4882:     $namevalue=~s/\&$//;
1.187     www      4883:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4884:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4885: }
                   4886: 
1.47      www      4887: # -------------------------------------------------------------- Critical Store
                   4888: 
                   4889: sub cstore {
1.124     www      4890:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4891:     my $home='';
                   4892: 
1.168     albertel 4893:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4894: 
1.213     www      4895:     $symb=&symbclean($symb);
1.122     albertel 4896:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4897: 
1.620     albertel 4898:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4899:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4900: 
                   4901:     &devalidate($symb,$stuname,$domain);
1.109     www      4902: 
                   4903:     $symb=escape($symb);
1.187     www      4904:     if (!$namespace) { 
1.620     albertel 4905:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4906:           return ''; 
                   4907:        } 
                   4908:     }
1.620     albertel 4909:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4910: 
                   4911:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4912:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4913: 
1.47      www      4914:     my $namevalue='';
1.800     albertel 4915:     foreach my $key (keys(%$storehash)) {
                   4916:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4917:     }
1.47      www      4918:     $namevalue=~s/\&$//;
1.187     www      4919:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4920:     return critical
                   4921:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4922: }
                   4923: 
1.9       www      4924: # --------------------------------------------------------------------- Restore
                   4925: 
                   4926: sub restore {
1.124     www      4927:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4928:     my $home='';
                   4929: 
1.168     albertel 4930:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4931: 
1.122     albertel 4932:     if (!$symb) {
1.1224    raeburn  4933:         return if ($namespace eq 'courserequests');
                   4934:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 4935:     } else {
1.1224    raeburn  4936:         unless ($namespace eq 'courserequests') {
                   4937:             $symb=&escape(&symbclean($symb));
                   4938:         }
1.122     albertel 4939:     }
1.188     www      4940:     if (!$namespace) { 
1.620     albertel 4941:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4942:           return ''; 
                   4943:        } 
                   4944:     }
1.620     albertel 4945:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4946:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4947:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4948:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4949: 
1.12      www      4950:     my %returnhash=();
1.800     albertel 4951:     foreach my $line (split(/\&/,$answer)) {
                   4952: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4953:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4954:     }
1.75      www      4955:     my $version;
                   4956:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4957:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4958:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4959:        }
1.75      www      4960:     }
1.13      www      4961:     return %returnhash;
1.34      www      4962: }
                   4963: 
                   4964: # ---------------------------------------------------------- Course Description
1.1118    foxr     4965: #
                   4966: #  
1.34      www      4967: 
                   4968: sub coursedescription {
1.731     albertel 4969:     my ($courseid,$args)=@_;
1.34      www      4970:     $courseid=~s/^\///;
1.49      www      4971:     $courseid=~s/\_/\//g;
1.34      www      4972:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4973:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4974:     my $normalid=$cdomain.'_'.$cnum;
                   4975:     # need to always cache even if we get errors otherwise we keep 
                   4976:     # trying and trying and trying to get the course description.
                   4977:     my %envhash=();
                   4978:     my %returnhash=();
1.731     albertel 4979:     
                   4980:     my $expiretime=600;
                   4981:     if ($env{'request.course.id'} eq $normalid) {
                   4982: 	$expiretime=120;
                   4983:     }
                   4984: 
                   4985:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4986:     if (!$args->{'freshen_cache'}
                   4987: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4988: 	foreach my $key (keys(%env)) {
                   4989: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4990: 	    my ($setting) = $1;
                   4991: 	    $returnhash{$setting} = $env{$key};
                   4992: 	}
                   4993: 	return %returnhash;
                   4994:     }
                   4995: 
1.1118    foxr     4996:     # get the data again
                   4997: 
1.731     albertel 4998:     if (!$args->{'one_time'}) {
                   4999: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5000:     }
1.811     albertel 5001: 
1.34      www      5002:     if ($chome ne 'no_host') {
1.302     albertel 5003:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5004:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5005: 	   my $username = $env{'user.name'}; # Defult username
                   5006: 	   if(defined $args->{'user'}) {
                   5007: 	       $username = $args->{'user'};
                   5008: 	   }
1.129     albertel 5009:            $returnhash{'home'}= $chome;
                   5010: 	   $returnhash{'domain'} = $cdomain;
                   5011: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5012:            if (!defined($returnhash{'type'})) {
                   5013:                $returnhash{'type'} = 'Course';
                   5014:            }
1.130     albertel 5015:            while (my ($name,$value) = each %returnhash) {
1.53      www      5016:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5017:            }
1.270     www      5018:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5019:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5020: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5021:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5022:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5023:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5024:        }
                   5025:     }
1.731     albertel 5026:     if (!$args->{'one_time'}) {
1.949     raeburn  5027: 	&appenv(\%envhash);
1.731     albertel 5028:     }
1.302     albertel 5029:     return %returnhash;
1.461     www      5030: }
                   5031: 
1.1080    raeburn  5032: sub update_released_required {
                   5033:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5034:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5035:         $cid = $env{'request.course.id'};
                   5036:         $cdom = $env{'course.'.$cid.'.domain'};
                   5037:         $cnum = $env{'course.'.$cid.'.num'};
                   5038:         $chome = $env{'course.'.$cid.'.home'};
                   5039:     }
                   5040:     if ($needsrelease) {
                   5041:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5042:         my $needsupdate;
                   5043:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5044:             $needsupdate = 1;
                   5045:         } else {
                   5046:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5047:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5048:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5049:                 $needsupdate = 1;
                   5050:             }
                   5051:         }
                   5052:         if ($needsupdate) {
                   5053:             my %needshash = (
                   5054:                              'internal.releaserequired' => $needsrelease,
                   5055:                             );
                   5056:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5057:             if ($putresult eq 'ok') {
                   5058:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5059:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5060:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5061:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5062:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5063:                 }
                   5064:             }
                   5065:         }
                   5066:     }
                   5067:     return;
                   5068: }
                   5069: 
1.461     www      5070: # -------------------------------------------------See if a user is privileged
                   5071: 
                   5072: sub privileged {
1.1219    raeburn  5073:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5074:     my $now = time;
1.1219    raeburn  5075:     my $roles;
                   5076:     if (ref($possroles) eq 'ARRAY') {
                   5077:         $roles = $possroles; 
                   5078:     } else {
                   5079:         $roles = ['dc','su'];
                   5080:     }
                   5081:     if (ref($possdomains) eq 'ARRAY') {
                   5082:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5083:         foreach my $dom (@{$possdomains}) {
                   5084:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5085:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5086:                 foreach my $role (@{$roles}) {
                   5087:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5088:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5089:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5090:                             return 1 unless (($end && $end < $now) ||
                   5091:                                              ($start && $start > $now));
                   5092:                         }
                   5093:                     }
                   5094:                 }
                   5095:             }
                   5096:         }
                   5097:     } else {
                   5098:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5099:         my $now = time;
1.1170    droeschl 5100: 
1.1219    raeburn  5101:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170    droeschl 5102:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5103:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5104:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5105:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5106:             }
1.1219    raeburn  5107:         }
                   5108:     }
                   5109:     return 0;
                   5110: }
1.1170    droeschl 5111: 
1.1219    raeburn  5112: sub privileged_by_domain {
                   5113:     my ($domains,$roles) = @_;
                   5114:     my %privileged = ();
                   5115:     my $cachetime = 60*60*24;
                   5116:     my $now = time;
                   5117:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5118:         return %privileged;
                   5119:     }
                   5120:     foreach my $dom (@{$domains}) {
                   5121:         next if (ref($privileged{$dom}) eq 'HASH');
                   5122:         my $needroles;
                   5123:         foreach my $role (@{$roles}) {
                   5124:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5125:             if (defined($cached)) {
                   5126:                 if (ref($result) eq 'HASH') {
                   5127:                     $privileged{$dom}{$role} = $result;
                   5128:                 }
                   5129:             } else {
                   5130:                 $needroles = 1;
                   5131:             }
                   5132:         }
                   5133:         if ($needroles) {
                   5134:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5135:             $privileged{$dom} = {};
                   5136:             foreach my $server (keys(%dompersonnel)) {
                   5137:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5138:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5139:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5140:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5141:                         next if ($end && $end < $now);
                   5142:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5143:                             $dompersonnel{$server}{$item};
                   5144:                     }
                   5145:                 }
                   5146:             }
                   5147:             if (ref($privileged{$dom}) eq 'HASH') {
                   5148:                 foreach my $role (@{$roles}) {
                   5149:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5150:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5151:                     } else {
                   5152:                         my %hash = ();
                   5153:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5154:                     }
                   5155:                 }
                   5156:             }
                   5157:         }
                   5158:     }
                   5159:     return %privileged;
1.9       www      5160: }
1.1       albertel 5161: 
1.103     harris41 5162: # -------------------------------------------------------- Get user privileges
1.11      www      5163: 
                   5164: sub rolesinit {
1.1169    droeschl 5165:     my ($domain, $username) = @_;
                   5166:     my %userroles = ('user.login.time' => time);
                   5167:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5168: 
                   5169:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5170:     # also, blocking can be triggered by an activating timer
                   5171:     # it's saved in the user's %env.
                   5172:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5173:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5174:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5175:         %timerintchk, %timerintenv);
                   5176: 
1.1162    raeburn  5177:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5178:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5179:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5180:     }
1.1169    droeschl 5181: 
1.1162    raeburn  5182:     foreach my $key (keys(%timerinterval)) {
                   5183:         my ($cid,$rest) = split(/\0/,$key);
                   5184:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5185:     }
1.1169    droeschl 5186: 
1.11      www      5187:     my %allroles=();
1.1162    raeburn  5188:     my %allgroups=();
1.11      www      5189: 
1.1169    droeschl 5190:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   5191:         my $role = $rolesdump{$area};
                   5192:         $area =~ s/\_\w\w$//;
                   5193: 
                   5194:         my ($trole, $tend, $tstart, $group_privs);
                   5195: 
                   5196:         if ($role =~ /^cr/) {
                   5197:         # Custom role, defined by a user 
                   5198:         # e.g., user.role.cr/msu/smith/mynewrole
                   5199:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5200:                 $trole = $1;
                   5201:                 ($tend, $tstart) = split('_', $2);
                   5202:             } else {
                   5203:                 $trole = $role;
                   5204:             }
                   5205:         } elsif ($role =~ m|^gr/|) {
                   5206:         # Role of member in a group, defined within a course/community
                   5207:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5208:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5209:             next if $tstart eq '-1';
                   5210:             ($trole, $group_privs) = split(/\//, $trole);
                   5211:             $group_privs = &unescape($group_privs);
                   5212:         } else {
                   5213:         # Just a normal role, defined in roles.tab
                   5214:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5215:         }
                   5216: 
                   5217:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5218:                  $username);
                   5219:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5220: 
                   5221:         # role expired or not available yet?
                   5222:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5223:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5224: 
                   5225:         next if $area eq '' or $trole eq '';
                   5226: 
                   5227:         my $spec = "$trole.$area";
                   5228:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5229: 
                   5230:         if ($trole =~ /^cr\//) {
                   5231:         # Custom role, defined by a user
                   5232:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5233:         } elsif ($trole eq 'gr') {
                   5234:         # Role of a member in a group, defined within a course/community
                   5235:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5236:             next;
                   5237:         } else {
                   5238:         # Normal role, defined in roles.tab
                   5239:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5240:         }
                   5241: 
                   5242:         my $cid = $tdomain.'_'.$trest;
                   5243:         unless ($firstaccchk{$cid}) {
                   5244:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5245:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5246:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5247:                         $coursetimerstarts{$cid}{$item}; 
                   5248:                 }
                   5249:             }
                   5250:             $firstaccchk{$cid} = 1;
                   5251:         }
                   5252:         unless ($timerintchk{$cid}) {
                   5253:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5254:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5255:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5256:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5257:                 }
1.12      www      5258:             }
1.1169    droeschl 5259:             $timerintchk{$cid} = 1;
1.191     harris41 5260:         }
1.11      www      5261:     }
1.1169    droeschl 5262: 
                   5263:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5264:         \%allroles, \%allgroups);
                   5265:     $env{'user.adv'} = $userroles{'user.adv'};
                   5266: 
1.1162    raeburn  5267:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5268: }
                   5269: 
1.567     raeburn  5270: sub set_arearole {
1.1215    raeburn  5271:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5272:     unless ($nolog) {
1.567     raeburn  5273: # log the associated role with the area
1.1215    raeburn  5274:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5275:     }
1.743     albertel 5276:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5277: }
                   5278: 
                   5279: sub custom_roleprivs {
                   5280:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5281:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5282:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5283:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5284:         my ($rdummy,$roledef)=
                   5285:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5286:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5287:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5288:             if (defined($syspriv)) {
1.1043    raeburn  5289:                 if ($trest =~ /^$match_community$/) {
                   5290:                     $syspriv =~ s/bre\&S//; 
                   5291:                 }
1.567     raeburn  5292:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5293:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5294:             }
                   5295:             if ($tdomain ne '') {
                   5296:                 if (defined($dompriv)) {
                   5297:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5298:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5299:                 }
                   5300:                 if (($trest ne '') && (defined($coursepriv))) {
                   5301:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5302:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5303:                 }
                   5304:             }
                   5305:         }
                   5306:     }
                   5307: }
                   5308: 
1.678     raeburn  5309: sub group_roleprivs {
                   5310:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5311:     my $access = 1;
                   5312:     my $now = time;
                   5313:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5314:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5315:     if ($access) {
1.811     albertel 5316:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5317:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5318:     }
                   5319: }
1.567     raeburn  5320: 
                   5321: sub standard_roleprivs {
                   5322:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5323:     if (defined($pr{$trole.':s'})) {
                   5324:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5325:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5326:     }
                   5327:     if ($tdomain ne '') {
                   5328:         if (defined($pr{$trole.':d'})) {
                   5329:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5330:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5331:         }
                   5332:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5333:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5334:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5335:         }
                   5336:     }
                   5337: }
                   5338: 
                   5339: sub set_userprivs {
1.1064    raeburn  5340:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5341:     my $author=0;
                   5342:     my $adv=0;
1.678     raeburn  5343:     my %grouproles = ();
                   5344:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5345:         my @groupkeys; 
1.1000    raeburn  5346:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5347:             push(@groupkeys,$role);
                   5348:         }
                   5349:         if (ref($groups_roles) eq 'HASH') {
                   5350:             foreach my $key (keys(%{$groups_roles})) {
                   5351:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5352:                     push(@groupkeys,$key);
                   5353:                 }
                   5354:             }
                   5355:         }
                   5356:         if (@groupkeys > 0) {
                   5357:             foreach my $role (@groupkeys) {
                   5358:                 my ($trole,$area,$sec,$extendedarea);
                   5359:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5360:                     $trole = $1;
                   5361:                     $area = $2;
                   5362:                     $sec = $3;
                   5363:                     $extendedarea = $area.$sec;
                   5364:                     if (exists($$allgroups{$area})) {
                   5365:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5366:                             my $spec = $trole.'.'.$extendedarea;
                   5367:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5368:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5369:                         }
1.678     raeburn  5370:                     }
                   5371:                 }
                   5372:             }
                   5373:         }
                   5374:     }
1.800     albertel 5375:     foreach my $group (keys(%grouproles)) {
                   5376:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5377:     }
1.800     albertel 5378:     foreach my $role (keys(%{$allroles})) {
                   5379:         my %thesepriv;
1.941     raeburn  5380:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5381:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5382:             if ($item ne '') {
                   5383:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5384:                 if ($restrictions eq '') {
                   5385:                     $thesepriv{$privilege}='F';
                   5386:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5387:                     $thesepriv{$privilege}.=$restrictions;
                   5388:                 }
                   5389:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5390:             }
                   5391:         }
                   5392:         my $thesestr='';
1.1104    raeburn  5393:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5394: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5395: 	}
                   5396:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5397:     }
                   5398:     return ($author,$adv);
                   5399: }
                   5400: 
1.994     raeburn  5401: sub role_status {
1.1104    raeburn  5402:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5403:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5404:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5405:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5406:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5407:             $$where = '/'.$two;
1.994     raeburn  5408:             $$trolecode=$$role.'.'.$$where;
                   5409:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5410:             $$tstatus='is';
1.1104    raeburn  5411:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5412:                 $$tstatus='future';
1.1034    raeburn  5413:                 if ($$tstart<$now) {
                   5414:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5415:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5416:                             my (%allroles,%allgroups,$group_privs,
                   5417:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5418:                             my %userroles = (
                   5419:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5420:                             );
1.1064    raeburn  5421:                             @rolecodes = ('cm'); 
1.1002    raeburn  5422:                             my $spec=$$role.'.'.$$where;
                   5423:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5424:                             if ($$role =~ /^cr\//) {
                   5425:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5426:                                 push(@rolecodes,'cr');
1.1002    raeburn  5427:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5428:                                 push(@rolecodes,$$role);
1.1002    raeburn  5429:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5430:                                                     $env{'user.name'});
1.1064    raeburn  5431:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5432:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5433:                                 $group_privs = &unescape($group_privs);
                   5434:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5435:                                 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  5436:                                 &get_groups_roles($tdomain,$trest,
                   5437:                                                   \%course_roles,\@rolecodes,
                   5438:                                                   \%groups_roles);
1.1002    raeburn  5439:                             } else {
1.1064    raeburn  5440:                                 push(@rolecodes,$$role);
1.1002    raeburn  5441:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5442:                             }
1.1064    raeburn  5443:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5444:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5445:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5446:                         }
                   5447:                     }
1.1034    raeburn  5448:                     $$tstatus = 'is';
1.1002    raeburn  5449:                 }
1.994     raeburn  5450:             }
                   5451:             if ($$tend) {
1.1104    raeburn  5452:                 if ($$tend<$update) {
1.994     raeburn  5453:                     $$tstatus='expired';
                   5454:                 } elsif ($$tend<$now) {
                   5455:                     $$tstatus='will_not';
                   5456:                 }
                   5457:             }
                   5458:         }
                   5459:     }
                   5460: }
                   5461: 
1.1104    raeburn  5462: sub get_groups_roles {
                   5463:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5464:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5465:                   (ref($rolecodes) eq 'ARRAY') && 
                   5466:                   (ref($groups_roles) eq 'HASH')); 
                   5467:     if (keys(%{$cdom_courseroles}) > 0) {
                   5468:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5469:         if ($cdom ne '' && $cnum ne '') {
                   5470:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5471:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5472:                     my $crsrole = $1;
                   5473:                     my $crssec = $2;
                   5474:                     if ($crsrole =~ /^cr/) {
                   5475:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5476:                             push(@{$rolecodes},'cr');
                   5477:                         }
                   5478:                     } else {
                   5479:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5480:                             push(@{$rolecodes},$crsrole);
                   5481:                         }
                   5482:                     }
                   5483:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5484:                     if ($crssec ne '') {
                   5485:                         $rolekey .= "/$crssec";
                   5486:                     }
                   5487:                     $rolekey .= './';
                   5488:                     $groups_roles->{$rolekey} = $rolecodes;
                   5489:                 }
                   5490:             }
                   5491:         }
                   5492:     }
                   5493:     return;
                   5494: }
                   5495: 
                   5496: sub delete_env_groupprivs {
                   5497:     my ($where,$courseroles,$possroles) = @_;
                   5498:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5499:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5500:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5501:         %{$courseroles->{$udom}} =
                   5502:             &get_my_roles('','','userroles',['active'],
                   5503:                           $possroles,[$udom],1);
                   5504:     }
                   5505:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5506:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5507:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5508:             my $area = '/'.$cdom.'/'.$cnum;
                   5509:             my $privkey = "user.priv.$crsrole.$area";
                   5510:             if ($crssec ne '') {
                   5511:                 $privkey .= '/'.$crssec;
                   5512:             }
                   5513:             $privkey .= ".$area/$group";
                   5514:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5515:         }
                   5516:     }
                   5517:     return;
                   5518: }
                   5519: 
1.994     raeburn  5520: sub check_adhoc_privs {
1.1104    raeburn  5521:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5522:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5523:     my $setprivs;
1.994     raeburn  5524:     if ($env{$cckey}) {
                   5525:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5526:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5527:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5528:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5529:             $setprivs = 1;
1.994     raeburn  5530:         }
                   5531:     } else {
1.1088    raeburn  5532:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5533:         $setprivs = 1;
1.994     raeburn  5534:     }
1.1185    raeburn  5535:     return $setprivs;
1.994     raeburn  5536: }
                   5537: 
                   5538: sub set_adhoc_privileges {
                   5539: # role can be cc or ca
1.1088    raeburn  5540:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5541:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5542:     my $spec = $role.'.'.$area;
                   5543:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5544:                                   $env{'user.name'},1);
1.994     raeburn  5545:     my %ccrole = ();
                   5546:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5547:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5548:     &appenv(\%userroles,[$role,'cm']);
                   5549:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5550:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5551:         &appenv( {'request.role'        => $spec,
                   5552:                   'request.role.domain' => $dcdom,
                   5553:                   'request.course.sec'  => ''
                   5554:                  }
                   5555:                );
                   5556:         my $tadv=0;
                   5557:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5558:         &appenv({'request.role.adv'    => $tadv});
                   5559:     }
1.994     raeburn  5560: }
                   5561: 
1.12      www      5562: # --------------------------------------------------------------- get interface
                   5563: 
                   5564: sub get {
1.131     albertel 5565:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5566:    my $items='';
1.800     albertel 5567:    foreach my $item (@$storearr) {
                   5568:        $items.=&escape($item).'&';
1.191     harris41 5569:    }
1.12      www      5570:    $items=~s/\&$//;
1.620     albertel 5571:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5572:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5573:    my $uhome=&homeserver($uname,$udomain);
                   5574: 
1.133     albertel 5575:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5576:    my @pairs=split(/\&/,$rep);
1.273     albertel 5577:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5578:      return @pairs;
                   5579:    }
1.15      www      5580:    my %returnhash=();
1.42      www      5581:    my $i=0;
1.800     albertel 5582:    foreach my $item (@$storearr) {
                   5583:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5584:       $i++;
1.191     harris41 5585:    }
1.15      www      5586:    return %returnhash;
1.27      www      5587: }
                   5588: 
                   5589: # --------------------------------------------------------------- del interface
                   5590: 
                   5591: sub del {
1.133     albertel 5592:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5593:    my $items='';
1.800     albertel 5594:    foreach my $item (@$storearr) {
                   5595:        $items.=&escape($item).'&';
1.191     harris41 5596:    }
1.984     neumanie 5597: 
1.27      www      5598:    $items=~s/\&$//;
1.620     albertel 5599:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5600:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5601:    my $uhome=&homeserver($uname,$udomain);
                   5602:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5603: }
                   5604: 
                   5605: # -------------------------------------------------------------- dump interface
                   5606: 
1.1180    droeschl 5607: sub unserialize {
                   5608:     my ($rep, $escapedkeys) = @_;
                   5609: 
                   5610:     return {} if $rep =~ /^error/;
                   5611: 
                   5612:     my %returnhash=();
1.1252    raeburn  5613: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 5614: 	    my ($key, $value) = split(/=/, $item, 2);
                   5615: 	    $key = unescape($key) unless $escapedkeys;
                   5616: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  5617: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 5618: 	}
                   5619:     #return %returnhash;
                   5620:     return \%returnhash;
                   5621: }        
                   5622: 
                   5623: # see Lond::dump_with_regexp
                   5624: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5625: sub dump {
1.1180    droeschl 5626:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5627:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5628:     if (!$uname) { $uname=$env{'user.name'}; }
                   5629:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5630: 
1.1266  ! raeburn  5631:     if ($regexp) {
        !          5632:         $regexp=&escape($regexp);
        !          5633:     } else {
        !          5634:         $regexp='.';
        !          5635:     }
1.1180    droeschl 5636:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5637:         # user is hosted on this machine
1.1266  ! raeburn  5638:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5639:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5640:         return %{unserialize($reply, $escapedkeys)};
                   5641:     }
1.1166    raeburn  5642:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5643:     my @pairs=split(/\&/,$rep);
                   5644:     my %returnhash=();
1.1098    foxr     5645:     if (!($rep =~ /^error/ )) {
                   5646: 	foreach my $item (@pairs) {
                   5647: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5648:         $key = unescape($key) unless $escapedkeys;
                   5649:         #$key = &unescape($key);
1.1098    foxr     5650: 	    next if ($key =~ /^error: 2 /);
                   5651: 	    $returnhash{$key}=&thaw_unescape($value);
                   5652: 	}
1.755     albertel 5653:     }
                   5654:     return %returnhash;
1.407     www      5655: }
                   5656: 
1.1098    foxr     5657: 
1.717     albertel 5658: # --------------------------------------------------------- dumpstore interface
                   5659: 
                   5660: sub dumpstore {
                   5661:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5662:    # same as dump but keys must be escaped. They may contain colon separated
                   5663:    # lists of values that may themself contain colons (e.g. symbs).
                   5664:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5665: }
                   5666: 
1.407     www      5667: # -------------------------------------------------------------- keys interface
                   5668: 
                   5669: sub getkeys {
                   5670:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5671:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5672:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5673:    my $uhome=&homeserver($uname,$udomain);
                   5674:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5675:    my @keyarray=();
1.800     albertel 5676:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5677:       next if ($key =~ /^error: 2 /);
1.800     albertel 5678:       push(@keyarray,&unescape($key));
1.407     www      5679:    }
                   5680:    return @keyarray;
1.318     matthew  5681: }
                   5682: 
1.319     matthew  5683: # --------------------------------------------------------------- currentdump
                   5684: sub currentdump {
1.328     matthew  5685:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5686:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5687:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5688:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5689:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5690:    my $rep;
                   5691: 
                   5692:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5693:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5694:                    $courseid)));
                   5695:    } else {
                   5696:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5697:    }
                   5698: 
1.318     matthew  5699:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5700:    #
1.318     matthew  5701:    my %returnhash=();
1.319     matthew  5702:    #
                   5703:    if ($rep eq "unknown_cmd") { 
                   5704:        # an old lond will not know currentdump
                   5705:        # Do a dump and make it look like a currentdump
1.822     albertel 5706:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5707:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5708:        my %hash = @tmp;
                   5709:        @tmp=();
1.424     matthew  5710:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5711:    } else {
                   5712:        my @pairs=split(/\&/,$rep);
1.800     albertel 5713:        foreach my $pair (@pairs) {
                   5714:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5715:            my ($symb,$param) = split(/:/,$key);
                   5716:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5717:                                                         &thaw_unescape($value);
1.319     matthew  5718:        }
1.191     harris41 5719:    }
1.12      www      5720:    return %returnhash;
1.424     matthew  5721: }
                   5722: 
                   5723: sub convert_dump_to_currentdump{
                   5724:     my %hash = %{shift()};
                   5725:     my %returnhash;
                   5726:     # Code ripped from lond, essentially.  The only difference
                   5727:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5728:     # we might run in to problems with parameter names =~ /^v\./
                   5729:     while (my ($key,$value) = each(%hash)) {
                   5730:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5731: 	$symb  = &unescape($symb);
                   5732: 	$param = &unescape($param);
1.424     matthew  5733:         next if ($v eq 'version' || $symb eq 'keys');
                   5734:         next if (exists($returnhash{$symb}) &&
                   5735:                  exists($returnhash{$symb}->{$param}) &&
                   5736:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5737:         $returnhash{$symb}->{$param}=$value;
                   5738:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5739:     }
                   5740:     #
                   5741:     # Remove all of the keys in the hashes which keep track of
                   5742:     # the version of the parameter.
                   5743:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5744:         # use a foreach because we are going to delete from the hash.
                   5745:         foreach my $key (keys(%$param_hash)) {
                   5746:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5747:         }
                   5748:     }
                   5749:     return \%returnhash;
1.12      www      5750: }
                   5751: 
1.627     albertel 5752: # ------------------------------------------------------ critical inc interface
                   5753: 
                   5754: sub cinc {
                   5755:     return &inc(@_,'critical');
                   5756: }
                   5757: 
1.449     matthew  5758: # --------------------------------------------------------------- inc interface
                   5759: 
                   5760: sub inc {
1.627     albertel 5761:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5762:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5763:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5764:     my $uhome=&homeserver($uname,$udomain);
                   5765:     my $items='';
                   5766:     if (! ref($store)) {
                   5767:         # got a single value, so use that instead
                   5768:         $items = &escape($store).'=&';
                   5769:     } elsif (ref($store) eq 'SCALAR') {
                   5770:         $items = &escape($$store).'=&';        
                   5771:     } elsif (ref($store) eq 'ARRAY') {
                   5772:         $items = join('=&',map {&escape($_);} @{$store});
                   5773:     } elsif (ref($store) eq 'HASH') {
                   5774:         while (my($key,$value) = each(%{$store})) {
                   5775:             $items.= &escape($key).'='.&escape($value).'&';
                   5776:         }
                   5777:     }
                   5778:     $items=~s/\&$//;
1.627     albertel 5779:     if ($critical) {
                   5780: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5781:     } else {
                   5782: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5783:     }
1.449     matthew  5784: }
                   5785: 
1.12      www      5786: # --------------------------------------------------------------- put interface
                   5787: 
                   5788: sub put {
1.134     albertel 5789:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5790:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5791:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5792:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5793:    my $items='';
1.800     albertel 5794:    foreach my $item (keys(%$storehash)) {
                   5795:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5796:    }
1.12      www      5797:    $items=~s/\&$//;
1.134     albertel 5798:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5799: }
                   5800: 
1.631     albertel 5801: # ------------------------------------------------------------ newput interface
                   5802: 
                   5803: sub newput {
                   5804:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5805:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5806:    if (!$uname) { $uname=$env{'user.name'}; }
                   5807:    my $uhome=&homeserver($uname,$udomain);
                   5808:    my $items='';
                   5809:    foreach my $key (keys(%$storehash)) {
                   5810:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5811:    }
                   5812:    $items=~s/\&$//;
                   5813:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5814: }
                   5815: 
                   5816: # ---------------------------------------------------------  putstore interface
                   5817: 
1.524     raeburn  5818: sub putstore {
1.715     albertel 5819:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5820:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5821:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5822:    my $uhome=&homeserver($uname,$udomain);
                   5823:    my $items='';
1.715     albertel 5824:    foreach my $key (keys(%$storehash)) {
                   5825:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5826:    }
1.715     albertel 5827:    $items=~s/\&$//;
1.716     albertel 5828:    my $esc_symb=&escape($symb);
                   5829:    my $esc_v=&escape($version);
1.715     albertel 5830:    my $reply =
1.716     albertel 5831:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5832: 	      $uhome);
                   5833:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5834:        # gfall back to way things use to be done
1.715     albertel 5835:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5836: 			    $uname);
1.524     raeburn  5837:    }
1.715     albertel 5838:    return $reply;
                   5839: }
                   5840: 
                   5841: sub old_putstore {
1.716     albertel 5842:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5843:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5844:     if (!$uname) { $uname=$env{'user.name'}; }
                   5845:     my $uhome=&homeserver($uname,$udomain);
                   5846:     my %newstorehash;
1.800     albertel 5847:     foreach my $item (keys(%$storehash)) {
                   5848: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5849: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5850:     }
                   5851:     my $items='';
                   5852:     my %allitems = ();
1.800     albertel 5853:     foreach my $item (keys(%newstorehash)) {
                   5854: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5855: 	    my $key = $1.':keys:'.$2;
                   5856: 	    $allitems{$key} .= $3.':';
                   5857: 	}
1.800     albertel 5858: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5859:     }
1.800     albertel 5860:     foreach my $item (keys(%allitems)) {
                   5861: 	$allitems{$item} =~ s/\:$//;
                   5862: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5863:     }
                   5864:     $items=~s/\&$//;
                   5865:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5866: }
                   5867: 
1.47      www      5868: # ------------------------------------------------------ critical put interface
                   5869: 
                   5870: sub cput {
1.134     albertel 5871:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5872:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5873:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5874:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5875:    my $items='';
1.800     albertel 5876:    foreach my $item (keys(%$storehash)) {
                   5877:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5878:    }
1.47      www      5879:    $items=~s/\&$//;
1.134     albertel 5880:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5881: }
                   5882: 
                   5883: # -------------------------------------------------------------- eget interface
                   5884: 
                   5885: sub eget {
1.133     albertel 5886:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5887:    my $items='';
1.800     albertel 5888:    foreach my $item (@$storearr) {
                   5889:        $items.=&escape($item).'&';
1.191     harris41 5890:    }
1.12      www      5891:    $items=~s/\&$//;
1.620     albertel 5892:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5893:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5894:    my $uhome=&homeserver($uname,$udomain);
                   5895:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5896:    my @pairs=split(/\&/,$rep);
                   5897:    my %returnhash=();
1.42      www      5898:    my $i=0;
1.800     albertel 5899:    foreach my $item (@$storearr) {
                   5900:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5901:       $i++;
1.191     harris41 5902:    }
1.12      www      5903:    return %returnhash;
                   5904: }
                   5905: 
1.667     albertel 5906: # ------------------------------------------------------------ tmpput interface
                   5907: sub tmpput {
1.802     raeburn  5908:     my ($storehash,$server,$context)=@_;
1.667     albertel 5909:     my $items='';
1.800     albertel 5910:     foreach my $item (keys(%$storehash)) {
                   5911: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5912:     }
                   5913:     $items=~s/\&$//;
1.802     raeburn  5914:     if (defined($context)) {
                   5915:         $items .= ':'.&escape($context);
                   5916:     }
1.667     albertel 5917:     return &reply("tmpput:$items",$server);
                   5918: }
                   5919: 
                   5920: # ------------------------------------------------------------ tmpget interface
                   5921: sub tmpget {
1.688     albertel 5922:     my ($token,$server)=@_;
                   5923:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5924:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5925:     my %returnhash;
                   5926:     foreach my $item (split(/\&/,$rep)) {
                   5927: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5928:         next if ($key =~ /^error: 2 /);
1.667     albertel 5929: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5930:     }
                   5931:     return %returnhash;
                   5932: }
                   5933: 
1.1113    raeburn  5934: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5935: sub tmpdel {
                   5936:     my ($token,$server)=@_;
                   5937:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5938:     return &reply("tmpdel:$token",$server);
                   5939: }
                   5940: 
1.1198    raeburn  5941: # ------------------------------------------------------------ get_timebased_id 
                   5942: 
                   5943: sub get_timebased_id {
                   5944:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5945:         $maxtries) = @_;
                   5946:     my ($newid,$error,$dellock);
                   5947:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   5948:         return ('','ok','invalid call to get suffix');
                   5949:     }
                   5950: 
                   5951: # set defaults for any optional args for which values were not supplied
                   5952:     if ($who eq '') {
                   5953:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5954:     }
                   5955:     if (!$locktries) {
                   5956:         $locktries = 3;
                   5957:     }
                   5958:     if (!$maxtries) {
                   5959:         $maxtries = 10;
                   5960:     }
                   5961:     
                   5962:     if (($cdom eq '') || ($cnum eq '')) {
                   5963:         if ($env{'request.course.id'}) {
                   5964:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5965:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5966:         }
                   5967:         if (($cdom eq '') || ($cnum eq '')) {
                   5968:             return ('','ok','call to get suffix not in course context');
                   5969:         }
                   5970:     }
                   5971: 
                   5972: # construct locking item
                   5973:     my $lockhash = {
                   5974:                       $prefix."\0".'locked_'.$keyid => $who,
                   5975:                    };
                   5976:     my $tries = 0;
                   5977: 
                   5978: # attempt to get lock on nohist_$namespace file
                   5979:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5980:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5981:         $tries ++;
                   5982:         sleep 1;
                   5983:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5984:     }
                   5985: 
                   5986: # attempt to get unique identifier, based on current timestamp
                   5987:     if ($gotlock eq 'ok') {
                   5988:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5989:         my $id = time;
                   5990:         $newid = $id;
                   5991:         my $idtries = 0;
                   5992:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5993:             if ($idtype eq 'concat') {
                   5994:                 $newid = $id.$idtries;
                   5995:             } else {
                   5996:                 $newid ++;
                   5997:             }
                   5998:             $idtries ++;
                   5999:         }
                   6000:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6001:             my %new_item =  (
                   6002:                               $prefix."\0".$newid => $who,
                   6003:                             );
                   6004:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6005:                                                  $cdom,$cnum);
                   6006:             if ($putresult ne 'ok') {
                   6007:                 undef($newid);
                   6008:                 $error = 'error saving new item: '.$putresult;
                   6009:             }
                   6010:         } else {
                   6011:              $error = ('error: no unique suffix available for the new item ');
                   6012:         }
                   6013: #  remove lock
                   6014:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6015:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6016:     } else {
                   6017:         $error = "error: could not obtain lockfile\n";
                   6018:         $dellock = 'ok';
                   6019:     }
                   6020:     return ($newid,$dellock,$error);
                   6021: }
                   6022: 
1.765     albertel 6023: # -------------------------------------------------- portfolio access checking
                   6024: 
                   6025: sub portfolio_access {
1.766     albertel 6026:     my ($requrl) = @_;
1.765     albertel 6027:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   6028:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  6029:     if ($result) {
                   6030:         my %setters;
                   6031:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6032:             my ($startblock,$endblock) =
                   6033:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6034:             if ($startblock && $endblock) {
                   6035:                 return 'B';
                   6036:             }
                   6037:         } else {
                   6038:             my ($startblock,$endblock) =
                   6039:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6040:             if ($startblock && $endblock) {
                   6041:                 return 'B';
                   6042:             }
                   6043:         }
                   6044:     }
1.765     albertel 6045:     if ($result eq 'ok') {
1.766     albertel 6046:        return 'F';
1.765     albertel 6047:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6048:        return 'A';
1.765     albertel 6049:     }
1.766     albertel 6050:     return '';
1.765     albertel 6051: }
                   6052: 
                   6053: sub get_portfolio_access {
1.767     albertel 6054:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   6055: 
                   6056:     if (!ref($access_hash)) {
                   6057: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6058: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6059: 						   $file_name);
                   6060: 	$access_hash = $access_controls{$file_name};
                   6061:     }
                   6062: 
1.765     albertel 6063:     my ($public,$guest,@domains,@users,@courses,@groups);
                   6064:     my $now = time;
                   6065:     if (ref($access_hash) eq 'HASH') {
                   6066:         foreach my $key (keys(%{$access_hash})) {
                   6067:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6068:             if ($start > $now) {
                   6069:                 next;
                   6070:             }
                   6071:             if ($end && $end<$now) {
                   6072:                 next;
                   6073:             }
                   6074:             if ($scope eq 'public') {
                   6075:                 $public = $key;
                   6076:                 last;
                   6077:             } elsif ($scope eq 'guest') {
                   6078:                 $guest = $key;
                   6079:             } elsif ($scope eq 'domains') {
                   6080:                 push(@domains,$key);
                   6081:             } elsif ($scope eq 'users') {
                   6082:                 push(@users,$key);
                   6083:             } elsif ($scope eq 'course') {
                   6084:                 push(@courses,$key);
                   6085:             } elsif ($scope eq 'group') {
                   6086:                 push(@groups,$key);
                   6087:             }
                   6088:         }
                   6089:         if ($public) {
                   6090:             return 'ok';
                   6091:         }
                   6092:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6093:             if ($guest) {
                   6094:                 return $guest;
                   6095:             }
                   6096:         } else {
                   6097:             if (@domains > 0) {
                   6098:                 foreach my $domkey (@domains) {
                   6099:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6100:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6101:                             return 'ok';
                   6102:                         }
                   6103:                     }
                   6104:                 }
                   6105:             }
                   6106:             if (@users > 0) {
                   6107:                 foreach my $userkey (@users) {
1.865     raeburn  6108:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6109:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6110:                             if (ref($item) eq 'HASH') {
                   6111:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6112:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6113:                                     return 'ok';
                   6114:                                 }
                   6115:                             }
                   6116:                         }
                   6117:                     } 
1.765     albertel 6118:                 }
                   6119:             }
                   6120:             my %roleshash;
                   6121:             my @courses_and_groups = @courses;
                   6122:             push(@courses_and_groups,@groups); 
                   6123:             if (@courses_and_groups > 0) {
                   6124:                 my (%allgroups,%allroles); 
                   6125:                 my ($start,$end,$role,$sec,$group);
                   6126:                 foreach my $envkey (%env) {
1.1060    raeburn  6127:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6128:                         my $cid = $2.'_'.$3; 
                   6129:                         if ($1 eq 'gr') {
                   6130:                             $group = $4;
                   6131:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6132:                         } else {
                   6133:                             if ($4 eq '') {
                   6134:                                 $sec = 'none';
                   6135:                             } else {
                   6136:                                 $sec = $4;
                   6137:                             }
                   6138:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6139:                         }
1.811     albertel 6140:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6141:                         my $cid = $2.'_'.$3;
                   6142:                         if ($4 eq '') {
                   6143:                             $sec = 'none';
                   6144:                         } else {
                   6145:                             $sec = $4;
                   6146:                         }
                   6147:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6148:                     }
                   6149:                 }
                   6150:                 if (keys(%allroles) == 0) {
                   6151:                     return;
                   6152:                 }
                   6153:                 foreach my $key (@courses_and_groups) {
                   6154:                     my %content = %{$$access_hash{$key}};
                   6155:                     my $cnum = $content{'number'};
                   6156:                     my $cdom = $content{'domain'};
                   6157:                     my $cid = $cdom.'_'.$cnum;
                   6158:                     if (!exists($allroles{$cid})) {
                   6159:                         next;
                   6160:                     }    
                   6161:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6162:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6163:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6164:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6165:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6166:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6167:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6168:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6169:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6170:                                         if (grep/^all$/,@sections) {
                   6171:                                             return 'ok';
                   6172:                                         } else {
                   6173:                                             if (grep/^$sec$/,@sections) {
                   6174:                                                 return 'ok';
                   6175:                                             }
                   6176:                                         }
                   6177:                                     }
                   6178:                                 }
                   6179:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6180:                                     if (grep/^none$/,@groups) {
                   6181:                                         return 'ok';
                   6182:                                     }
                   6183:                                 } else {
                   6184:                                     if (grep/^all$/,@groups) {
                   6185:                                         return 'ok';
                   6186:                                     } 
                   6187:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6188:                                         if (grep/^$group$/,@groups) {
                   6189:                                             return 'ok';
                   6190:                                         }
                   6191:                                     }
                   6192:                                 } 
                   6193:                             }
                   6194:                         }
                   6195:                     }
                   6196:                 }
                   6197:             }
                   6198:             if ($guest) {
                   6199:                 return $guest;
                   6200:             }
                   6201:         }
                   6202:     }
                   6203:     return;
                   6204: }
                   6205: 
                   6206: sub course_group_datechecker {
                   6207:     my ($dates,$now,$status) = @_;
                   6208:     my ($start,$end) = split(/\./,$dates);
                   6209:     if (!$start && !$end) {
                   6210:         return 'ok';
                   6211:     }
                   6212:     if (grep/^active$/,@{$status}) {
                   6213:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6214:             return 'ok';
                   6215:         }
                   6216:     }
                   6217:     if (grep/^previous$/,@{$status}) {
                   6218:         if ($end > $now ) {
                   6219:             return 'ok';
                   6220:         }
                   6221:     }
                   6222:     if (grep/^future$/,@{$status}) {
                   6223:         if ($start > $now) {
                   6224:             return 'ok';
                   6225:         }
                   6226:     }
                   6227:     return; 
                   6228: }
                   6229: 
                   6230: sub parse_portfolio_url {
                   6231:     my ($url) = @_;
                   6232: 
                   6233:     my ($type,$udom,$unum,$group,$file_name);
                   6234:     
1.823     albertel 6235:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6236: 	$type = 1;
                   6237:         $udom = $1;
                   6238:         $unum = $2;
                   6239:         $file_name = $3;
1.823     albertel 6240:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6241: 	$type = 2;
                   6242:         $udom = $1;
                   6243:         $unum = $2;
                   6244:         $group = $3;
                   6245:         $file_name = $3.'/'.$4;
                   6246:     }
                   6247:     if (wantarray) {
                   6248: 	return ($type,$udom,$unum,$file_name,$group);
                   6249:     }
                   6250:     return $type;
                   6251: }
                   6252: 
                   6253: sub is_portfolio_url {
                   6254:     my ($url) = @_;
                   6255:     return scalar(&parse_portfolio_url($url));
                   6256: }
                   6257: 
1.798     raeburn  6258: sub is_portfolio_file {
                   6259:     my ($file) = @_;
1.820     raeburn  6260:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6261:         return 1;
                   6262:     }
                   6263:     return;
                   6264: }
                   6265: 
1.976     raeburn  6266: sub usertools_access {
1.1084    raeburn  6267:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6268:     my ($access,%tools);
                   6269:     if ($context eq '') {
                   6270:         $context = 'tools';
                   6271:     }
                   6272:     if ($context eq 'requestcourses') {
                   6273:         %tools = (
                   6274:                       official   => 1,
                   6275:                       unofficial => 1,
1.1006    raeburn  6276:                       community  => 1,
1.1246    raeburn  6277:                       textbook   => 1,
1.985     raeburn  6278:                  );
1.1183    raeburn  6279:     } elsif ($context eq 'requestauthor') {
                   6280:         %tools = (
                   6281:                       requestauthor => 1,
                   6282:                  );
1.985     raeburn  6283:     } else {
                   6284:         %tools = (
                   6285:                       aboutme   => 1,
                   6286:                       blog      => 1,
1.1177    raeburn  6287:                       webdav    => 1,
1.985     raeburn  6288:                       portfolio => 1,
                   6289:                  );
                   6290:     }
1.976     raeburn  6291:     return if (!defined($tools{$tool}));
                   6292: 
1.1242    raeburn  6293:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6294:         $udom = $env{'user.domain'};
                   6295:         $uname = $env{'user.name'};
                   6296:     }
                   6297: 
1.978     raeburn  6298:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6299:         if ($action ne 'reload') {
1.985     raeburn  6300:             if ($context eq 'requestcourses') {
                   6301:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6302:             } elsif ($context eq 'requestauthor') {
                   6303:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6304:             } else {
                   6305:                 return $env{'environment.availabletools.'.$tool};
                   6306:             }
                   6307:         }
1.976     raeburn  6308:     }
                   6309: 
1.1183    raeburn  6310:     my ($toolstatus,$inststatus,$envkey);
                   6311:     if ($context eq 'requestauthor') {
                   6312:         $envkey = $context; 
                   6313:     } else {
                   6314:         $envkey = $context.'.'.$tool;
                   6315:     }
1.976     raeburn  6316: 
1.985     raeburn  6317:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6318:          ($action ne 'reload')) {
1.1183    raeburn  6319:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6320:         $inststatus = $env{'environment.inststatus'};
                   6321:     } else {
1.1084    raeburn  6322:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6323:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6324:             $inststatus = $userenvref->{'inststatus'};
                   6325:         } else {
1.1183    raeburn  6326:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6327:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6328:             $inststatus = $userenv{'inststatus'};
                   6329:         }
1.976     raeburn  6330:     }
                   6331: 
                   6332:     if ($toolstatus ne '') {
                   6333:         if ($toolstatus) {
                   6334:             $access = 1;
                   6335:         } else {
                   6336:             $access = 0;
                   6337:         }
                   6338:         return $access;
                   6339:     }
                   6340: 
1.1084    raeburn  6341:     my ($is_adv,%domdef);
                   6342:     if (ref($is_advref) eq 'HASH') {
                   6343:         $is_adv = $is_advref->{'is_adv'};
                   6344:     } else {
                   6345:         $is_adv = &is_advanced_user($udom,$uname);
                   6346:     }
                   6347:     if (ref($domdefref) eq 'HASH') {
                   6348:         %domdef = %{$domdefref};
                   6349:     } else {
                   6350:         %domdef = &get_domain_defaults($udom);
                   6351:     }
1.976     raeburn  6352:     if (ref($domdef{$tool}) eq 'HASH') {
                   6353:         if ($is_adv) {
                   6354:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6355:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6356:                     $access = 1;
                   6357:                 } else {
                   6358:                     $access = 0;
                   6359:                 }
                   6360:                 return $access;
                   6361:             }
                   6362:         }
                   6363:         if ($inststatus ne '') {
                   6364:             my ($hasaccess,$hasnoaccess);
                   6365:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6366:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6367:                     if ($domdef{$tool}{$affiliation}) {
                   6368:                         $hasaccess = 1;
                   6369:                     } else {
                   6370:                         $hasnoaccess = 1;
                   6371:                     }
                   6372:                 }
                   6373:             }
                   6374:             if ($hasaccess || $hasnoaccess) {
                   6375:                 if ($hasaccess) {
                   6376:                     $access = 1;
                   6377:                 } elsif ($hasnoaccess) {
                   6378:                     $access = 0; 
                   6379:                 }
                   6380:                 return $access;
                   6381:             }
                   6382:         } else {
                   6383:             if ($domdef{$tool}{'default'} ne '') {
                   6384:                 if ($domdef{$tool}{'default'}) {
                   6385:                     $access = 1;
                   6386:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6387:                     $access = 0;
                   6388:                 }
                   6389:                 return $access;
                   6390:             }
                   6391:         }
                   6392:     } else {
1.1177    raeburn  6393:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6394:             $access = 1;
                   6395:         } else {
                   6396:             $access = 0;
                   6397:         }
1.976     raeburn  6398:         return $access;
                   6399:     }
                   6400: }
                   6401: 
1.1050    raeburn  6402: sub is_course_owner {
                   6403:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6404:     if (($udom eq '') || ($uname eq '')) {
                   6405:         $udom = $env{'user.domain'};
                   6406:         $uname = $env{'user.name'};
                   6407:     }
                   6408:     unless (($udom eq '') || ($uname eq '')) {
                   6409:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6410:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6411:                 return 1;
                   6412:             } else {
                   6413:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6414:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6415:                     return 1;
                   6416:                 }
                   6417:             }
                   6418:         }
                   6419:     }
                   6420:     return;
                   6421: }
                   6422: 
1.976     raeburn  6423: sub is_advanced_user {
                   6424:     my ($udom,$uname) = @_;
1.1085    raeburn  6425:     if ($udom ne '' && $uname ne '') {
                   6426:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6427:             if (wantarray) {
                   6428:                 return ($env{'user.adv'},$env{'user.author'});
                   6429:             } else {
                   6430:                 return $env{'user.adv'};
                   6431:             }
1.1085    raeburn  6432:         }
                   6433:     }
1.976     raeburn  6434:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6435:     my %allroles;
1.1128    raeburn  6436:     my ($is_adv,$is_author);
1.976     raeburn  6437:     foreach my $role (keys(%roleshash)) {
                   6438:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6439:         my $area = '/'.$tdomain.'/'.$trest;
                   6440:         if ($sec ne '') {
                   6441:             $area .= '/'.$sec;
                   6442:         }
                   6443:         if (($area ne '') && ($trole ne '')) {
                   6444:             my $spec=$trole.'.'.$area;
                   6445:             if ($trole =~ /^cr\//) {
                   6446:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6447:             } elsif ($trole ne 'gr') {
                   6448:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6449:             }
1.1128    raeburn  6450:             if ($trole eq 'au') {
                   6451:                 $is_author = 1;
                   6452:             }
1.976     raeburn  6453:         }
                   6454:     }
                   6455:     foreach my $role (keys(%allroles)) {
                   6456:         last if ($is_adv);
                   6457:         foreach my $item (split(/:/,$allroles{$role})) {
                   6458:             if ($item ne '') {
                   6459:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6460:                 if ($privilege eq 'adv') {
                   6461:                     $is_adv = 1;
                   6462:                     last;
                   6463:                 }
                   6464:             }
                   6465:         }
                   6466:     }
1.1128    raeburn  6467:     if (wantarray) {
                   6468:         return ($is_adv,$is_author);
                   6469:     }
1.976     raeburn  6470:     return $is_adv;
                   6471: }
1.798     raeburn  6472: 
1.1035    raeburn  6473: sub check_can_request {
1.1036    raeburn  6474:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6475:     my $canreq = 0;
                   6476:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6477:     my @options = ('approval','validate','autolimit');
                   6478:     my $optregex = join('|',@options);
                   6479:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6480:         foreach my $type (@{$types}) {
                   6481:             if (&usertools_access($env{'user.name'},
                   6482:                                   $env{'user.domain'},
                   6483:                                   $type,undef,'requestcourses')) {
                   6484:                 $canreq ++;
1.1036    raeburn  6485:                 if (ref($request_domains) eq 'HASH') {
                   6486:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6487:                 }
1.1035    raeburn  6488:                 if ($dom eq $env{'user.domain'}) {
                   6489:                     $can_request->{$type} = 1;
                   6490:                 }
                   6491:             }
                   6492:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6493:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6494:                 if (@curr > 0) {
1.1036    raeburn  6495:                     foreach my $item (@curr) {
                   6496:                         if (ref($request_domains) eq 'HASH') {
                   6497:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6498:                             if ($otherdom ne '') {
                   6499:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6500:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6501:                                         push(@{$request_domains->{$type}},$otherdom);
                   6502:                                     }
                   6503:                                 } else {
                   6504:                                     push(@{$request_domains->{$type}},$otherdom);
                   6505:                                 }
                   6506:                             }
                   6507:                         }
                   6508:                     }
                   6509:                     unless($dom eq $env{'user.domain'}) {
                   6510:                         $canreq ++;
1.1035    raeburn  6511:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6512:                             $can_request->{$type} = 1;
                   6513:                         }
                   6514:                     }
                   6515:                 }
                   6516:             }
                   6517:         }
                   6518:     }
                   6519:     return $canreq;
                   6520: }
                   6521: 
1.341     www      6522: # ---------------------------------------------- Custom access rule evaluation
                   6523: 
                   6524: sub customaccess {
                   6525:     my ($priv,$uri)=@_;
1.807     albertel 6526:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6527:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6528:     $udom = &LONCAPA::clean_domain($udom);
                   6529:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6530:     my $access=0;
1.800     albertel 6531:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6532: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6533: 	if ($type eq 'user') {
                   6534: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6535: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6536: 		if ($tdom) {
                   6537: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6538: 		}
1.896     albertel 6539: 		if ($tuname) {
                   6540: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6541: 		}
                   6542: 		$access=($effect eq 'allow');
                   6543: 		last;
                   6544: 	    }
                   6545: 	} else {
                   6546: 	    if ($role) {
                   6547: 		if ($role ne $urole) { next; }
                   6548: 	    }
                   6549: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6550: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6551: 		if ($tdom) {
                   6552: 		    if ($tdom ne $udom) { next; }
                   6553: 		}
                   6554: 		if ($tcrs) {
                   6555: 		    if ($tcrs ne $ucrs) { next; }
                   6556: 		}
                   6557: 		if ($tsec) {
                   6558: 		    if ($tsec ne $usec) { next; }
                   6559: 		}
                   6560: 		$access=($effect eq 'allow');
                   6561: 		last;
                   6562: 	    }
                   6563: 	    if ($realm eq '' && $role eq '') {
                   6564: 		$access=($effect eq 'allow');
                   6565: 	    }
1.402     bowersj2 6566: 	}
1.341     www      6567:     }
                   6568:     return $access;
                   6569: }
                   6570: 
1.103     harris41 6571: # ------------------------------------------------- Check for a user privilege
1.12      www      6572: 
                   6573: sub allowed {
1.810     raeburn  6574:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6575:     my $ver_orguri=$uri;
1.439     www      6576:     $uri=&deversion($uri);
1.152     www      6577:     my $orguri=$uri;
1.52      www      6578:     $uri=&declutter($uri);
1.809     raeburn  6579: 
1.810     raeburn  6580:     if ($priv eq 'evb') {
                   6581: # Evade communication block restrictions for specified role in a course
                   6582:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6583:             return $1;
                   6584:         } else {
                   6585:             return;
                   6586:         }
                   6587:     }
                   6588: 
1.620     albertel 6589:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6590: # Free bre access to adm and meta resources
1.775     albertel 6591:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6592: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6593: 	&& ($priv eq 'bre')) {
1.14      www      6594: 	return 'F';
1.159     www      6595:     }
                   6596: 
1.545     banghart 6597: # Free bre access to user's own portfolio contents
1.714     raeburn  6598:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6599:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6600: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6601:         my %setters;
                   6602:         my ($startblock,$endblock) = 
                   6603:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6604:         if ($startblock && $endblock) {
                   6605:             return 'B';
                   6606:         } else {
                   6607:             return 'F';
                   6608:         }
1.545     banghart 6609:     }
                   6610: 
1.762     raeburn  6611: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6612:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6613:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6614:         if (exists($env{'request.course.id'})) {
                   6615:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6616:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6617:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6618:                 my $courseprivid=$env{'request.course.id'};
                   6619:                 $courseprivid=~s/\_/\//;
                   6620:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6621:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6622:                     return $1; 
1.762     raeburn  6623:                 } else {
                   6624:                     if ($env{'request.course.sec'}) {
                   6625:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6626:                     }
                   6627:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6628:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6629:                         return $2;
                   6630:                     }
1.714     raeburn  6631:                 }
                   6632:             }
                   6633:         }
                   6634:     }
                   6635: 
1.159     www      6636: # Free bre to public access
                   6637: 
                   6638:     if ($priv eq 'bre') {
1.238     www      6639:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6640: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6641:            return 'F'; 
                   6642:         }
1.238     www      6643:         if ($copyright eq 'priv') {
                   6644:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6645: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6646: 		return '';
                   6647:             }
                   6648:         }
                   6649:         if ($copyright eq 'domain') {
                   6650:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6651: 	    unless (($env{'user.domain'} eq $1) ||
                   6652:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6653: 		return '';
                   6654:             }
1.262     matthew  6655:         }
1.620     albertel 6656:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6657:             # Library role, so allow browsing of resources in this domain.
                   6658:             return 'F';
1.238     www      6659:         }
1.341     www      6660:         if ($copyright eq 'custom') {
                   6661: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6662:         }
1.14      www      6663:     }
1.264     matthew  6664:     # Domain coordinator is trying to create a course
1.620     albertel 6665:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6666:         # uri is the requested domain in this case.
                   6667:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6668:         # a role of dc for the domain in question.
1.620     albertel 6669:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6670:     }
1.29      www      6671: 
1.52      www      6672:     my $thisallowed='';
                   6673:     my $statecond=0;
                   6674:     my $courseprivid='';
                   6675: 
1.1039    raeburn  6676:     my $ownaccess;
1.1043    raeburn  6677:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6678:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6679:         if ($uri eq '') {
                   6680:             $ownaccess = 1;
                   6681:         } else {
                   6682:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6683:                 my $udom = $env{'user.domain'};
                   6684:                 my $uname = $env{'user.name'};
                   6685:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6686:                     $ownaccess = 1;
1.1040    raeburn  6687:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6688:                     unless ($uri =~ m{\.\./}) {
                   6689:                         $ownaccess = 1;
                   6690:                     }
                   6691:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6692:                     my $now = time;
                   6693:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6694:                         my $adom = $1;
                   6695:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6696:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6697:                                 my ($start,$end) = split('.',$env{$key});
                   6698:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6699:                                     $ownaccess = 1;
                   6700:                                     last;
                   6701:                                 }
                   6702:                             }
                   6703:                         }
                   6704:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6705:                         my $adom = $1;
                   6706:                         my $aname = $2;
1.1042    raeburn  6707:                         foreach my $role ('ca','aa') { 
                   6708:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6709:                                 my ($start,$end) =
                   6710:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6711:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6712:                                     $ownaccess = 1;
                   6713:                                     last;
                   6714:                                 }
1.1039    raeburn  6715:                             }
                   6716:                         }
                   6717:                     }
                   6718:                 }
                   6719:             }
                   6720:         }
                   6721:     }
                   6722: 
1.52      www      6723: # Course
                   6724: 
1.620     albertel 6725:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6726:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6727:             $thisallowed.=$1;
                   6728:         }
1.52      www      6729:     }
1.29      www      6730: 
1.52      www      6731: # Domain
                   6732: 
1.620     albertel 6733:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6734:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6735:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6736:             $thisallowed.=$1;
                   6737:         }
1.12      www      6738:     }
1.52      www      6739: 
1.1141    raeburn  6740: # User who is not author or co-author might still be able to edit
                   6741: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6742:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6743:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6744:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6745:             $thisallowed.=$1;
                   6746:         }
                   6747:     }
                   6748: 
1.52      www      6749: # Course: uri itself is a course
1.66      www      6750:     my $courseuri=$uri;
                   6751:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6752:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6753: 
1.620     albertel 6754:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6755:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6756:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6757:             $thisallowed.=$1;
                   6758:         }
1.12      www      6759:     }
1.29      www      6760: 
1.665     albertel 6761: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6762: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6763:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6764: 	$thisallowed='';
1.671     raeburn  6765:         my ($match)=&is_on_map($uri);
                   6766:         if ($match) {
                   6767:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6768:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6769:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6770:                 if (@blockers > 0) {
                   6771:                     $thisallowed = 'B';
                   6772:                 } else {
                   6773:                     $thisallowed.=$1;
                   6774:                 }
1.671     raeburn  6775:             }
                   6776:         } else {
1.705     albertel 6777:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6778:             if ($refuri) {
                   6779:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6780:                     $thisallowed='F';
1.671     raeburn  6781:                 } else {
                   6782:                     $refuri=&declutter($refuri);
                   6783:                     my ($match) = &is_on_map($refuri);
                   6784:                     if ($match) {
1.1162    raeburn  6785:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6786:                         if (@blockers > 0) {
                   6787:                             $thisallowed = 'B';
                   6788:                         } else {
                   6789:                             $thisallowed='F';
                   6790:                         }
1.671     raeburn  6791:                     }
1.669     raeburn  6792:                 }
1.671     raeburn  6793:             }
                   6794:         }
1.314     www      6795:     }
1.492     albertel 6796: 
1.766     albertel 6797:     if ($priv eq 'bre'
                   6798: 	&& $thisallowed ne 'F' 
                   6799: 	&& $thisallowed ne '2'
                   6800: 	&& &is_portfolio_url($uri)) {
                   6801: 	$thisallowed = &portfolio_access($uri);
                   6802:     }
1.1250    raeburn  6803: 
1.52      www      6804: # Full access at system, domain or course-wide level? Exit.
1.29      www      6805:     if ($thisallowed=~/F/) {
                   6806: 	return 'F';
                   6807:     }
                   6808: 
1.52      www      6809: # If this is generating or modifying users, exit with special codes
1.29      www      6810: 
1.643     www      6811:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6812: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6813: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6814: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6815: 	    unless ($auname) { return $thisallowed; }
                   6816: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6817: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6818: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6819: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6820: 	}
1.52      www      6821: 	return $thisallowed;
                   6822:     }
                   6823: #
1.103     harris41 6824: # Gathered so far: system, domain and course wide privileges
1.52      www      6825: #
                   6826: # Course: See if uri or referer is an individual resource that is part of 
                   6827: # the course
                   6828: 
1.620     albertel 6829:     if ($env{'request.course.id'}) {
1.232     www      6830: 
1.620     albertel 6831:        $courseprivid=$env{'request.course.id'};
                   6832:        if ($env{'request.course.sec'}) {
                   6833:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6834:        }
                   6835:        $courseprivid=~s/\_/\//;
                   6836:        my $checkreferer=1;
1.232     www      6837:        my ($match,$cond)=&is_on_map($uri);
                   6838:        if ($match) {
                   6839:            $statecond=$cond;
1.620     albertel 6840:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6841:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6842:                my $value = $1;
                   6843:                if ($priv eq 'bre') {
                   6844:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6845:                    if (@blockers > 0) {
                   6846:                        $thisallowed = 'B';
                   6847:                    } else {
                   6848:                        $thisallowed.=$value;
                   6849:                    }
                   6850:                } else {
                   6851:                    $thisallowed.=$value;
                   6852:                }
1.52      www      6853:                $checkreferer=0;
                   6854:            }
1.29      www      6855:        }
1.83      www      6856:        
1.148     www      6857:        if ($checkreferer) {
1.620     albertel 6858: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6859:             unless ($refuri) {
1.800     albertel 6860:                 foreach my $key (keys(%env)) {
                   6861: 		    if ($key=~/^httpref\..*\*/) {
                   6862: 			my $pattern=$key;
1.156     www      6863:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6864:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6865:                         $pattern=~s/\//\\\//g;
1.152     www      6866:                         if ($orguri=~/$pattern/) {
1.800     albertel 6867: 			    $refuri=$env{$key};
1.148     www      6868:                         }
                   6869:                     }
1.191     harris41 6870:                 }
1.148     www      6871:             }
1.232     www      6872: 
1.148     www      6873:          if ($refuri) { 
1.152     www      6874: 	  $refuri=&declutter($refuri);
1.232     www      6875:           my ($match,$cond)=&is_on_map($refuri);
                   6876:             if ($match) {
                   6877:               my $refstatecond=$cond;
1.620     albertel 6878:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6879:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6880:                   my $value = $1;
                   6881:                   if ($priv eq 'bre') {
                   6882:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6883:                       if (@blockers > 0) {
                   6884:                           $thisallowed = 'B';
                   6885:                       } else {
                   6886:                           $thisallowed.=$value;
                   6887:                       }
                   6888:                   } else {
                   6889:                       $thisallowed.=$value;
                   6890:                   }
1.53      www      6891:                   $uri=$refuri;
                   6892:                   $statecond=$refstatecond;
1.52      www      6893:               }
                   6894:           }
1.148     www      6895:         }
1.29      www      6896:        }
1.52      www      6897:    }
1.29      www      6898: 
1.52      www      6899: #
1.103     harris41 6900: # Gathered now: all privileges that could apply, and condition number
1.52      www      6901: # 
                   6902: #
                   6903: # Full or no access?
                   6904: #
1.29      www      6905: 
1.52      www      6906:     if ($thisallowed=~/F/) {
                   6907: 	return 'F';
                   6908:     }
1.29      www      6909: 
1.52      www      6910:     unless ($thisallowed) {
                   6911:         return '';
                   6912:     }
1.29      www      6913: 
1.52      www      6914: # Restrictions exist, deal with them
                   6915: #
                   6916: #   C:according to course preferences
                   6917: #   R:according to resource settings
                   6918: #   L:unless locked
                   6919: #   X:according to user session state
                   6920: #
                   6921: 
                   6922: # Possibly locked functionality, check all courses
1.54      www      6923: # Locks might take effect only after 10 minutes cache expiration for other
                   6924: # courses, and 2 minutes for current course
1.52      www      6925: 
                   6926:     my $envkey;
                   6927:     if ($thisallowed=~/L/) {
1.1000    raeburn  6928:         foreach $envkey (keys(%env)) {
1.54      www      6929:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6930:                my $courseid=$2;
                   6931:                my $roleid=$1.'.'.$2;
1.92      www      6932:                $courseid=~s/^\///;
1.54      www      6933:                my $expiretime=600;
1.620     albertel 6934:                if ($env{'request.role'} eq $roleid) {
1.54      www      6935: 		  $expiretime=120;
                   6936:                }
                   6937: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6938:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6939:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6940: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6941:                }
1.620     albertel 6942:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6943:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6944: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6945:                        &log($env{'user.domain'},$env{'user.name'},
                   6946:                             $env{'user.home'},
1.57      www      6947:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6948:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6949:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6950: 		       return '';
                   6951:                    }
                   6952:                }
1.620     albertel 6953:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6954:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6955: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6956:                        &log($env{'user.domain'},$env{'user.name'},
                   6957:                             $env{'user.home'},
1.57      www      6958:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6959:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6960:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6961: 		       return '';
                   6962:                    }
                   6963:                }
                   6964: 	   }
1.29      www      6965:        }
1.52      www      6966:     }
                   6967:    
                   6968: #
                   6969: # Rest of the restrictions depend on selected course
                   6970: #
                   6971: 
1.620     albertel 6972:     unless ($env{'request.course.id'}) {
1.766     albertel 6973: 	if ($thisallowed eq 'A') {
                   6974: 	    return 'A';
1.814     raeburn  6975:         } elsif ($thisallowed eq 'B') {
                   6976:             return 'B';
1.766     albertel 6977: 	} else {
                   6978: 	    return '1';
                   6979: 	}
1.52      www      6980:     }
1.29      www      6981: 
1.52      www      6982: #
                   6983: # Now user is definitely in a course
                   6984: #
1.53      www      6985: 
                   6986: 
                   6987: # Course preferences
                   6988: 
                   6989:    if ($thisallowed=~/C/) {
1.620     albertel 6990:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6991:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6992:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6993: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6994: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6995: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6996: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6997: 			$env{'request.course.id'});
                   6998: 	   }
1.237     www      6999:            return '';
                   7000:        }
                   7001: 
1.620     albertel 7002:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7003: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7004: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7005: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7006: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7007: 			$env{'request.course.id'});
                   7008: 	   }
1.54      www      7009:            return '';
                   7010:        }
1.53      www      7011:    }
                   7012: 
                   7013: # Resource preferences
                   7014: 
                   7015:    if ($thisallowed=~/R/) {
1.620     albertel 7016:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7017:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7018: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7019: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7020: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7021: 	   }
                   7022: 	   return '';
1.54      www      7023:        }
1.53      www      7024:    }
1.30      www      7025: 
1.246     www      7026: # Restricted by state or randomout?
1.30      www      7027: 
1.52      www      7028:    if ($thisallowed=~/X/) {
1.620     albertel 7029:       if ($env{'acc.randomout'}) {
1.579     albertel 7030: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7031:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7032:             return ''; 
                   7033:          }
1.247     www      7034:       }
                   7035:       if (&condval($statecond)) {
1.52      www      7036: 	 return '2';
                   7037:       } else {
                   7038:          return '';
                   7039:       }
                   7040:    }
1.30      www      7041: 
1.766     albertel 7042:     if ($thisallowed eq 'A') {
                   7043: 	return 'A';
1.814     raeburn  7044:     } elsif ($thisallowed eq 'B') {
                   7045:         return 'B';
1.766     albertel 7046:     }
1.52      www      7047:    return 'F';
1.232     www      7048: }
1.1162    raeburn  7049: 
1.1192    raeburn  7050: # ------------------------------------------- Check construction space access
                   7051: 
                   7052: sub constructaccess {
                   7053:     my ($url,$setpriv)=@_;
                   7054: 
                   7055: # We do not allow editing of previous versions of files
                   7056:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7057: 
                   7058: # Get username and domain from URL
                   7059:     my ($ownername,$ownerdomain,$ownerhome);
                   7060: 
                   7061:     ($ownerdomain,$ownername) =
                   7062:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   7063: 
                   7064: # The URL does not really point to any authorspace, forget it
                   7065:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7066: 
                   7067: # Now we need to see if the user has access to the authorspace of
                   7068: # $ownername at $ownerdomain
                   7069: 
                   7070:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7071: # Real author for this?
                   7072:        $ownerhome = $env{'user.home'};
                   7073:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7074:           return ($ownername,$ownerdomain,$ownerhome);
                   7075:        }
                   7076:     } else {
                   7077: # Co-author for this?
                   7078:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7079:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7080:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7081:             return ($ownername,$ownerdomain,$ownerhome);
                   7082:         }
                   7083:     }
                   7084: 
                   7085: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7086: # we might as well leave
                   7087:    unless ($setpriv) { return ''; }
                   7088: 
                   7089: # Backdoor access?
                   7090:     my $allowed=&allowed('eco',$ownerdomain);
                   7091: # Nope
                   7092:     unless ($allowed) { return ''; }
                   7093: # Looks like we may have access, but could be locked by the owner of the construction space
                   7094:     if ($allowed eq 'U') {
                   7095:         my %blocked=&get('environment',['domcoord.author'],
                   7096:                          $ownerdomain,$ownername);
                   7097: # Is blocked by owner
                   7098:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7099:     }
                   7100:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7101: # Grant temporary access
                   7102:         my $then=$env{'user.login.time'};
1.1209    raeburn  7103:         my $update=$env{'user.update.time'};
1.1192    raeburn  7104:         if (!$update) { $update = $then; }
                   7105:         my $refresh=$env{'user.refresh.time'};
                   7106:         if (!$refresh) { $refresh = $update; }
                   7107:         my $now = time;
                   7108:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7109:                            $now,'ca','constructaccess');
                   7110:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7111:         return($ownername,$ownerdomain,$ownerhome);
                   7112:     }
                   7113: # No business here
                   7114:     return '';
                   7115: }
                   7116: 
1.1162    raeburn  7117: sub get_comm_blocks {
                   7118:     my ($cdom,$cnum) = @_;
                   7119:     if ($cdom eq '' || $cnum eq '') {
                   7120:         return unless ($env{'request.course.id'});
                   7121:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7122:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7123:     }
                   7124:     my %commblocks;
                   7125:     my $hashid=$cdom.'_'.$cnum;
                   7126:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7127:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7128:         %commblocks = %{$blocksref};
                   7129:     } else {
                   7130:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7131:         my $cachetime = 600;
                   7132:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7133:     }
                   7134:     return %commblocks;
                   7135: }
                   7136: 
                   7137: sub has_comm_blocking {
                   7138:     my ($priv,$symb,$uri,$blocks) = @_;
                   7139:     return unless ($env{'request.course.id'});
                   7140:     return unless ($priv eq 'bre');
                   7141:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7142:     my %commblocks;
                   7143:     if (ref($blocks) eq 'HASH') {
                   7144:         %commblocks = %{$blocks};
                   7145:     } else {
                   7146:         %commblocks = &get_comm_blocks();
                   7147:     }
                   7148:     return unless (keys(%commblocks) > 0);
                   7149:     if (!$symb) { $symb=&symbread($uri,1); }
                   7150:     my ($map,$resid,undef)=&decode_symb($symb);
                   7151:     my %tocheck = (
                   7152:                     maps      => $map,
                   7153:                     resources => $symb,
                   7154:                   );
                   7155:     my @blockers;
                   7156:     my $now = time;
1.1163    raeburn  7157:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7158:     foreach my $block (keys(%commblocks)) {
                   7159:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7160:             my ($start,$end) = ($1,$2);
                   7161:             if ($start <= $now && $end >= $now) {
                   7162:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7163:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7164:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7165:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7166:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7167:                                     push(@blockers,$block);
                   7168:                                 }
                   7169:                             }
                   7170:                         }
                   7171:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7172:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7173:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7174:                                     push(@blockers,$block);
                   7175:                                 }
                   7176:                             }
                   7177:                         }
                   7178:                     }
                   7179:                 }
                   7180:             }
                   7181:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7182:             my $item = $1;
1.1163    raeburn  7183:             my @to_test;
1.1162    raeburn  7184:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7185:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7186:                     my $check_interval;
                   7187:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7188:                         my @interval;
                   7189:                         my $type = 'map';
                   7190:                         if ($item eq 'course') {
                   7191:                             $type = 'course';
                   7192:                             @interval=&EXT("resource.0.interval");
                   7193:                         } else {
                   7194:                             if ($item =~ /___\d+___/) {
                   7195:                                 $type = 'resource';
                   7196:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7197:                                 if (ref($navmap)) {                        
                   7198:                                     my $res = $navmap->getBySymb($item); 
                   7199:                                     push(@to_test,$res);
                   7200:                                 }
1.1162    raeburn  7201:                             } else {
                   7202:                                 my $mapsymb = &symbread($item,1);
                   7203:                                 if ($mapsymb) {
                   7204:                                     if (ref($navmap)) {
                   7205:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7206:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7207:                                         foreach my $res (@to_test) {
1.1162    raeburn  7208:                                             my $symb = $res->symb();
                   7209:                                             next if ($symb eq $mapsymb);
                   7210:                                             if ($symb ne '') {
                   7211:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7212:                                                 last;
                   7213:                                             }
                   7214:                                         }
                   7215:                                     }
                   7216:                                 }
                   7217:                             }
                   7218:                         }
                   7219:                         if ($interval[0] =~ /\d+/) {
                   7220:                             my $first_access;
                   7221:                             if ($type eq 'resource') {
                   7222:                                 $first_access=&get_first_access($interval[1],$item);
                   7223:                             } elsif ($type eq 'map') {
                   7224:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7225:                             } else {
                   7226:                                 $first_access=&get_first_access($interval[1]);
                   7227:                             }
                   7228:                             if ($first_access) {
                   7229:                                 my $timesup = $first_access+$interval[0];
                   7230:                                 if ($timesup > $now) {
1.1163    raeburn  7231:                                     foreach my $res (@to_test) {
                   7232:                                         if ($res->is_problem()) {
                   7233:                                             if ($res->completable()) {
                   7234:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7235:                                                     push(@blockers,$block);
                   7236:                                                 }
                   7237:                                                 last;
                   7238:                                             }
                   7239:                                         }
1.1162    raeburn  7240:                                     }
                   7241:                                 }
                   7242:                             }
                   7243:                         }
                   7244:                     }
                   7245:                 }
                   7246:             }
                   7247:         }
                   7248:     }
                   7249:     return @blockers;
                   7250: }
                   7251: 
                   7252: sub check_docs_block {
                   7253:     my ($docsblock,$tocheck) =@_;
                   7254:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7255:         return;
                   7256:     }
                   7257:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7258:         if ($tocheck->{'maps'}) {
                   7259:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7260:                 return 1;
                   7261:             }
                   7262:         }
                   7263:     }
                   7264:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7265:         if ($tocheck->{'resources'}) {
                   7266:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7267:                 return 1;
                   7268:             }
                   7269:         }
                   7270:     }
                   7271:     return;
                   7272: }
                   7273: 
1.1133    foxr     7274: #
                   7275: #   Removes the versino from a URI and
                   7276: #   splits it in to its filename and path to the filename.
                   7277: #   Seems like File::Basename could have done this more clearly.
                   7278: #   Parameters:
                   7279: #      $uri   - input URI
                   7280: #   Returns:
                   7281: #     Two element list consisting of 
                   7282: #     $pathname  - the URI up to and excluding the trailing /
                   7283: #     $filename  - The part of the URI following the last /
                   7284: #  NOTE:
                   7285: #    Another realization of this is simply:
                   7286: #    use File::Basename;
                   7287: #    ...
                   7288: #    $uri = shift;
                   7289: #    $filename = basename($uri);
                   7290: #    $path     = dirname($uri);
                   7291: #    return ($filename, $path);
                   7292: #
                   7293: #     The implementation below is probably faster however.
                   7294: #
1.710     albertel 7295: sub split_uri_for_cond {
                   7296:     my $uri=&deversion(&declutter(shift));
                   7297:     my @uriparts=split(/\//,$uri);
                   7298:     my $filename=pop(@uriparts);
                   7299:     my $pathname=join('/',@uriparts);
                   7300:     return ($pathname,$filename);
                   7301: }
1.232     www      7302: # --------------------------------------------------- Is a resource on the map?
                   7303: 
                   7304: sub is_on_map {
1.710     albertel 7305:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7306:     #Trying to find the conditional for the file
1.620     albertel 7307:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7308: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7309:     if ($match) {
1.289     bowersj2 7310: 	return (1,$1);
                   7311:     } else {
1.434     www      7312: 	return (0,0);
1.289     bowersj2 7313:     }
1.12      www      7314: }
                   7315: 
1.427     www      7316: # --------------------------------------------------------- Get symb from alias
                   7317: 
                   7318: sub get_symb_from_alias {
                   7319:     my $symb=shift;
                   7320:     my ($map,$resid,$url)=&decode_symb($symb);
                   7321: # Already is a symb
                   7322:     if ($url) { return $symb; }
                   7323: # Must be an alias
                   7324:     my $aliassymb='';
                   7325:     my %bighash;
1.620     albertel 7326:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7327:                             &GDBM_READER(),0640)) {
                   7328:         my $rid=$bighash{'mapalias_'.$symb};
                   7329: 	if ($rid) {
                   7330: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7331: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7332: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7333: 	}
                   7334:         untie %bighash;
                   7335:     }
                   7336:     return $aliassymb;
                   7337: }
                   7338: 
1.12      www      7339: # ----------------------------------------------------------------- Define Role
                   7340: 
                   7341: sub definerole {
                   7342:   if (allowed('mcr','/')) {
                   7343:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7344:     foreach my $role (split(':',$sysrole)) {
                   7345: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7346:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7347:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7348: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7349:                return "refused:s:$crole&$cqual"; 
                   7350:             }
                   7351:         }
1.191     harris41 7352:     }
1.800     albertel 7353:     foreach my $role (split(':',$domrole)) {
                   7354: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7355:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7356:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7357: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7358:                return "refused:d:$crole&$cqual"; 
                   7359:             }
                   7360:         }
1.191     harris41 7361:     }
1.800     albertel 7362:     foreach my $role (split(':',$courole)) {
                   7363: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7364:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7365:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7366: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7367:                return "refused:c:$crole&$cqual"; 
                   7368:             }
                   7369:         }
1.191     harris41 7370:     }
1.620     albertel 7371:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7372:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7373: 	        "rolesdef_$rolename=".
                   7374:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7375:     return reply($command,$env{'user.home'});
1.12      www      7376:   } else {
                   7377:     return 'refused';
                   7378:   }
1.105     harris41 7379: }
                   7380: 
                   7381: # ---------------- Make a metadata query against the network of library servers
                   7382: 
                   7383: sub metadata_query {
1.1237    raeburn  7384:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7385:     my %rhash;
1.845     albertel 7386:     my %libserv = &all_library();
1.244     matthew  7387:     my @server_list = (defined($server_array) ? @$server_array
                   7388:                                               : keys(%libserv) );
                   7389:     for my $server (@server_list) {
1.1237    raeburn  7390:         my $domains = ''; 
                   7391:         if (ref($domains_hash) eq 'HASH') {
                   7392:             $domains = $domains_hash->{$server}; 
                   7393:         }
1.118     harris41 7394: 	unless ($custom or $customshow) {
1.1237    raeburn  7395: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7396: 	    $rhash{$server}=$reply;
                   7397: 	}
                   7398: 	else {
                   7399: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7400: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7401: 			     $server);
                   7402: 	    $rhash{$server}=$reply;
                   7403: 	}
1.112     harris41 7404:     }
1.118     harris41 7405:     return \%rhash;
1.240     www      7406: }
                   7407: 
                   7408: # ----------------------------------------- Send log queries and wait for reply
                   7409: 
                   7410: sub log_query {
                   7411:     my ($uname,$udom,$query,%filters)=@_;
                   7412:     my $uhome=&homeserver($uname,$udom);
                   7413:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7414:     my $uhost=&hostname($uhome);
1.800     albertel 7415:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7416:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7417:                        $uhome);
1.479     albertel 7418:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7419:     return get_query_reply($queryid);
                   7420: }
                   7421: 
1.818     raeburn  7422: # -------------------------- Update MySQL table for portfolio file
                   7423: 
                   7424: sub update_portfolio_table {
1.821     raeburn  7425:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7426:     if ($group ne '') {
                   7427:         $file_name =~s /^\Q$group\E//;
                   7428:     }
1.818     raeburn  7429:     my $homeserver = &homeserver($uname,$udom);
                   7430:     my $queryid=
1.821     raeburn  7431:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7432:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7433:     my $reply = &get_query_reply($queryid);
                   7434:     return $reply;
                   7435: }
                   7436: 
1.899     raeburn  7437: # -------------------------- Update MySQL allusers table
                   7438: 
                   7439: sub update_allusers_table {
                   7440:     my ($uname,$udom,$names) = @_;
                   7441:     my $homeserver = &homeserver($uname,$udom);
                   7442:     my $queryid=
                   7443:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7444:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7445:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7446:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7447:                'generation='.&escape($names->{'generation'}).'%%'.
                   7448:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7449:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7450:     return;
1.899     raeburn  7451: }
                   7452: 
1.508     raeburn  7453: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7454: 
                   7455: sub fetch_enrollment_query {
1.511     raeburn  7456:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7457:     my $homeserver;
1.547     raeburn  7458:     my $maxtries = 1;
1.508     raeburn  7459:     if ($context eq 'automated') {
                   7460:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7461:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7462:     } else {
                   7463:         $homeserver = &homeserver($cnum,$dom);
                   7464:     }
1.838     albertel 7465:     my $host=&hostname($homeserver);
1.506     raeburn  7466:     my $cmd = '';
1.1000    raeburn  7467:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7468:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7469:     }
                   7470:     $cmd =~ s/%%$//;
                   7471:     $cmd = &escape($cmd);
                   7472:     my $query = 'fetchenrollment';
1.620     albertel 7473:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7474:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7475:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7476:         return 'error: '.$queryid;
                   7477:     }
1.506     raeburn  7478:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7479:     my $tries = 1;
                   7480:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7481:         $reply = &get_query_reply($queryid);
                   7482:         $tries ++;
                   7483:     }
1.526     raeburn  7484:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7485:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7486:     } else {
1.901     albertel 7487:         my @responses = split(/:/,$reply);
1.515     raeburn  7488:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7489:             foreach my $line (@responses) {
                   7490:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7491:                 $$replyref{$key} = $value;
                   7492:             }
                   7493:         } else {
1.1117    foxr     7494:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7495:             foreach my $line (@responses) {
                   7496:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7497:                 $$replyref{$key} = $value;
                   7498:                 if ($value > 0) {
1.800     albertel 7499:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7500:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7501:                         my $destname = $pathname.'/'.$filename;
                   7502:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7503:                         if ($xml_classlist =~ /^error/) {
                   7504:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7505:                         } else {
1.506     raeburn  7506:                             if ( open(FILE,">$destname") ) {
                   7507:                                 print FILE &unescape($xml_classlist);
                   7508:                                 close(FILE);
1.526     raeburn  7509:                             } else {
                   7510:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7511:                             }
                   7512:                         }
                   7513:                     }
                   7514:                 }
                   7515:             }
                   7516:         }
                   7517:         return 'ok';
                   7518:     }
                   7519:     return 'error';
                   7520: }
                   7521: 
1.242     www      7522: sub get_query_reply {
                   7523:     my $queryid=shift;
1.1117    foxr     7524:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7525:     my $reply='';
                   7526:     for (1..100) {
                   7527: 	sleep 2;
                   7528:         if (-e $replyfile.'.end') {
1.448     albertel 7529: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7530: 		$reply = join('',<$fh>);
                   7531: 		close($fh);
1.240     www      7532: 	   } else { return 'error: reply_file_error'; }
1.242     www      7533:            return &unescape($reply);
                   7534: 	}
1.240     www      7535:     }
1.242     www      7536:     return 'timeout:'.$queryid;
1.240     www      7537: }
                   7538: 
                   7539: sub courselog_query {
1.241     www      7540: #
                   7541: # possible filters:
                   7542: # url: url or symb
                   7543: # username
                   7544: # domain
                   7545: # action: view, submit, grade
                   7546: # start: timestamp
                   7547: # end: timestamp
                   7548: #
1.240     www      7549:     my (%filters)=@_;
1.620     albertel 7550:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7551:     if ($filters{'url'}) {
                   7552: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7553:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7554:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7555:     }
1.620     albertel 7556:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7557:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7558:     return &log_query($cname,$cdom,'courselog',%filters);
                   7559: }
                   7560: 
                   7561: sub userlog_query {
1.858     raeburn  7562: #
                   7563: # possible filters:
                   7564: # action: log check role
                   7565: # start: timestamp
                   7566: # end: timestamp
                   7567: #
1.240     www      7568:     my ($uname,$udom,%filters)=@_;
                   7569:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7570: }
                   7571: 
1.506     raeburn  7572: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7573: 
                   7574: sub auto_run {
1.508     raeburn  7575:     my ($cnum,$cdom) = @_;
1.876     raeburn  7576:     my $response = 0;
                   7577:     my $settings;
                   7578:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7579:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7580:         $settings = $domconfig{'autoenroll'};
                   7581:         if ($settings->{'run'} eq '1') {
                   7582:             $response = 1;
                   7583:         }
                   7584:     } else {
1.934     raeburn  7585:         my $homeserver;
                   7586:         if (&is_course($cdom,$cnum)) {
                   7587:             $homeserver = &homeserver($cnum,$cdom);
                   7588:         } else {
                   7589:             $homeserver = &domain($cdom,'primary');
                   7590:         }
                   7591:         if ($homeserver ne 'no_host') {
                   7592:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7593:         }
1.876     raeburn  7594:     }
1.506     raeburn  7595:     return $response;
                   7596: }
1.776     albertel 7597: 
1.506     raeburn  7598: sub auto_get_sections {
1.508     raeburn  7599:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7600:     my $homeserver;
                   7601:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7602:         $homeserver = &homeserver($cnum,$cdom);
                   7603:     }
                   7604:     if (!defined($homeserver)) { 
                   7605:         if ($cdom =~ /^$match_domain$/) {
                   7606:             $homeserver = &domain($cdom,'primary');
                   7607:         }
                   7608:     }
                   7609:     my @secs;
                   7610:     if (defined($homeserver)) {
                   7611:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7612:         unless ($response eq 'refused') {
                   7613:             @secs = split(/:/,$response);
                   7614:         }
1.506     raeburn  7615:     }
                   7616:     return @secs;
                   7617: }
1.776     albertel 7618: 
1.506     raeburn  7619: sub auto_new_course {
1.1099    raeburn  7620:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7621:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7622:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7623:     return $response;
                   7624: }
1.776     albertel 7625: 
1.506     raeburn  7626: sub auto_validate_courseID {
1.508     raeburn  7627:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7628:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7629:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7630:     return $response;
                   7631: }
1.776     albertel 7632: 
1.1007    raeburn  7633: sub auto_validate_instcode {
1.1020    raeburn  7634:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7635:     my ($homeserver,$response);
                   7636:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7637:         $homeserver = &homeserver($cnum,$cdom);
                   7638:     }
                   7639:     if (!defined($homeserver)) {
                   7640:         if ($cdom =~ /^$match_domain$/) {
                   7641:             $homeserver = &domain($cdom,'primary');
                   7642:         }
                   7643:     }
1.1065    raeburn  7644:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7645:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  7646:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7647:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7648: }
                   7649: 
1.506     raeburn  7650: sub auto_create_password {
1.873     raeburn  7651:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7652:     my ($homeserver,$response);
1.506     raeburn  7653:     my $create_passwd = 0;
                   7654:     my $authchk = '';
1.873     raeburn  7655:     if ($udom =~ /^$match_domain$/) {
                   7656:         $homeserver = &domain($udom,'primary');
                   7657:     }
                   7658:     if ($homeserver eq '') {
                   7659:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7660:             $homeserver = &homeserver($cnum,$cdom);
                   7661:         }
                   7662:     }
                   7663:     if ($homeserver eq '') {
                   7664:         $authchk = 'nodomain';
1.506     raeburn  7665:     } else {
1.873     raeburn  7666:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7667:         if ($response eq 'refused') {
                   7668:             $authchk = 'refused';
                   7669:         } else {
1.901     albertel 7670:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7671:         }
1.506     raeburn  7672:     }
                   7673:     return ($authparam,$create_passwd,$authchk);
                   7674: }
                   7675: 
1.706     raeburn  7676: sub auto_photo_permission {
                   7677:     my ($cnum,$cdom,$students) = @_;
                   7678:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7679:     my ($outcome,$perm_reqd,$conditions) = 
                   7680: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7681:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7682: 	return (undef,undef);
                   7683:     }
1.706     raeburn  7684:     return ($outcome,$perm_reqd,$conditions);
                   7685: }
                   7686: 
                   7687: sub auto_checkphotos {
                   7688:     my ($uname,$udom,$pid) = @_;
                   7689:     my $homeserver = &homeserver($uname,$udom);
                   7690:     my ($result,$resulttype);
                   7691:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7692: 				   &escape($uname).':'.&escape($pid),
                   7693: 				   $homeserver));
1.709     albertel 7694:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7695: 	return (undef,undef);
                   7696:     }
1.706     raeburn  7697:     if ($outcome) {
                   7698:         ($result,$resulttype) = split(/:/,$outcome);
                   7699:     } 
                   7700:     return ($result,$resulttype);
                   7701: }
                   7702: 
                   7703: sub auto_photochoice {
                   7704:     my ($cnum,$cdom) = @_;
                   7705:     my $homeserver = &homeserver($cnum,$cdom);
                   7706:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7707: 						       &escape($cdom),
                   7708: 						       $homeserver)));
1.709     albertel 7709:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7710: 	return (undef,undef);
                   7711:     }
1.706     raeburn  7712:     return ($update,$comment);
                   7713: }
                   7714: 
                   7715: sub auto_photoupdate {
                   7716:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7717:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7718:     my $host=&hostname($homeserver);
1.706     raeburn  7719:     my $cmd = '';
                   7720:     my $maxtries = 1;
1.800     albertel 7721:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7722:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7723:     }
                   7724:     $cmd =~ s/%%$//;
                   7725:     $cmd = &escape($cmd);
                   7726:     my $query = 'institutionalphotos';
                   7727:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7728:     unless ($queryid=~/^\Q$host\E\_/) {
                   7729:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7730:         return 'error: '.$queryid;
                   7731:     }
                   7732:     my $reply = &get_query_reply($queryid);
                   7733:     my $tries = 1;
                   7734:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7735:         $reply = &get_query_reply($queryid);
                   7736:         $tries ++;
                   7737:     }
                   7738:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7739:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7740:     } else {
                   7741:         my @responses = split(/:/,$reply);
                   7742:         my $outcome = shift(@responses); 
                   7743:         foreach my $item (@responses) {
                   7744:             my ($key,$value) = split(/=/,$item);
                   7745:             $$photo{$key} = $value;
                   7746:         }
                   7747:         return $outcome;
                   7748:     }
                   7749:     return 'error';
                   7750: }
                   7751: 
1.521     raeburn  7752: sub auto_instcode_format {
1.793     albertel 7753:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7754: 	$cat_order) = @_;
1.521     raeburn  7755:     my $courses = '';
1.772     raeburn  7756:     my @homeservers;
1.521     raeburn  7757:     if ($caller eq 'global') {
1.841     albertel 7758: 	my %servers = &get_servers($codedom,'library');
                   7759: 	foreach my $tryserver (keys(%servers)) {
                   7760: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7761: 		push(@homeservers,$tryserver);
                   7762: 	    }
1.584     raeburn  7763:         }
1.1022    raeburn  7764:     } elsif ($caller eq 'requests') {
                   7765:         if ($codedom =~ /^$match_domain$/) {
                   7766:             my $chome = &domain($codedom,'primary');
                   7767:             unless ($chome eq 'no_host') {
                   7768:                 push(@homeservers,$chome);
                   7769:             }
                   7770:         }
1.521     raeburn  7771:     } else {
1.772     raeburn  7772:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7773:     }
1.793     albertel 7774:     foreach my $code (keys(%{$instcodes})) {
                   7775:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7776:     }
                   7777:     chop($courses);
1.772     raeburn  7778:     my $ok_response = 0;
                   7779:     my $response;
                   7780:     while (@homeservers > 0 && $ok_response == 0) {
                   7781:         my $server = shift(@homeservers); 
                   7782:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7783:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7784:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7785: 		split(/:/,$response);
1.772     raeburn  7786:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7787:             push(@{$codetitles},&str2array($codetitles_str));
                   7788:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7789:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7790:             $ok_response = 1;
                   7791:         }
                   7792:     }
                   7793:     if ($ok_response) {
1.521     raeburn  7794:         return 'ok';
1.772     raeburn  7795:     } else {
                   7796:         return $response;
1.521     raeburn  7797:     }
                   7798: }
                   7799: 
1.792     raeburn  7800: sub auto_instcode_defaults {
                   7801:     my ($domain,$returnhash,$code_order) = @_;
                   7802:     my @homeservers;
1.841     albertel 7803: 
                   7804:     my %servers = &get_servers($domain,'library');
                   7805:     foreach my $tryserver (keys(%servers)) {
                   7806: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7807: 	    push(@homeservers,$tryserver);
                   7808: 	}
1.792     raeburn  7809:     }
1.841     albertel 7810: 
1.792     raeburn  7811:     my $response;
1.841     albertel 7812:     foreach my $server (@homeservers) {
1.792     raeburn  7813:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7814:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7815: 	
                   7816: 	foreach my $pair (split(/\&/,$response)) {
                   7817: 	    my ($name,$value)=split(/\=/,$pair);
                   7818: 	    if ($name eq 'code_order') {
                   7819: 		@{$code_order} = split(/\&/,&unescape($value));
                   7820: 	    } else {
                   7821: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7822: 	    }
                   7823: 	}
                   7824: 	return 'ok';
1.792     raeburn  7825:     }
1.841     albertel 7826: 
                   7827:     return $response;
1.1003    raeburn  7828: }
                   7829: 
                   7830: sub auto_possible_instcodes {
1.1007    raeburn  7831:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7832:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7833:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7834:         return;
                   7835:     }
1.1003    raeburn  7836:     my (@homeservers,$uhome);
                   7837:     if (defined(&domain($domain,'primary'))) {
                   7838:         $uhome=&domain($domain,'primary');
                   7839:         push(@homeservers,&domain($domain,'primary'));
                   7840:     } else {
                   7841:         my %servers = &get_servers($domain,'library');
                   7842:         foreach my $tryserver (keys(%servers)) {
                   7843:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7844:                 push(@homeservers,$tryserver);
                   7845:             }
                   7846:         }
                   7847:     }
                   7848:     my $response;
                   7849:     foreach my $server (@homeservers) {
                   7850:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7851:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7852:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7853:             split(':',$response);
                   7854:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7855:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7856:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7857:             my ($name,$value)=split('=',$item);
                   7858:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7859:         }
                   7860:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7861:             my ($name,$value)=split('=',$item);
                   7862:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7863:         }
                   7864:         return 'ok';
                   7865:     }
                   7866:     return $response;
                   7867: }
1.792     raeburn  7868: 
1.1010    raeburn  7869: sub auto_courserequest_checks {
                   7870:     my ($dom) = @_;
1.1020    raeburn  7871:     my ($homeserver,%validations);
                   7872:     if ($dom =~ /^$match_domain$/) {
                   7873:         $homeserver = &domain($dom,'primary');
                   7874:     }
                   7875:     unless ($homeserver eq 'no_host') {
                   7876:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7877:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7878:             my @items = split(/&/,$response);
                   7879:             foreach my $item (@items) {
                   7880:                 my ($key,$value) = split('=',$item);
                   7881:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7882:             }
                   7883:         }
                   7884:     }
1.1010    raeburn  7885:     return %validations; 
                   7886: }
                   7887: 
1.1020    raeburn  7888: sub auto_courserequest_validation {
1.1255    raeburn  7889:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  7890:     my ($homeserver,$response);
                   7891:     if ($dom =~ /^$match_domain$/) {
                   7892:         $homeserver = &domain($dom,'primary');
                   7893:     }
1.1255    raeburn  7894:     unless ($homeserver eq 'no_host') {
                   7895:         my $customdata;
                   7896:         if (ref($custominfo) eq 'HASH') {
                   7897:             $customdata = &freeze_escape($custominfo);
                   7898:         }
1.1020    raeburn  7899:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7900:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  7901:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   7902:                                     $customdata,$homeserver));
1.1020    raeburn  7903:     }
                   7904:     return $response;
                   7905: }
                   7906: 
1.777     albertel 7907: sub auto_validate_class_sec {
1.918     raeburn  7908:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7909:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7910:     my $ownerlist;
                   7911:     if (ref($owners) eq 'ARRAY') {
                   7912:         $ownerlist = join(',',@{$owners});
                   7913:     } else {
                   7914:         $ownerlist = $owners;
                   7915:     }
1.773     raeburn  7916:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7917:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7918:     return $response;
                   7919: }
                   7920: 
1.1248    raeburn  7921: sub auto_crsreq_update {
                   7922:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  7923:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  7924:     my ($homeserver,%crsreqresponse);
                   7925:     if ($cdom =~ /^$match_domain$/) {
                   7926:         $homeserver = &domain($cdom,'primary');
                   7927:     }
                   7928:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   7929:         my $info;
                   7930:         if (ref($inbound) eq 'HASH') {
                   7931:             $info = &freeze_escape($inbound);
                   7932:         }
                   7933:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   7934:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   7935:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  7936:                             &escape($title).':'.&escape($code).':'.
                   7937:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   7938:                             $homeserver);
1.1248    raeburn  7939:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7940:             my @items = split(/&/,$response);
                   7941:             foreach my $item (@items) {
                   7942:                 my ($key,$value) = split('=',$item);
                   7943:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   7944:             }
                   7945:         }
                   7946:     }
                   7947:     return \%crsreqresponse;
                   7948: }
                   7949: 
1.679     raeburn  7950: # ------------------------------------------------------- Course Group routines
                   7951: 
                   7952: sub get_coursegroups {
1.809     raeburn  7953:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7954:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7955: }
                   7956: 
1.679     raeburn  7957: sub modify_coursegroup {
                   7958:     my ($cdom,$cnum,$groupsettings) = @_;
                   7959:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7960: }
                   7961: 
1.809     raeburn  7962: sub toggle_coursegroup_status {
                   7963:     my ($cdom,$cnum,$group,$action) = @_;
                   7964:     my ($from_namespace,$to_namespace);
                   7965:     if ($action eq 'delete') {
                   7966:         $from_namespace = 'coursegroups';
                   7967:         $to_namespace = 'deleted_groups';
                   7968:     } else {
                   7969:         $from_namespace = 'deleted_groups';
                   7970:         $to_namespace = 'coursegroups';
                   7971:     }
                   7972:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7973:     if (my $tmp = &error(%curr_group)) {
                   7974:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7975:         return ('read error',$tmp);
                   7976:     } else {
                   7977:         my %savedsettings = %curr_group; 
1.809     raeburn  7978:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7979:         my $deloutcome;
                   7980:         if ($result eq 'ok') {
1.809     raeburn  7981:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7982:         } else {
                   7983:             return ('write error',$result);
                   7984:         }
                   7985:         if ($deloutcome eq 'ok') {
                   7986:             return 'ok';
                   7987:         } else {
                   7988:             return ('delete error',$deloutcome);
                   7989:         }
                   7990:     }
                   7991: }
                   7992: 
1.679     raeburn  7993: sub modify_group_roles {
1.957     raeburn  7994:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7995:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7996:     my $role = 'gr/'.&escape($userprivs);
                   7997:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7998:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7999:     if ($result eq 'ok') {
                   8000:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8001:     }
1.679     raeburn  8002:     return $result;
                   8003: }
                   8004: 
                   8005: sub modify_coursegroup_membership {
                   8006:     my ($cdom,$cnum,$membership) = @_;
                   8007:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8008:     return $result;
                   8009: }
                   8010: 
1.682     raeburn  8011: sub get_active_groups {
                   8012:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8013:     my $now = time;
                   8014:     my %groups = ();
                   8015:     foreach my $key (keys(%env)) {
1.811     albertel 8016:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8017:             my ($start,$end) = split(/\./,$env{$key});
                   8018:             if (($end!=0) && ($end<$now)) { next; }
                   8019:             if (($start!=0) && ($start>$now)) { next; }
                   8020:             if ($1 eq $cdom && $2 eq $cnum) {
                   8021:                 $groups{$3} = $env{$key} ;
                   8022:             }
                   8023:         }
                   8024:     }
                   8025:     return %groups;
                   8026: }
                   8027: 
1.683     raeburn  8028: sub get_group_membership {
                   8029:     my ($cdom,$cnum,$group) = @_;
                   8030:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8031: }
                   8032: 
                   8033: sub get_users_groups {
                   8034:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8035:     my @usersgroups;
1.683     raeburn  8036:     my $cachetime=1800;
                   8037: 
                   8038:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8039:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8040:     if (defined($cached)) {
1.734     albertel 8041:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8042:     } else {  
                   8043:         $grouplist = '';
1.816     raeburn  8044:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8045:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8046:         my $access_end = $env{'course.'.$courseid.
                   8047:                               '.default_enrollment_end_date'};
                   8048:         my $now = time;
                   8049:         foreach my $key (keys(%roleshash)) {
                   8050:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8051:                 my $group = $1;
                   8052:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8053:                     my $start = $2;
                   8054:                     my $end = $1;
                   8055:                     if ($start == -1) { next; } # deleted from group
                   8056:                     if (($start!=0) && ($start>$now)) { next; }
                   8057:                     if (($end!=0) && ($end<$now)) {
                   8058:                         if ($access_end && $access_end < $now) {
                   8059:                             if ($access_end - $end < 86400) {
                   8060:                                 push(@usersgroups,$group);
1.733     raeburn  8061:                             }
                   8062:                         }
1.817     raeburn  8063:                         next;
1.733     raeburn  8064:                     }
1.817     raeburn  8065:                     push(@usersgroups,$group);
1.683     raeburn  8066:                 }
                   8067:             }
                   8068:         }
1.817     raeburn  8069:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8070:         $grouplist = join(':',@usersgroups);
                   8071:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8072:     }
1.733     raeburn  8073:     return @usersgroups;
1.683     raeburn  8074: }
                   8075: 
                   8076: sub devalidate_getgroups_cache {
                   8077:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8078:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8079: 
1.683     raeburn  8080:     my $hashid="$udom:$uname:$courseid";
                   8081:     &devalidate_cache_new('getgroups',$hashid);
                   8082: }
                   8083: 
1.12      www      8084: # ------------------------------------------------------------------ Plain Text
                   8085: 
                   8086: sub plaintext {
1.988     raeburn  8087:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8088:     if ($short =~ m{^cr/}) {
1.758     albertel 8089: 	return (split('/',$short))[-1];
                   8090:     }
1.742     raeburn  8091:     if (!defined($cid)) {
                   8092:         $cid = $env{'request.course.id'};
                   8093:     }
                   8094:     my %rolenames = (
1.1008    raeburn  8095:                       Course    => 'std',
                   8096:                       Community => 'alt1',
1.742     raeburn  8097:                     );
1.1037    raeburn  8098:     if ($cid ne '') {
                   8099:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8100:             unless ($forcedefault) {
                   8101:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8102:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8103:                 return &Apache::lonlocal::mt($roletext);
                   8104:             }
                   8105:         }
                   8106:     }
                   8107:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8108:         (defined($rolenames{$type})) && 
                   8109:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8110:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8111:     } elsif ($cid ne '') {
                   8112:         my $crstype = $env{'course.'.$cid.'.type'};
                   8113:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8114:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8115:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8116:         }
1.742     raeburn  8117:     }
1.1037    raeburn  8118:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8119: }
                   8120: 
                   8121: # ----------------------------------------------------------------- Assign Role
                   8122: 
                   8123: sub assignrole {
1.957     raeburn  8124:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8125:         $context)=@_;
1.21      www      8126:     my $mrole;
                   8127:     if ($role =~ /^cr\//) {
1.393     www      8128:         my $cwosec=$url;
1.811     albertel 8129:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8130: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8131:            my $refused = 1;
                   8132:            if ($context eq 'requestcourses') {
                   8133:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8134:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8135:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8136:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8137:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8138:                            if ($crsenv{'internal.courseowner'} eq
                   8139:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8140:                                $refused = '';
                   8141:                            }
                   8142:                        }
                   8143:                    }
                   8144:                }
                   8145:            }
                   8146:            if ($refused) {
                   8147:                &logthis('Refused custom assignrole: '.
                   8148:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8149:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8150:                return 'refused';
                   8151:            }
1.104     www      8152:         }
1.21      www      8153:         $mrole='cr';
1.678     raeburn  8154:     } elsif ($role =~ /^gr\//) {
                   8155:         my $cwogrp=$url;
1.811     albertel 8156:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8157:         unless (&allowed('mdg',$cwogrp)) {
                   8158:             &logthis('Refused group assignrole: '.
                   8159:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8160:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8161:             return 'refused';
                   8162:         }
                   8163:         $mrole='gr';
1.21      www      8164:     } else {
1.82      www      8165:         my $cwosec=$url;
1.811     albertel 8166:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8167:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8168:             my $refused;
                   8169:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8170:                 if (!(&allowed('c'.$role,$url))) {
                   8171:                     $refused = 1;
                   8172:                 }
                   8173:             } else {
                   8174:                 $refused = 1;
                   8175:             }
1.947     raeburn  8176:             if ($refused) {
1.1045    raeburn  8177:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8178:                 if (!$selfenroll && $context eq 'course') {
                   8179:                     my %crsenv;
                   8180:                     if ($role eq 'cc' || $role eq 'co') {
                   8181:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8182:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8183:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8184:                                 if ($crsenv{'internal.courseowner'} eq 
                   8185:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8186:                                     $refused = '';
                   8187:                                 }
                   8188:                             }
                   8189:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8190:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8191:                                 if ($crsenv{'internal.courseowner'} eq 
                   8192:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8193:                                     $refused = '';
                   8194:                                 }
                   8195:                             }
                   8196:                         }
                   8197:                     }
                   8198:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8199:                     $refused = '';
1.1017    raeburn  8200:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8201:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8202:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8203:                         my $wrongcc;
                   8204:                         if ($cnum =~ /^$match_community$/) {
                   8205:                             $wrongcc = 1 if ($role eq 'cc');
                   8206:                         } else {
                   8207:                             $wrongcc = 1 if ($role eq 'co');
                   8208:                         }
                   8209:                         unless ($wrongcc) {
                   8210:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8211:                             if ($crsenv{'internal.courseowner'} eq 
                   8212:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8213:                                 $refused = '';
                   8214:                             }
1.1017    raeburn  8215:                         }
                   8216:                     }
1.1183    raeburn  8217:                 } elsif ($context eq 'requestauthor') {
                   8218:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8219:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8220:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8221:                             $refused = '';
                   8222:                         } else {
                   8223:                             my %domdefaults = &get_domain_defaults($udom);
                   8224:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8225:                                 my $checkbystatus;
                   8226:                                 if ($env{'user.adv'}) { 
                   8227:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8228:                                     if ($disposition eq 'automatic') {
                   8229:                                         $refused = '';
                   8230:                                     } elsif ($disposition eq '') {
                   8231:                                         $checkbystatus = 1;
                   8232:                                     } 
                   8233:                                 } else {
                   8234:                                     $checkbystatus = 1;
                   8235:                                 }
                   8236:                                 if ($checkbystatus) {
                   8237:                                     if ($env{'environment.inststatus'}) {
                   8238:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8239:                                         foreach my $type (@inststatuses) {
                   8240:                                             if (($type ne '') &&
                   8241:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8242:                                                 $refused = '';
                   8243:                                             }
                   8244:                                         }
                   8245:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8246:                                         $refused = '';
                   8247:                                     }
                   8248:                                 }
                   8249:                             }
                   8250:                         }
                   8251:                     }
1.1017    raeburn  8252:                 }
                   8253:                 if ($refused) {
1.947     raeburn  8254:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8255:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8256: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8257:                     return 'refused';
                   8258:                 }
1.932     raeburn  8259:             }
1.1131    raeburn  8260:         } elsif ($role eq 'au') {
                   8261:             if ($url ne '/'.$udom.'/') {
                   8262:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8263:                          ' to assign author role for '.$uname.':'.$udom.
                   8264:                          ' in domain: '.$url.' refused (wrong domain).');
                   8265:                 return 'refused';
                   8266:             }
1.104     www      8267:         }
1.21      www      8268:         $mrole=$role;
                   8269:     }
1.620     albertel 8270:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8271:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8272:     if ($end) { $command.='_'.$end; }
1.21      www      8273:     if ($start) {
                   8274: 	if ($end) { 
1.81      www      8275:            $command.='_'.$start; 
1.21      www      8276:         } else {
1.81      www      8277:            $command.='_0_'.$start;
1.21      www      8278:         }
                   8279:     }
1.739     raeburn  8280:     my $origstart = $start;
                   8281:     my $origend = $end;
1.957     raeburn  8282:     my $delflag;
1.357     www      8283: # actually delete
                   8284:     if ($deleteflag) {
1.373     www      8285: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8286: # modify command to delete the role
1.620     albertel 8287:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8288:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8289: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8290: # set start and finish to negative values for userrolelog
                   8291:            $start=-1;
                   8292:            $end=-1;
1.957     raeburn  8293:            $delflag = 1;
1.357     www      8294:         }
                   8295:     }
                   8296: # send command
1.349     www      8297:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8298: # log new user role if status is ok
1.349     www      8299:     if ($answer eq 'ok') {
1.663     raeburn  8300: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8301:         if (($role eq 'cc') || ($role eq 'in') ||
                   8302:             ($role eq 'ep') || ($role eq 'ad') ||
                   8303:             ($role eq 'ta') || ($role eq 'st') ||
                   8304:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8305:             ($role eq 'co')) {
1.1200    raeburn  8306: # for course roles, perform group memberships changes triggered by role change.
                   8307:             unless ($role =~ /^gr/) {
                   8308:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8309:                                                  $origstart,$selfenroll,$context);
                   8310:             }
1.1184    raeburn  8311:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8312:                            $selfenroll,$context);
                   8313:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8314:                  ($role eq 'au') || ($role eq 'dc')) {
                   8315:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8316:                            $context);
                   8317:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8318:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8319:                              $context); 
                   8320:         }
1.1053    raeburn  8321:         if ($role eq 'cc') {
                   8322:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8323:         }
1.349     www      8324:     }
                   8325:     return $answer;
1.169     harris41 8326: }
                   8327: 
1.1053    raeburn  8328: sub autoupdate_coowners {
                   8329:     my ($url,$end,$start,$uname,$udom) = @_;
                   8330:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8331:     if (($cdom ne '') && ($cnum ne '')) {
                   8332:         my $now = time;
                   8333:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8334:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8335:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8336:             my $instcode = $coursehash{'internal.coursecode'};
                   8337:             if ($instcode ne '') {
1.1056    raeburn  8338:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8339:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8340:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8341:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8342:                         if ($result eq 'valid') {
                   8343:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8344:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8345:                                     push(@newcoowners,$coowner);
                   8346:                                 }
                   8347:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8348:                                     push(@newcoowners,$uname.':'.$udom);
                   8349:                                 }
                   8350:                                 @newcoowners = sort(@newcoowners);
                   8351:                             } else {
                   8352:                                 push(@newcoowners,$uname.':'.$udom);
                   8353:                             }
                   8354:                         } else {
                   8355:                             if ($coursehash{'internal.co-owners'}) {
                   8356:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8357:                                     unless ($coowner eq $uname.':'.$udom) {
                   8358:                                         push(@newcoowners,$coowner);
                   8359:                                     }
                   8360:                                 }
                   8361:                                 unless (@newcoowners > 0) {
                   8362:                                     $delcoowners = 1;
                   8363:                                     $coowners = '';
                   8364:                                 }
                   8365:                             }
                   8366:                         }
                   8367:                         if (@newcoowners || $delcoowners) {
                   8368:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8369:                                             $delcoowners,@newcoowners);
                   8370:                         }
                   8371:                     }
                   8372:                 }
                   8373:             }
                   8374:         }
                   8375:     }
                   8376: }
                   8377: 
                   8378: sub store_coowners {
                   8379:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8380:     my $cid = $cdom.'_'.$cnum;
                   8381:     my ($coowners,$delresult,$putresult);
                   8382:     if (@newcoowners) {
                   8383:         $coowners = join(',',@newcoowners);
                   8384:         my %coownershash = (
                   8385:                             'internal.co-owners' => $coowners,
                   8386:                            );
                   8387:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8388:         if ($putresult eq 'ok') {
                   8389:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8390:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8391:             }
                   8392:         }
                   8393:     }
                   8394:     if ($delcoowners) {
                   8395:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8396:         if ($delresult eq 'ok') {
                   8397:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8398:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8399:             }
                   8400:         }
                   8401:     }
                   8402:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8403:         my %crsinfo =
                   8404:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8405:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8406:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8407:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8408:         }
                   8409:     }
                   8410: }
                   8411: 
1.169     harris41 8412: # -------------------------------------------------- Modify user authentication
1.197     www      8413: # Overrides without validation
                   8414: 
1.169     harris41 8415: sub modifyuserauth {
                   8416:     my ($udom,$uname,$umode,$upass)=@_;
                   8417:     my $uhome=&homeserver($uname,$udom);
1.197     www      8418:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8419:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8420:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8421:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8422:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8423: 		     &escape($upass),$uhome);
1.620     albertel 8424:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8425:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8426:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8427:     &log($udom,,$uname,$uhome,
1.620     albertel 8428:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8429:                                      $env{'user.name'}.', '.$umode.
1.197     www      8430:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8431:     unless ($reply eq 'ok') {
1.197     www      8432:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8433: 	return 'error: '.$reply;
                   8434:     }   
1.170     harris41 8435:     return 'ok';
1.80      www      8436: }
                   8437: 
1.81      www      8438: # --------------------------------------------------------------- Modify a user
1.80      www      8439: 
1.81      www      8440: sub modifyuser {
1.206     matthew  8441:     my ($udom,    $uname, $uid,
                   8442:         $umode,   $upass, $first,
                   8443:         $middle,  $last,  $gene,
1.1058    raeburn  8444:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8445:     $udom= &LONCAPA::clean_domain($udom);
                   8446:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8447:     my $showcandelete = 'none';
                   8448:     if (ref($candelete) eq 'ARRAY') {
                   8449:         if (@{$candelete} > 0) {
                   8450:             $showcandelete = join(', ',@{$candelete});
                   8451:         }
                   8452:     }
1.81      www      8453:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8454:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8455: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8456:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8457:                                      ' desiredhome not specified'). 
1.620     albertel 8458:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8459:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8460:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8461:     my $newuser;
                   8462:     if ($uhome eq 'no_host') {
                   8463:         $newuser = 1;
                   8464:     }
1.80      www      8465: # ----------------------------------------------------------------- Create User
1.406     albertel 8466:     if (($uhome eq 'no_host') && 
                   8467: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8468:         my $unhome='';
1.844     albertel 8469:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8470:             $unhome = $desiredhome;
1.620     albertel 8471: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8472: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8473:         } else { # load balancing routine for determining $unhome
1.81      www      8474:             my $loadm=10000000;
1.841     albertel 8475: 	    my %servers = &get_servers($udom,'library');
                   8476: 	    foreach my $tryserver (keys(%servers)) {
                   8477: 		my $answer=reply('load',$tryserver);
                   8478: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8479: 		    $loadm=$answer;
                   8480: 		    $unhome=$tryserver;
                   8481: 		}
1.80      www      8482: 	    }
                   8483:         }
                   8484:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8485: 	    return 'error: unable to find a home server for '.$uname.
                   8486:                    ' in domain '.$udom;
1.80      www      8487:         }
                   8488:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8489:                          &escape($upass),$unhome);
                   8490: 	unless ($reply eq 'ok') {
                   8491:             return 'error: '.$reply;
                   8492:         }   
1.230     stredwic 8493:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8494:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8495: 	    return 'error: unable verify users home machine.';
1.80      www      8496:         }
1.209     matthew  8497:     }   # End of creation of new user
1.80      www      8498: # ---------------------------------------------------------------------- Add ID
                   8499:     if ($uid) {
                   8500:        $uid=~tr/A-Z/a-z/;
                   8501:        my %uidhash=&idrget($udom,$uname);
1.196     www      8502:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8503:          && (!$forceid)) {
1.80      www      8504: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8505: 	      return 'error: user id "'.$uid.'" does not match '.
                   8506:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8507:           }
                   8508:        } else {
                   8509: 	  &idput($udom,($uname => $uid));
                   8510:        }
                   8511:     }
                   8512: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8513:     my @tmp=&get('environment',
1.899     raeburn  8514: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8515:                     'permanentemail','inststatus'],
1.134     albertel 8516: 		   $udom,$uname);
1.1075    raeburn  8517:     my (%names,%oldnames);
1.313     matthew  8518:     if ($tmp[0] =~ m/^error:.*/) { 
                   8519:         %names=(); 
                   8520:     } else {
                   8521:         %names = @tmp;
1.1075    raeburn  8522:         %oldnames = %names;
1.313     matthew  8523:     }
1.388     www      8524: #
1.1058    raeburn  8525: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8526: # of users did not contain them), do not overwrite existing values
                   8527: # unless field is in $candelete array ref.  
                   8528: #
                   8529: 
                   8530:     my @fields = ('firstname','middlename','lastname','generation',
                   8531:                   'permanentemail','id');
                   8532:     my %newvalues;
                   8533:     if (ref($candelete) eq 'ARRAY') {
                   8534:         foreach my $field (@fields) {
                   8535:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8536:                 if ($field eq 'firstname') {
                   8537:                     $names{$field} = $first;
                   8538:                 } elsif ($field eq 'middlename') {
                   8539:                     $names{$field} = $middle;
                   8540:                 } elsif ($field eq 'lastname') {
                   8541:                     $names{$field} = $last;
                   8542:                 } elsif ($field eq 'generation') { 
                   8543:                     $names{$field} = $gene;
                   8544:                 } elsif ($field eq 'permanentemail') {
                   8545:                     $names{$field} = $email;
                   8546:                 } elsif ($field eq 'id') {
                   8547:                     $names{$field}  = $uid;
                   8548:                 }
                   8549:             }
                   8550:         }
                   8551:     }
1.388     www      8552:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8553:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8554:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8555:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8556:     if ($email) {
                   8557:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8558:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8559:     }
1.899     raeburn  8560:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8561:     if (defined($inststatus)) {
                   8562:         $names{'inststatus'} = '';
                   8563:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8564:         if (ref($usertypes) eq 'HASH') {
                   8565:             my @okstatuses; 
                   8566:             foreach my $item (split(/:/,$inststatus)) {
                   8567:                 if (defined($usertypes->{$item})) {
                   8568:                     push(@okstatuses,$item);  
                   8569:                 }
                   8570:             }
                   8571:             if (@okstatuses) {
                   8572:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8573:             }
                   8574:         }
                   8575:     }
1.1075    raeburn  8576:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8577:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8578:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8579:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8580:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8581:     } else {
                   8582:         $logmsg .= ' during self creation';
                   8583:     }
1.1075    raeburn  8584:     my $changed;
                   8585:     if ($newuser) {
                   8586:         $changed = 1;
                   8587:     } else {
                   8588:         foreach my $field (@fields) {
                   8589:             if ($names{$field} ne $oldnames{$field}) {
                   8590:                 $changed = 1;
                   8591:                 last;
                   8592:             }
                   8593:         }
                   8594:     }
                   8595:     unless ($changed) {
                   8596:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8597:         &logthis($logmsg);
                   8598:         return 'ok';
                   8599:     }
                   8600:     my $reply = &put('environment', \%names, $udom,$uname);
                   8601:     if ($reply ne 'ok') { 
                   8602:         return 'error: '.$reply;
                   8603:     }
1.1087    raeburn  8604:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8605:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8606:     }
1.1075    raeburn  8607:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8608:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8609:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8610:     &logthis($logmsg);
1.134     albertel 8611:     return 'ok';
1.80      www      8612: }
                   8613: 
1.81      www      8614: # -------------------------------------------------------------- Modify student
1.80      www      8615: 
1.81      www      8616: sub modifystudent {
                   8617:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8618:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216    raeburn  8619:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8620:     if (!$cid) {
1.620     albertel 8621: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8622: 	    return 'not_in_class';
                   8623: 	}
1.80      www      8624:     }
                   8625: # --------------------------------------------------------------- Make the user
1.81      www      8626:     my $reply=&modifyuser
1.209     matthew  8627: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8628:          $desiredhome,$email,$inststatus);
1.80      www      8629:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8630:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  8631:     # student's environment
1.297     matthew  8632:     $uid = undef if (!$forceid);
1.455     albertel 8633:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  8634:                                         $gene,$usec,$end,$start,$type,$locktype,
                   8635:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8636:     return $reply;
                   8637: }
                   8638: 
                   8639: sub modify_student_enrollment {
1.1216    raeburn  8640:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8641:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8642:     my ($cdom,$cnum,$chome);
                   8643:     if (!$cid) {
1.620     albertel 8644: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8645: 	    return 'not_in_class';
                   8646: 	}
1.620     albertel 8647: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8648: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8649:     } else {
                   8650: 	($cdom,$cnum)=split(/_/,$cid);
                   8651:     }
1.620     albertel 8652:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8653:     if (!$chome) {
1.457     raeburn  8654: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8655:     }
1.455     albertel 8656:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8657:     # Make sure the user exists
1.81      www      8658:     my $uhome=&homeserver($uname,$udom);
                   8659:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8660: 	return 'error: no such user';
                   8661:     }
1.297     matthew  8662:     # Get student data if we were not given enough information
                   8663:     if (!defined($first)  || $first  eq '' || 
                   8664:         !defined($last)   || $last   eq '' || 
                   8665:         !defined($uid)    || $uid    eq '' || 
                   8666:         !defined($middle) || $middle eq '' || 
                   8667:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8668:         # They did not supply us with enough data to enroll the student, so
                   8669:         # we need to pick up more information.
1.297     matthew  8670:         my %tmp = &get('environment',
1.294     matthew  8671:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8672:                        ,$udom,$uname);
                   8673: 
1.800     albertel 8674:         #foreach my $key (keys(%tmp)) {
                   8675:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8676:         #}
1.294     matthew  8677:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8678:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8679:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8680:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8681:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8682:     }
1.556     albertel 8683:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8684:     my $user = "$uname:$udom";
                   8685:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8686:     my $reply=cput('classlist',
1.1148    raeburn  8687: 		   {$user => 
1.1216    raeburn  8688: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8689: 		   $cdom,$cnum);
1.1148    raeburn  8690:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8691:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8692:     } else { 
1.81      www      8693: 	return 'error: '.$reply;
                   8694:     }
1.297     matthew  8695:     # Add student role to user
1.83      www      8696:     my $uurl='/'.$cid;
1.81      www      8697:     $uurl=~s/\_/\//g;
                   8698:     if ($usec) {
                   8699: 	$uurl.='/'.$usec;
                   8700:     }
1.1148    raeburn  8701:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8702:                              $selfenroll,$context);
                   8703:     if ($result ne 'ok') {
                   8704:         if ($old_entry{$user} ne '') {
                   8705:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8706:         } else {
                   8707:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8708:         }
                   8709:     }
                   8710:     return $result; 
1.21      www      8711: }
                   8712: 
1.556     albertel 8713: sub format_name {
                   8714:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8715:     my $name;
                   8716:     if ($first ne 'lastname') {
                   8717: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8718:     } else {
                   8719: 	if ($lastname=~/\S/) {
                   8720: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8721: 	    $name=~s/\s+,/,/;
                   8722: 	} else {
                   8723: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8724: 	}
                   8725:     }
                   8726:     $name=~s/^\s+//;
                   8727:     $name=~s/\s+$//;
                   8728:     $name=~s/\s+/ /g;
                   8729:     return $name;
                   8730: }
                   8731: 
1.84      www      8732: # ------------------------------------------------- Write to course preferences
                   8733: 
                   8734: sub writecoursepref {
                   8735:     my ($courseid,%prefs)=@_;
                   8736:     $courseid=~s/^\///;
                   8737:     $courseid=~s/\_/\//g;
                   8738:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8739:     my $chome=homeserver($cnum,$cdomain);
                   8740:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8741: 	return 'error: no such course';
                   8742:     }
                   8743:     my $cstring='';
1.800     albertel 8744:     foreach my $pref (keys(%prefs)) {
                   8745: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8746:     }
1.84      www      8747:     $cstring=~s/\&$//;
                   8748:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8749: }
                   8750: 
                   8751: # ---------------------------------------------------------- Make/modify course
                   8752: 
                   8753: sub createcourse {
1.741     raeburn  8754:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8755:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8756:     $url=&declutter($url);
                   8757:     my $cid='';
1.1028    raeburn  8758:     if ($context eq 'requestcourses') {
                   8759:         my $can_create = 0;
                   8760:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8761:         if ($udom eq $ownerdom) {
                   8762:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8763:                                   $context)) {
                   8764:                 $can_create = 1;
                   8765:             }
                   8766:         } else {
                   8767:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8768:                                            $category);
                   8769:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8770:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8771:                 if (@curr > 0) {
                   8772:                     my @options = qw(approval validate autolimit);
                   8773:                     my $optregex = join('|',@options);
                   8774:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8775:                         $can_create = 1;
                   8776:                     }
                   8777:                 }
                   8778:             }
                   8779:         }
                   8780:         if ($can_create) {
                   8781:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8782:                 unless (&allowed('ccc',$udom)) {
                   8783:                     return 'refused'; 
                   8784:                 }
1.1017    raeburn  8785:             }
                   8786:         } else {
                   8787:             return 'refused';
                   8788:         }
1.1028    raeburn  8789:     } elsif (!&allowed('ccc',$udom)) {
                   8790:         return 'refused';
1.84      www      8791:     }
1.1011    raeburn  8792: # --------------------------------------------------------------- Get Unique ID
                   8793:     my $uname;
                   8794:     if ($cnum =~ /^$match_courseid$/) {
                   8795:         my $chome=&homeserver($cnum,$udom,'true');
                   8796:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8797:             $uname = $cnum;
                   8798:         } else {
1.1038    raeburn  8799:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8800:         }
                   8801:     } else {
1.1038    raeburn  8802:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8803:     }
                   8804:     return $uname if ($uname =~ /^error/);
                   8805: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8806:     if (!defined($course_server)) {
                   8807:         if (defined(&domain($udom,'primary'))) {
                   8808:             $course_server = &domain($udom,'primary');
                   8809:         } else {
                   8810:             $course_server = $env{'user.home'}; 
                   8811:         }
                   8812:     }
                   8813:     my %host_servers =
                   8814:         &Apache::lonnet::get_servers($udom,'library');
                   8815:     unless ($host_servers{$course_server}) {
                   8816:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8817:     }
1.84      www      8818: # ------------------------------------------------------------- Make the course
                   8819:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8820:                       $course_server);
1.84      www      8821:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8822:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8823:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8824: 	return 'error: no such course';
                   8825:     }
1.271     www      8826: # ----------------------------------------------------------------- Course made
1.516     raeburn  8827: # log existence
1.1029    raeburn  8828:     my $now = time;
1.918     raeburn  8829:     my $newcourse = {
                   8830:                     $udom.'_'.$uname => {
1.921     raeburn  8831:                                      description => $description,
                   8832:                                      inst_code   => $inst_code,
                   8833:                                      owner       => $course_owner,
                   8834:                                      type        => $crstype,
1.1029    raeburn  8835:                                      creator     => $env{'user.name'}.':'.
                   8836:                                                     $env{'user.domain'},
                   8837:                                      created     => $now,
                   8838:                                      context     => $context,
1.918     raeburn  8839:                                                 },
                   8840:                     };
1.921     raeburn  8841:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8842: # set toplevel url
1.271     www      8843:     my $topurl=$url;
                   8844:     unless ($nonstandard) {
                   8845: # ------------------------------------------ For standard courses, make top url
                   8846:         my $mapurl=&clutter($url);
1.278     www      8847:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8848:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8849: <map>
                   8850: <resource id="1" type="start"></resource>
                   8851: <resource id="2" src="$mapurl"></resource>
                   8852: <resource id="3" type="finish"></resource>
                   8853: <link index="1" from="1" to="2"></link>
                   8854: <link index="2" from="2" to="3"></link>
                   8855: </map>
                   8856: ENDINITMAP
                   8857:         $topurl=&declutter(
1.638     albertel 8858:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8859:                           );
                   8860:     }
                   8861: # ----------------------------------------------------------- Write preferences
1.84      www      8862:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8863:                      ('description'              => $description,
                   8864:                       'url'                      => $topurl,
                   8865:                       'internal.creator'         => $env{'user.name'}.':'.
                   8866:                                                     $env{'user.domain'},
                   8867:                       'internal.created'         => $now,
                   8868:                       'internal.creationcontext' => $context)
                   8869:                     );
1.84      www      8870:     return '/'.$udom.'/'.$uname;
                   8871: }
                   8872: 
1.1011    raeburn  8873: # ------------------------------------------------------------------- Create ID
                   8874: sub generate_coursenum {
1.1038    raeburn  8875:     my ($udom,$crstype) = @_;
1.1011    raeburn  8876:     my $domdesc = &domain($udom);
                   8877:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8878:     my $first;
                   8879:     if ($crstype eq 'Community') {
                   8880:         $first = '0';
                   8881:     } else {
                   8882:         $first = int(1+rand(9)); 
                   8883:     } 
                   8884:     my $uname=$first.
1.1011    raeburn  8885:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8886:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8887:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8888: # ----------------------------------------------- Make sure that does not exist
                   8889:     my $uhome=&homeserver($uname,$udom,'true');
                   8890:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8891:         if ($crstype eq 'Community') {
                   8892:             $first = '0';
                   8893:         } else {
                   8894:             $first = int(1+rand(9));
                   8895:         }
                   8896:         $uname=$first.
1.1011    raeburn  8897:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8898:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8899:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8900:         $uhome=&homeserver($uname,$udom,'true');
                   8901:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8902:             return 'error: unable to generate unique course-ID';
                   8903:         }
                   8904:     }
                   8905:     return $uname;
                   8906: }
                   8907: 
1.813     albertel 8908: sub is_course {
1.1167    droeschl 8909:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8910:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8911: 
                   8912:     return unless $cdom and $cnum;
                   8913: 
                   8914:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8915:         '.');
                   8916: 
1.1219    raeburn  8917:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 8918:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8919: }
                   8920: 
1.1015    raeburn  8921: sub store_userdata {
                   8922:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8923:     my $result;
1.1016    raeburn  8924:     if ($datakey ne '') {
1.1013    raeburn  8925:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8926:             if ($udom eq '' || $uname eq '') {
                   8927:                 $udom = $env{'user.domain'};
                   8928:                 $uname = $env{'user.name'};
                   8929:             }
                   8930:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8931:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8932:                 $result = 'error: no_host';
                   8933:             } else {
                   8934:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8935:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8936: 
                   8937:                 my $namevalue='';
                   8938:                 foreach my $key (keys(%{$storehash})) {
                   8939:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8940:                 }
                   8941:                 $namevalue=~s/\&$//;
1.1224    raeburn  8942:                 unless ($namespace eq 'courserequests') {
                   8943:                     $datakey = &escape($datakey);
                   8944:                 }
1.1105    raeburn  8945:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8946:                                   $namevalue,$uhome);
1.1013    raeburn  8947:             }
                   8948:         } else {
                   8949:             $result = 'error: data to store was not a hash reference'; 
                   8950:         }
                   8951:     } else {
                   8952:         $result= 'error: invalid requestkey'; 
                   8953:     }
                   8954:     return $result;
                   8955: }
                   8956: 
1.21      www      8957: # ---------------------------------------------------------- Assign Custom Role
                   8958: 
                   8959: sub assigncustomrole {
1.957     raeburn  8960:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8961:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8962:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8963: }
                   8964: 
                   8965: # ----------------------------------------------------------------- Revoke Role
                   8966: 
                   8967: sub revokerole {
1.957     raeburn  8968:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8969:     my $now=time;
1.965     raeburn  8970:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8971: }
                   8972: 
                   8973: # ---------------------------------------------------------- Revoke Custom Role
                   8974: 
                   8975: sub revokecustomrole {
1.957     raeburn  8976:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8977:     my $now=time;
1.357     www      8978:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8979:            $deleteflag,$selfenroll,$context);
1.17      www      8980: }
                   8981: 
1.533     banghart 8982: # ------------------------------------------------------------ Disk usage
1.535     albertel 8983: sub diskusage {
1.955     raeburn  8984:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8985:     $directorypath =~ s/\/$//;
                   8986:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8987:                        .&escape($getpropath).':'.&escape($uname).':'
                   8988:                        .&escape($udom),homeserver($uname,$udom));
                   8989:     if ($listing eq 'unknown_cmd') {
                   8990:         if ($getpropath) {
                   8991:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8992:         }
                   8993:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8994:     }
1.514     albertel 8995:     return $listing;
1.512     banghart 8996: }
                   8997: 
1.566     banghart 8998: sub is_locked {
1.1096    raeburn  8999:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9000:     my @check;
                   9001:     my $is_locked;
1.1093    raeburn  9002:     push (@check,$file_name);
1.613     albertel 9003:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9004: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9005:     my ($tmp)=keys(%locked);
                   9006:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9007:     
1.566     banghart 9008:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9009:         $is_locked = 'false';
                   9010:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9011:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9012:                $is_locked = 'true';
1.1096    raeburn  9013:                if (ref($which) eq 'ARRAY') {
                   9014:                    push(@{$which},$entry);
                   9015:                } else {
                   9016:                    last;
                   9017:                }
1.745     raeburn  9018:            }
                   9019:        }
1.566     banghart 9020:     } else {
                   9021:         $is_locked = 'false';
                   9022:     }
1.1093    raeburn  9023:     return $is_locked;
1.566     banghart 9024: }
                   9025: 
1.759     albertel 9026: sub declutter_portfile {
                   9027:     my ($file) = @_;
1.833     albertel 9028:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9029:     return $file;
                   9030: }
                   9031: 
1.559     banghart 9032: # ------------------------------------------------------------- Mark as Read Only
                   9033: 
                   9034: sub mark_as_readonly {
                   9035:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9036:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9037:     my ($tmp)=keys(%current_permissions);
                   9038:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9039:     foreach my $file (@{$files}) {
1.759     albertel 9040: 	$file = &declutter_portfile($file);
1.561     banghart 9041:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9042:     }
1.613     albertel 9043:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9044:     return;
                   9045: }
                   9046: 
1.572     banghart 9047: # ------------------------------------------------------------Save Selected Files
                   9048: 
                   9049: sub save_selected_files {
                   9050:     my ($user, $path, @files) = @_;
                   9051:     my $filename = $user."savedfiles";
1.573     banghart 9052:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9053:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9054:     foreach my $file (@files) {
1.620     albertel 9055:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9056:     }
                   9057:     foreach my $file (@other_files) {
1.574     banghart 9058:         print (OUT $file."\n");
1.572     banghart 9059:     }
1.574     banghart 9060:     close (OUT);
1.572     banghart 9061:     return 'ok';
                   9062: }
                   9063: 
1.574     banghart 9064: sub clear_selected_files {
                   9065:     my ($user) = @_;
                   9066:     my $filename = $user."savedfiles";
1.1117    foxr     9067:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9068:     print (OUT undef);
                   9069:     close (OUT);
                   9070:     return ("ok");    
                   9071: }
                   9072: 
1.572     banghart 9073: sub files_in_path {
                   9074:     my ($user, $path) = @_;
                   9075:     my $filename = $user."savedfiles";
                   9076:     my %return_files;
1.1117    foxr     9077:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9078:     while (my $line_in = <IN>) {
1.574     banghart 9079:         chomp ($line_in);
                   9080:         my @paths_and_file = split (m!/!, $line_in);
                   9081:         my $file_part = pop (@paths_and_file);
                   9082:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9083:         $path_part.='/';
                   9084:         my $path_and_file = $path_part.$file_part;
                   9085:         if ($path_part eq $path) {
                   9086:             $return_files{$file_part}= 'selected';
                   9087:         }
                   9088:     }
1.574     banghart 9089:     close (IN);
                   9090:     return (\%return_files);
1.572     banghart 9091: }
                   9092: 
                   9093: # called in portfolio select mode, to show files selected NOT in current directory
                   9094: sub files_not_in_path {
                   9095:     my ($user, $path) = @_;
                   9096:     my $filename = $user."savedfiles";
                   9097:     my @return_files;
                   9098:     my $path_part;
1.1117    foxr     9099:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9100:     while (my $line = <IN>) {
1.572     banghart 9101:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9102:         my @paths_and_file = split(m|/|, $line);
                   9103:         my $file_part = pop(@paths_and_file);
                   9104:         chomp($file_part);
                   9105:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9106:         $path_part .= '/';
                   9107:         my $path_and_file = $path_part.$file_part;
                   9108:         if ($path_part ne $path) {
1.800     albertel 9109:             push(@return_files, ($path_and_file));
1.572     banghart 9110:         }
                   9111:     }
1.800     albertel 9112:     close(OUT);
1.574     banghart 9113:     return (@return_files);
1.572     banghart 9114: }
                   9115: 
1.745     raeburn  9116: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9117: 
1.745     raeburn  9118: sub get_portfile_permissions {
                   9119:     my ($domain,$user) = @_;
1.613     albertel 9120:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9121:     my ($tmp)=keys(%current_permissions);
                   9122:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9123:     return \%current_permissions;
                   9124: }
                   9125: 
                   9126: #---------------------------------------------Get portfolio file access controls
                   9127: 
1.749     raeburn  9128: sub get_access_controls {
1.745     raeburn  9129:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9130:     my %access;
                   9131:     my $real_file = $file;
                   9132:     $file =~ s/\.meta$//;
1.745     raeburn  9133:     if (defined($file)) {
1.749     raeburn  9134:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9135:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9136:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9137:             }
                   9138:         }
1.745     raeburn  9139:     } else {
1.749     raeburn  9140:         foreach my $key (keys(%{$current_permissions})) {
                   9141:             if ($key =~ /\0accesscontrol$/) {
                   9142:                 if (defined($group)) {
                   9143:                     if ($key !~ m-^\Q$group\E/-) {
                   9144:                         next;
                   9145:                     }
                   9146:                 }
                   9147:                 my ($fullpath) = split(/\0/,$key);
                   9148:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9149:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9150:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9151:                     }
                   9152:                 }
                   9153:             }
                   9154:         }
                   9155:     }
                   9156:     return %access;
                   9157: }
                   9158: 
                   9159: sub modify_access_controls {
                   9160:     my ($file_name,$changes,$domain,$user)=@_;
                   9161:     my ($outcome,$deloutcome);
                   9162:     my %store_permissions;
                   9163:     my %new_values;
                   9164:     my %new_control;
                   9165:     my %translation;
                   9166:     my @deletions = ();
                   9167:     my $now = time;
                   9168:     if (exists($$changes{'activate'})) {
                   9169:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9170:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9171:             my $numnew = scalar(@newitems);
                   9172:             for (my $i=0; $i<$numnew; $i++) {
                   9173:                 my $newkey = $newitems[$i];
                   9174:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9175:                 if ($newkey =~ /^\d+:/) { 
                   9176:                     $newkey =~ s/^(\d+)/$newid/;
                   9177:                     $translation{$1} = $newid;
                   9178:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9179:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9180:                     $translation{$1} = $newid;
                   9181:                 }
1.749     raeburn  9182:                 $new_values{$file_name."\0".$newkey} = 
                   9183:                                           $$changes{'activate'}{$newitems[$i]};
                   9184:                 $new_control{$newkey} = $now;
                   9185:             }
                   9186:         }
                   9187:     }
                   9188:     my %todelete;
                   9189:     my %changed_items;
                   9190:     foreach my $action ('delete','update') {
                   9191:         if (exists($$changes{$action})) {
                   9192:             if (ref($$changes{$action}) eq 'HASH') {
                   9193:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9194:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9195:                     if ($action eq 'delete') { 
                   9196:                         $todelete{$itemnum} = 1;
                   9197:                     } else {
                   9198:                         $changed_items{$itemnum} = $key;
                   9199:                     }
                   9200:                 }
1.745     raeburn  9201:             }
                   9202:         }
1.749     raeburn  9203:     }
                   9204:     # get lock on access controls for file.
                   9205:     my $lockhash = {
                   9206:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9207:                                                        ':'.$env{'user.domain'},
                   9208:                    }; 
                   9209:     my $tries = 0;
                   9210:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9211:    
                   9212:     while (($gotlock ne 'ok') && $tries <3) {
                   9213:         $tries ++;
                   9214:         sleep 1;
                   9215:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9216:     }
                   9217:     if ($gotlock eq 'ok') {
                   9218:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9219:         my ($tmp)=keys(%curr_permissions);
                   9220:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9221:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9222:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9223:             if (ref($curr_controls) eq 'HASH') {
                   9224:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9225:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9226:                     if (defined($todelete{$itemnum})) {
                   9227:                         push(@deletions,$file_name."\0".$control_item);
                   9228:                     } else {
                   9229:                         if (defined($changed_items{$itemnum})) {
                   9230:                             $new_control{$changed_items{$itemnum}} = $now;
                   9231:                             push(@deletions,$file_name."\0".$control_item);
                   9232:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9233:                         } else {
                   9234:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9235:                         }
                   9236:                     }
1.745     raeburn  9237:                 }
                   9238:             }
                   9239:         }
1.970     raeburn  9240:         my ($group);
                   9241:         if (&is_course($domain,$user)) {
                   9242:             ($group,my $file) = split(/\//,$file_name,2);
                   9243:         }
1.749     raeburn  9244:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9245:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9246:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9247:         #  remove lock
                   9248:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9249:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9250:         my $sqlresult =
1.970     raeburn  9251:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9252:                                     $group);
1.749     raeburn  9253:     } else {
                   9254:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9255:     }
1.749     raeburn  9256:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9257: }
                   9258: 
1.827     raeburn  9259: sub make_public_indefinitely {
                   9260:     my ($requrl) = @_;
                   9261:     my $now = time;
                   9262:     my $action = 'activate';
                   9263:     my $aclnum = 0;
                   9264:     if (&is_portfolio_url($requrl)) {
                   9265:         my (undef,$udom,$unum,$file_name,$group) =
                   9266:             &parse_portfolio_url($requrl);
                   9267:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9268:         my %access_controls = &get_access_controls($current_perms,
                   9269:                                                    $group,$file_name);
                   9270:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9271:             my ($num,$scope,$end,$start) = 
                   9272:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9273:             if ($scope eq 'public') {
                   9274:                 if ($start <= $now && $end == 0) {
                   9275:                     $action = 'none';
                   9276:                 } else {
                   9277:                     $action = 'update';
                   9278:                     $aclnum = $num;
                   9279:                 }
                   9280:                 last;
                   9281:             }
                   9282:         }
                   9283:         if ($action eq 'none') {
                   9284:              return 'ok';
                   9285:         } else {
                   9286:             my %changes;
                   9287:             my $newend = 0;
                   9288:             my $newstart = $now;
                   9289:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9290:             $changes{$action}{$newkey} = {
                   9291:                 type => 'public',
                   9292:                 time => {
                   9293:                     start => $newstart,
                   9294:                     end   => $newend,
                   9295:                 },
                   9296:             };
                   9297:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9298:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9299:             return $outcome;
                   9300:         }
                   9301:     } else {
                   9302:         return 'invalid';
                   9303:     }
                   9304: }
                   9305: 
1.745     raeburn  9306: #------------------------------------------------------Get Marked as Read Only
                   9307: 
                   9308: sub get_marked_as_readonly {
                   9309:     my ($domain,$user,$what,$group) = @_;
                   9310:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9311:     my @readonly_files;
1.629     banghart 9312:     my $cmp1=$what;
                   9313:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9314:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9315:         if (defined($group)) {
                   9316:             if ($file_name !~ m-^\Q$group\E/-) {
                   9317:                 next;
                   9318:             }
                   9319:         }
1.561     banghart 9320:         if (ref($value) eq "ARRAY"){
                   9321:             foreach my $stored_what (@{$value}) {
1.629     banghart 9322:                 my $cmp2=$stored_what;
1.759     albertel 9323:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9324:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9325:                 }
1.629     banghart 9326:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9327:                     push(@readonly_files, $file_name);
1.745     raeburn  9328:                     last;
1.563     banghart 9329:                 } elsif (!defined($what)) {
                   9330:                     push(@readonly_files, $file_name);
1.745     raeburn  9331:                     last;
1.561     banghart 9332:                 }
                   9333:             }
1.745     raeburn  9334:         }
1.561     banghart 9335:     }
                   9336:     return @readonly_files;
                   9337: }
1.577     banghart 9338: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9339: 
1.577     banghart 9340: sub get_marked_as_readonly_hash {
1.745     raeburn  9341:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9342:     my %readonly_files;
1.745     raeburn  9343:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9344:         if (defined($group)) {
                   9345:             if ($file_name !~ m-^\Q$group\E/-) {
                   9346:                 next;
                   9347:             }
                   9348:         }
1.577     banghart 9349:         if (ref($value) eq "ARRAY"){
                   9350:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9351:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9352:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9353:                         if ($lock_descriptor eq 'graded') {
                   9354:                             $readonly_files{$file_name} = 'graded';
                   9355:                         } elsif ($lock_descriptor eq 'handback') {
                   9356:                             $readonly_files{$file_name} = 'handback';
                   9357:                         } else {
                   9358:                             if (!exists($readonly_files{$file_name})) {
                   9359:                                 $readonly_files{$file_name} = 'locked';
                   9360:                             }
                   9361:                         }
1.745     raeburn  9362:                     }
1.750     banghart 9363:                 } 
1.577     banghart 9364:             }
                   9365:         } 
                   9366:     }
                   9367:     return %readonly_files;
                   9368: }
1.559     banghart 9369: # ------------------------------------------------------------ Unmark as Read Only
                   9370: 
                   9371: sub unmark_as_readonly {
1.629     banghart 9372:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9373:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9374:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9375:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9376:     my $symb_crs = $what;
                   9377:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9378:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9379:     my ($tmp)=keys(%current_permissions);
                   9380:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9381:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9382:     foreach my $file (@readonly_files) {
1.759     albertel 9383: 	my $clean_file = &declutter_portfile($file);
                   9384: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9385: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9386:         my @new_locks;
                   9387:         my @del_keys;
                   9388:         if (ref($current_locks) eq "ARRAY"){
                   9389:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9390:                 my $compare=$locker;
1.749     raeburn  9391:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9392:                     $compare=join('',@{$locker});
1.746     raeburn  9393:                     if ($compare ne $symb_crs) {
                   9394:                         push(@new_locks, $locker);
                   9395:                     }
1.563     banghart 9396:                 }
                   9397:             }
1.650     albertel 9398:             if (scalar(@new_locks) > 0) {
1.563     banghart 9399:                 $current_permissions{$file} = \@new_locks;
                   9400:             } else {
                   9401:                 push(@del_keys, $file);
1.613     albertel 9402:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9403:                 delete($current_permissions{$file});
1.563     banghart 9404:             }
                   9405:         }
1.561     banghart 9406:     }
1.613     albertel 9407:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9408:     return;
                   9409: }
1.512     banghart 9410: 
1.17      www      9411: # ------------------------------------------------------------ Directory lister
                   9412: 
                   9413: sub dirlist {
1.955     raeburn  9414:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9415:     $uri=~s/^\///;
                   9416:     $uri=~s/\/$//;
1.253     stredwic 9417:     my ($udom, $uname);
1.955     raeburn  9418:     if ($getuserdir) {
1.253     stredwic 9419:         $udom = $userdomain;
                   9420:         $uname = $username;
1.955     raeburn  9421:     } else {
                   9422:         (undef,$udom,$uname)=split(/\//,$uri);
                   9423:         if(defined($userdomain)) {
                   9424:             $udom = $userdomain;
                   9425:         }
                   9426:         if(defined($username)) {
                   9427:             $uname = $username;
                   9428:         }
1.253     stredwic 9429:     }
1.955     raeburn  9430:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9431: 
1.955     raeburn  9432:     $dirRoot = $perlvar{'lonDocRoot'};
                   9433:     if (defined($getpropath)) {
                   9434:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9435:         $dirRoot =~ s/\/$//;
1.955     raeburn  9436:     } elsif (defined($getuserdir)) {
                   9437:         my $subdir=$uname.'__';
                   9438:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9439:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9440:                    ."/$udom/$subdir/$uname";
                   9441:     } elsif (defined($alternateRoot)) {
                   9442:         $dirRoot = $alternateRoot;
1.751     banghart 9443:     }
1.253     stredwic 9444: 
                   9445:     if($udom) {
                   9446:         if($uname) {
1.1135    raeburn  9447:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9448:             if ($uhome eq 'no_host') {
                   9449:                 return ([],'no_host');
                   9450:             }
1.955     raeburn  9451:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9452:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9453:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9454:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9455:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9456:             } else {
                   9457:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9458:             }
1.605     matthew  9459:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9460:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9461:                 @listing_results = split(/:/,$listing);
                   9462:             } else {
                   9463:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9464:             }
1.1135    raeburn  9465:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9466:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9467:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9468:                 return ([],$listing);
                   9469:             } else {
                   9470:                 return (\@listing_results);
1.1135    raeburn  9471:             }
1.955     raeburn  9472:         } elsif(!$alternateRoot) {
1.1136    raeburn  9473:             my (%allusers,%listerror);
1.841     albertel 9474: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9475:  	    foreach my $tryserver (keys(%servers)) {
                   9476:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9477:                                   &escape($udom),$tryserver);
                   9478:                 if ($listing eq 'unknown_cmd') {
                   9479: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9480: 				      $udom, $tryserver);
                   9481:                 } else {
                   9482:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9483:                 }
1.841     albertel 9484: 		if ($listing eq 'unknown_cmd') {
                   9485: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9486: 				      $udom, $tryserver);
                   9487: 		    @listing_results = split(/:/,$listing);
                   9488: 		} else {
                   9489: 		    @listing_results =
                   9490: 			map { &unescape($_); } split(/:/,$listing);
                   9491: 		}
1.1136    raeburn  9492:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9493:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9494:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9495:                     $listerror{$tryserver} = $listing;
                   9496:                 } else {
1.841     albertel 9497: 		    foreach my $line (@listing_results) {
                   9498: 			my ($entry) = split(/&/,$line,2);
                   9499: 			$allusers{$entry} = 1;
                   9500: 		    }
                   9501: 		}
1.253     stredwic 9502:             }
1.1136    raeburn  9503:             my @alluserslist=();
1.800     albertel 9504:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9505:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9506:             }
1.1136    raeburn  9507:             return (\@alluserslist);
1.253     stredwic 9508:         } else {
1.1136    raeburn  9509:             return ([],'missing username');
1.253     stredwic 9510:         }
1.955     raeburn  9511:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9512:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9513:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9514:         return (\@all_domains);
1.955     raeburn  9515:     } else {
1.1136    raeburn  9516:         return ([],'missing domain');
1.275     stredwic 9517:     }
                   9518: }
                   9519: 
                   9520: # --------------------------------------------- GetFileTimestamp
                   9521: # This function utilizes dirlist and returns the date stamp for
                   9522: # when it was last modified.  It will also return an error of -1
                   9523: # if an error occurs
                   9524: 
                   9525: sub GetFileTimestamp {
1.955     raeburn  9526:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9527:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9528:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9529:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9530:                                     undef,$getuserdir);
                   9531:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9532:         return -1;
                   9533:     }
                   9534:     if (ref($fileref) eq 'ARRAY') {
                   9535:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9536:         # @stats contains first the filename, then the stat output
                   9537:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9538:     } else {
                   9539:         return -1;
1.253     stredwic 9540:     }
1.26      www      9541: }
                   9542: 
1.712     albertel 9543: sub stat_file {
                   9544:     my ($uri) = @_;
1.787     albertel 9545:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9546: 
1.955     raeburn  9547:     my ($udom,$uname,$file);
1.712     albertel 9548:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9549: 	($udom,$uname,$file) =
1.811     albertel 9550: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9551: 	$file = 'userfiles/'.$file;
                   9552:     }
                   9553:     if ($uri =~ m-^/res/-) {
                   9554: 	($udom,$uname) = 
1.807     albertel 9555: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9556: 	$file = $uri;
                   9557:     }
                   9558: 
                   9559:     if (!$udom || !$uname || !$file) {
                   9560: 	# unable to handle the uri
                   9561: 	return ();
                   9562:     }
1.956     raeburn  9563:     my $getpropath;
                   9564:     if ($file =~ /^userfiles\//) {
                   9565:         $getpropath = 1;
                   9566:     }
1.1136    raeburn  9567:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9568:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9569:         return ();
                   9570:     } else {
                   9571:         if (ref($listref) eq 'ARRAY') {
                   9572:             my @stats = split('&',$listref->[0]);
                   9573: 	    shift(@stats); #filename is first
                   9574: 	    return @stats;
                   9575:         }
1.712     albertel 9576:     }
                   9577:     return ();
                   9578: }
                   9579: 
1.26      www      9580: # -------------------------------------------------------- Value of a Condition
                   9581: 
1.713     albertel 9582: # gets the value of a specific preevaluated condition
                   9583: #    stored in the string  $env{user.state.<cid>}
                   9584: # or looks up a condition reference in the bighash and if if hasn't
                   9585: # already been evaluated recurses into docondval to get the value of
                   9586: # the condition, then memoizing it to 
                   9587: #   $env{user.state.<cid>.<condition>}
1.40      www      9588: sub directcondval {
                   9589:     my $number=shift;
1.620     albertel 9590:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9591: 	&Apache::lonuserstate::evalstate();
                   9592:     }
1.713     albertel 9593:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9594: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9595:     } elsif ($number =~ /^_/) {
                   9596: 	my $sub_condition;
                   9597: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9598: 		&GDBM_READER(),0640)) {
                   9599: 	    $sub_condition=$bighash{'conditions'.$number};
                   9600: 	    untie(%bighash);
                   9601: 	}
                   9602: 	my $value = &docondval($sub_condition);
1.949     raeburn  9603: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9604: 	return $value;
                   9605:     }
1.620     albertel 9606:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9607:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9608:     } else {
                   9609:        return 2;
                   9610:     }
                   9611: }
                   9612: 
1.713     albertel 9613: # get the collection of conditions for this resource
1.26      www      9614: sub condval {
                   9615:     my $condidx=shift;
1.54      www      9616:     my $allpathcond='';
1.713     albertel 9617:     foreach my $cond (split(/\|/,$condidx)) {
                   9618: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9619: 	    $allpathcond.=
                   9620: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9621: 	}
1.191     harris41 9622:     }
1.54      www      9623:     $allpathcond=~s/\|$//;
1.713     albertel 9624:     return &docondval($allpathcond);
                   9625: }
                   9626: 
                   9627: #evaluates an expression of conditions
                   9628: sub docondval {
                   9629:     my ($allpathcond) = @_;
                   9630:     my $result=0;
                   9631:     if ($env{'request.course.id'}
                   9632: 	&& defined($allpathcond)) {
                   9633: 	my $operand='|';
                   9634: 	my @stack;
                   9635: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9636: 	    if ($chunk eq '(') {
                   9637: 		push @stack,($operand,$result);
                   9638: 	    } elsif ($chunk eq ')') {
                   9639: 		my $before=pop @stack;
                   9640: 		if (pop @stack eq '&') {
                   9641: 		    $result=$result>$before?$before:$result;
                   9642: 		} else {
                   9643: 		    $result=$result>$before?$result:$before;
                   9644: 		}
                   9645: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9646: 		$operand=$chunk;
                   9647: 	    } else {
                   9648: 		my $new=directcondval($chunk);
                   9649: 		if ($operand eq '&') {
                   9650: 		    $result=$result>$new?$new:$result;
                   9651: 		} else {
                   9652: 		    $result=$result>$new?$result:$new;
                   9653: 		}
                   9654: 	    }
                   9655: 	}
1.26      www      9656:     }
                   9657:     return $result;
1.421     albertel 9658: }
                   9659: 
                   9660: # ---------------------------------------------------- Devalidate courseresdata
                   9661: 
                   9662: sub devalidatecourseresdata {
                   9663:     my ($coursenum,$coursedomain)=@_;
                   9664:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9665:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9666: }
                   9667: 
1.763     www      9668: 
1.200     www      9669: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9670: #
                   9671: #  Parameters:
                   9672: #      $coursenum    - Number of the course.
                   9673: #      $coursedomain - Domain at which the course was created.
                   9674: #  Returns:
                   9675: #     A hash of the course parameters along (I think) with timestamps
                   9676: #     and version info.
1.877     foxr     9677: 
1.624     albertel 9678: sub get_courseresdata {
                   9679:     my ($coursenum,$coursedomain)=@_;
1.200     www      9680:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9681:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9682:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9683:     my %dumpreply;
1.417     albertel 9684:     unless (defined($cached)) {
1.624     albertel 9685: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9686: 	$result=\%dumpreply;
1.251     albertel 9687: 	my ($tmp) = keys(%dumpreply);
                   9688: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9689: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9690: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9691: 	    return $tmp;
1.416     albertel 9692: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9693: 	    $result=undef;
1.599     albertel 9694: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9695: 	}
                   9696:     }
1.624     albertel 9697:     return $result;
                   9698: }
                   9699: 
1.633     albertel 9700: sub devalidateuserresdata {
                   9701:     my ($uname,$udom)=@_;
                   9702:     my $hashid="$udom:$uname";
                   9703:     &devalidate_cache_new('userres',$hashid);
                   9704: }
                   9705: 
1.624     albertel 9706: sub get_userresdata {
                   9707:     my ($uname,$udom)=@_;
                   9708:     #most student don\'t have any data set, check if there is some data
                   9709:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9710: 
                   9711:     my $hashid="$udom:$uname";
                   9712:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9713:     if (!defined($cached)) {
                   9714: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9715: 	$result=\%resourcedata;
                   9716: 	&do_cache_new('userres',$hashid,$result,600);
                   9717:     }
                   9718:     my ($tmp)=keys(%$result);
                   9719:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9720: 	return $result;
                   9721:     }
                   9722:     #error 2 occurs when the .db doesn't exist
                   9723:     if ($tmp!~/error: 2 /) {
1.672     albertel 9724: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9725: 		 " Trying to get resource data for ".
                   9726: 		 $uname." at ".$udom.": ".
                   9727: 		 $tmp."</font>");
                   9728:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9729: 	#&EXT_cache_set($udom,$uname);
                   9730: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9731: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9732:     }
                   9733:     return $tmp;
                   9734: }
1.879     foxr     9735: #----------------------------------------------- resdata - return resource data
                   9736: #  Purpose:
                   9737: #    Return resource data for either users or for a course.
                   9738: #  Parameters:
                   9739: #     $name      - Course/user name.
                   9740: #     $domain    - Name of the domain the user/course is registered on.
                   9741: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9742: #     @which     - Array of names of resources desired.
                   9743: #  Returns:
                   9744: #     The value of the first reasource in @which that is found in the
                   9745: #     resource hash.
                   9746: #  Exceptional Conditions:
                   9747: #     If the $type passed in is not valid (not the string 'course' or 
                   9748: #     'user', an undefined  reference is returned.
                   9749: #     If none of the resources are found, an undef is returned
1.624     albertel 9750: sub resdata {
                   9751:     my ($name,$domain,$type,@which)=@_;
                   9752:     my $result;
                   9753:     if ($type eq 'course') {
                   9754: 	$result=&get_courseresdata($name,$domain);
                   9755:     } elsif ($type eq 'user') {
                   9756: 	$result=&get_userresdata($name,$domain);
                   9757:     }
                   9758:     if (!ref($result)) { return $result; }    
1.251     albertel 9759:     foreach my $item (@which) {
1.927     albertel 9760: 	if (defined($result->{$item->[0]})) {
                   9761: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9762: 	}
1.250     albertel 9763:     }
1.291     albertel 9764:     return undef;
1.200     www      9765: }
                   9766: 
1.1236    raeburn  9767: sub get_numsuppfiles {
                   9768:     my ($cnum,$cdom,$ignorecache)=@_;
                   9769:     my $hashid=$cnum.':'.$cdom;
                   9770:     my ($suppcount,$cached);
                   9771:     unless ($ignorecache) {
                   9772:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   9773:     }
                   9774:     unless (defined($cached)) {
                   9775:         my $chome=&homeserver($cnum,$cdom);
                   9776:         unless ($chome eq 'no_host') {
                   9777:             ($suppcount,my $errors) = (0,0);
                   9778:             my $suppmap = 'supplemental.sequence';
                   9779:             ($suppcount,$errors) = 
                   9780:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   9781:         }
                   9782:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   9783:     }
                   9784:     return $suppcount;
                   9785: }
                   9786: 
1.379     matthew  9787: #
                   9788: # EXT resource caching routines
                   9789: #
                   9790: 
                   9791: sub clear_EXT_cache_status {
1.383     albertel 9792:     &delenv('cache.EXT.');
1.379     matthew  9793: }
                   9794: 
                   9795: sub EXT_cache_status {
                   9796:     my ($target_domain,$target_user) = @_;
1.383     albertel 9797:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9798:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9799:         # We know already the user has no data
                   9800:         return 1;
                   9801:     } else {
                   9802:         return 0;
                   9803:     }
                   9804: }
                   9805: 
                   9806: sub EXT_cache_set {
                   9807:     my ($target_domain,$target_user) = @_;
1.383     albertel 9808:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9809:     #&appenv({$cachename => time});
1.379     matthew  9810: }
                   9811: 
1.28      www      9812: # --------------------------------------------------------- Value of a Variable
1.58      www      9813: sub EXT {
1.715     albertel 9814: 
1.1228    raeburn  9815:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      9816:     unless ($varname) { return ''; }
1.218     albertel 9817:     #get real user name/domain, courseid and symb
                   9818:     my $courseid;
1.359     albertel 9819:     my $publicuser;
1.427     www      9820:     if ($symbparm) {
                   9821: 	$symbparm=&get_symb_from_alias($symbparm);
                   9822:     }
1.218     albertel 9823:     if (!($uname && $udom)) {
1.790     albertel 9824:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9825:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9826:     } else {
1.620     albertel 9827: 	$courseid=$env{'request.course.id'};
1.218     albertel 9828:     }
1.48      www      9829:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9830:     my $rest;
1.320     albertel 9831:     if (defined($therest[0])) {
1.48      www      9832:        $rest=join('.',@therest);
                   9833:     } else {
                   9834:        $rest='';
                   9835:     }
1.320     albertel 9836: 
1.57      www      9837:     my $qualifierrest=$qualifier;
                   9838:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9839:     my $spacequalifierrest=$space;
                   9840:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9841:     if ($realm eq 'user') {
1.48      www      9842: # --------------------------------------------------------------- user.resource
                   9843: 	if ($space eq 'resource') {
1.651     albertel 9844: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9845: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9846: 		 &&
1.744     albertel 9847: 		 ($symbparm eq &symbread()) ) {	
                   9848: 		# if we are in the middle of processing the resource the
                   9849: 		# get the value we are planning on committing
                   9850:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9851:                     return $Apache::lonhomework::results{$qualifierrest};
                   9852:                 } else {
                   9853:                     return $Apache::lonhomework::history{$qualifierrest};
                   9854:                 }
1.335     albertel 9855: 	    } else {
1.359     albertel 9856: 		my %restored;
1.620     albertel 9857: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9858: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9859: 		} else {
                   9860: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9861: 		}
1.335     albertel 9862: 		return $restored{$qualifierrest};
                   9863: 	    }
1.48      www      9864: # ----------------------------------------------------------------- user.access
                   9865:         } elsif ($space eq 'access') {
1.218     albertel 9866: 	    # FIXME - not supporting calls for a specific user
1.48      www      9867:             return &allowed($qualifier,$rest);
                   9868: # ------------------------------------------ user.preferences, user.environment
                   9869:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9870: 	    if (($uname eq $env{'user.name'}) &&
                   9871: 		($udom eq $env{'user.domain'})) {
                   9872: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9873: 	    } else {
1.359     albertel 9874: 		my %returnhash;
                   9875: 		if (!$publicuser) {
                   9876: 		    %returnhash=&userenvironment($udom,$uname,
                   9877: 						 $qualifierrest);
                   9878: 		}
1.218     albertel 9879: 		return $returnhash{$qualifierrest};
                   9880: 	    }
1.48      www      9881: # ----------------------------------------------------------------- user.course
                   9882:         } elsif ($space eq 'course') {
1.218     albertel 9883: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9884:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9885: # ------------------------------------------------------------------- user.role
                   9886:         } elsif ($space eq 'role') {
1.218     albertel 9887: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9888:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9889:             if ($qualifier eq 'value') {
                   9890: 		return $role;
                   9891:             } elsif ($qualifier eq 'extent') {
                   9892:                 return $where;
                   9893:             }
                   9894: # ----------------------------------------------------------------- user.domain
                   9895:         } elsif ($space eq 'domain') {
1.218     albertel 9896:             return $udom;
1.48      www      9897: # ------------------------------------------------------------------- user.name
                   9898:         } elsif ($space eq 'name') {
1.218     albertel 9899:             return $uname;
1.48      www      9900: # ---------------------------------------------------- Any other user namespace
1.29      www      9901:         } else {
1.359     albertel 9902: 	    my %reply;
                   9903: 	    if (!$publicuser) {
                   9904: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9905: 	    }
                   9906: 	    return $reply{$qualifierrest};
1.48      www      9907:         }
1.236     www      9908:     } elsif ($realm eq 'query') {
                   9909: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9910:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9911: 						[$spacequalifierrest]);
1.620     albertel 9912: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9913:    } elsif ($realm eq 'request') {
1.48      www      9914: # ------------------------------------------------------------- request.browser
                   9915:         if ($space eq 'browser') {
1.1145    bisitz   9916:             return $env{'browser.'.$qualifier};
1.57      www      9917: # ------------------------------------------------------------ request.filename
                   9918:         } else {
1.620     albertel 9919:             return $env{'request.'.$spacequalifierrest};
1.29      www      9920:         }
1.28      www      9921:     } elsif ($realm eq 'course') {
1.48      www      9922: # ---------------------------------------------------------- course.description
1.620     albertel 9923:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9924:     } elsif ($realm eq 'resource') {
1.165     www      9925: 
1.620     albertel 9926: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9927: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9928: 	}
1.693     albertel 9929: 
1.1232    raeburn  9930:         if ($qualifier eq '') {
                   9931: 	    if ($space eq 'title') {
                   9932: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9933: 	        return &gettitle($symbparm);
                   9934: 	    }
1.693     albertel 9935: 	
1.1232    raeburn  9936: 	    if ($space eq 'map') {
                   9937: 	        my ($map) = &decode_symb($symbparm);
                   9938: 	        return &symbread($map);
                   9939: 	    }
                   9940:             if ($space eq 'maptitle') {
                   9941:                 my ($map) = &decode_symb($symbparm);
                   9942:                 return &gettitle($map);
                   9943:             }
                   9944: 	    if ($space eq 'filename') {
                   9945: 	        if ($symbparm) {
                   9946: 		    return &clutter((&decode_symb($symbparm))[2]);
                   9947: 	        }
                   9948: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 9949: 	    }
1.1232    raeburn  9950: 
1.1233    raeburn  9951:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   9952:                 if ($space eq 'visibleparts') {
                   9953:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9954:                     my $item;
                   9955:                     if (ref($navmap)) {
                   9956:                         my $res = $navmap->getBySymb($symbparm);
                   9957:                         my $parts = $res->parts();
                   9958:                         if (ref($parts) eq 'ARRAY') {
                   9959:                             $item = join(',',@{$parts});
                   9960:                         }
                   9961:                         undef($navmap);
1.1232    raeburn  9962:                     }
1.1233    raeburn  9963:                     return $item;
1.1232    raeburn  9964:                 }
                   9965:             }
                   9966:         }
1.693     albertel 9967: 
                   9968: 	my ($section, $group, @groups);
1.593     albertel 9969: 	my ($courselevelm,$courselevel);
1.1228    raeburn  9970:         if (($courseid eq '') && ($cid)) {
                   9971:             $courseid = $cid;
                   9972:         }
                   9973: 	if (($symbparm && $courseid) && 
                   9974: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      9975: 
1.218     albertel 9976: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9977: 
1.60      www      9978: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9979: 	    my $symbp=$symbparm;
1.735     albertel 9980: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9981: 
                   9982: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9983: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9984: 
1.620     albertel 9985: 	    if (($env{'user.name'} eq $uname) &&
                   9986: 		($env{'user.domain'} eq $udom)) {
                   9987: 		$section=$env{'request.course.sec'};
1.733     raeburn  9988:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9989:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9990: 	    } else {
1.539     albertel 9991: 		if (! defined($usection)) {
1.551     albertel 9992: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9993: 		} else {
                   9994: 		    $section = $usection;
                   9995: 		}
1.733     raeburn  9996:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9997: 	    }
                   9998: 
                   9999: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10000: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10001: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10002: 
1.593     albertel 10003: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10004: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10005: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10006: 
1.60      www      10007: # ----------------------------------------------------------- first, check user
1.624     albertel 10008: 
                   10009: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10010: 				       ([$courselevelr,'resource'],
                   10011: 					[$courselevelm,'map'     ],
                   10012: 					[$courselevel, 'course'  ]));
1.931     albertel 10013: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10014: 
1.594     albertel 10015: # ------------------------------------------------ second, check some of course
1.684     raeburn  10016:             my $coursereply;
1.691     raeburn  10017:             if (@groups > 0) {
                   10018:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10019:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10020:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10021:             }
1.96      www      10022: 
1.684     raeburn  10023: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10024: 				  $env{'course.'.$courseid.'.domain'},
                   10025: 				  'course',
                   10026: 				  ([$seclevelr,   'resource'],
                   10027: 				   [$seclevelm,   'map'     ],
                   10028: 				   [$seclevel,    'course'  ],
                   10029: 				   [$courselevelr,'resource']));
                   10030: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10031: 
1.60      www      10032: # ------------------------------------------------------ third, check map parms
1.218     albertel 10033: 	    my %parmhash=();
                   10034: 	    my $thisparm='';
                   10035: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10036: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10037: 		    &GDBM_READER(),0640)) {
1.218     albertel 10038: 		$thisparm=$parmhash{$symbparm};
                   10039: 		untie(%parmhash);
                   10040: 	    }
1.927     albertel 10041: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10042: 	}
1.594     albertel 10043: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10044: 
1.218     albertel 10045: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10046: 	my $filename;
                   10047: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10048: 	if ($symbparm) {
1.409     www      10049: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10050: 	} else {
1.620     albertel 10051: 	    $filename=$env{'request.filename'};
1.282     albertel 10052: 	}
                   10053: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10054: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10055: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10056: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10057: 
1.927     albertel 10058: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10059: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10060: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10061: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10062: 				     $env{'course.'.$courseid.'.domain'},
                   10063: 				     'course',
1.927     albertel 10064: 				     ([$courselevelm,'map'   ],
                   10065: 				      [$courselevel, 'course']));
                   10066: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10067: 	}
1.145     www      10068: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10069: 	unless ($space eq '0') {
1.336     albertel 10070: 	    my @parts=split(/_/,$space);
                   10071: 	    my $id=pop(@parts);
                   10072: 	    my $part=join('_',@parts);
                   10073: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10074: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10075: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10076: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10077: 	}
1.395     albertel 10078: 	if ($recurse) { return undef; }
                   10079: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10080: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10081: # ---------------------------------------------------- Any other user namespace
                   10082:     } elsif ($realm eq 'environment') {
                   10083: # ----------------------------------------------------------------- environment
1.620     albertel 10084: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10085: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10086: 	} else {
1.770     albertel 10087: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10088: 		return '';
                   10089: 	    }
1.219     albertel 10090: 	    my %returnhash=&userenvironment($udom,$uname,
                   10091: 					    $spacequalifierrest);
                   10092: 	    return $returnhash{$spacequalifierrest};
                   10093: 	}
1.28      www      10094:     } elsif ($realm eq 'system') {
1.48      www      10095: # ----------------------------------------------------------------- system.time
                   10096: 	if ($space eq 'time') {
                   10097: 	    return time;
                   10098:         }
1.696     albertel 10099:     } elsif ($realm eq 'server') {
                   10100: # ----------------------------------------------------------------- system.time
                   10101: 	if ($space eq 'name') {
                   10102: 	    return $ENV{'SERVER_NAME'};
                   10103:         }
1.28      www      10104:     }
1.48      www      10105:     return '';
1.61      www      10106: }
                   10107: 
1.927     albertel 10108: sub get_reply {
                   10109:     my ($reply_value) = @_;
1.940     raeburn  10110:     if (ref($reply_value) eq 'ARRAY') {
                   10111:         if (wantarray) {
                   10112: 	    return @$reply_value;
                   10113:         }
                   10114:         return $reply_value->[0];
                   10115:     } else {
                   10116:         return $reply_value;
1.927     albertel 10117:     }
                   10118: }
                   10119: 
1.691     raeburn  10120: sub check_group_parms {
                   10121:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10122:     my @groupitems = ();
                   10123:     my $resultitem;
1.927     albertel 10124:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10125:     foreach my $group (@{$groups}) {
                   10126:         foreach my $level (@levels) {
1.927     albertel 10127:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10128:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10129:         }
                   10130:     }
                   10131:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10132:                             $env{'course.'.$courseid.'.domain'},
                   10133:                                      'course',@groupitems);
                   10134:     return $coursereply;
                   10135: }
                   10136: 
                   10137: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10138:     my ($courseid,@groups) = @_;
                   10139:     @groups = sort(@groups);
1.691     raeburn  10140:     return @groups;
                   10141: }
                   10142: 
1.395     albertel 10143: sub packages_tab_default {
                   10144:     my ($uri,$varname)=@_;
                   10145:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10146: 
                   10147:     my (@extension,@specifics,$do_default);
                   10148:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10149: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10150: 	if ($pack_type eq 'default') {
                   10151: 	    $do_default=1;
                   10152: 	} elsif ($pack_type eq 'extension') {
                   10153: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10154: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10155: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10156: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10157: 	}
                   10158:     }
                   10159:     # first look for a package that matches the requested part id
                   10160:     foreach my $package (@specifics) {
                   10161: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10162: 	next if ($pack_part ne $part);
                   10163: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10164: 	    return $packagetab{"$pack_type&$name&default"};
                   10165: 	}
                   10166:     }
                   10167:     # look for any possible matching non extension_ package
                   10168:     foreach my $package (@specifics) {
                   10169: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10170: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10171: 	    return $packagetab{"$pack_type&$name&default"};
                   10172: 	}
1.585     albertel 10173: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10174: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10175: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10176: 	}
                   10177:     }
1.738     albertel 10178:     # look for any posible extension_ match
                   10179:     foreach my $package (@extension) {
                   10180: 	my ($package,$pack_type)=@{$package};
                   10181: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10182: 	    return $packagetab{"$pack_type&$name&default"};
                   10183: 	}
                   10184: 	if (defined($packagetab{$package."&$name&default"})) {
                   10185: 	    return $packagetab{$package."&$name&default"};
                   10186: 	}
                   10187:     }
                   10188:     # look for a global default setting
                   10189:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10190: 	return $packagetab{"default&$name&default"};
                   10191:     }
1.395     albertel 10192:     return undef;
                   10193: }
                   10194: 
1.334     albertel 10195: sub add_prefix_and_part {
                   10196:     my ($prefix,$part)=@_;
                   10197:     my $keyroot;
                   10198:     if (defined($prefix) && $prefix !~ /^__/) {
                   10199: 	# prefix that has a part already
                   10200: 	$keyroot=$prefix;
                   10201:     } elsif (defined($prefix)) {
                   10202: 	# prefix that is missing a part
                   10203: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10204:     } else {
                   10205: 	# no prefix at all
                   10206: 	if (defined($part)) { $keyroot='_'.$part; }
                   10207:     }
                   10208:     return $keyroot;
                   10209: }
                   10210: 
1.71      www      10211: # ---------------------------------------------------------------- Get metadata
                   10212: 
1.599     albertel 10213: my %metaentry;
1.1070    www      10214: my %importedpartids;
1.71      www      10215: sub metadata {
1.176     www      10216:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10217:     $uri=&declutter($uri);
1.288     albertel 10218:     # if it is a non metadata possible uri return quickly
1.529     albertel 10219:     if (($uri eq '') || 
                   10220: 	(($uri =~ m|^/*adm/|) && 
1.1217    raeburn  10221: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10222:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10223: 	return undef;
                   10224:     }
1.1261    raeburn  10225:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10226: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10227: 	return undef;
1.288     albertel 10228:     }
1.73      www      10229:     my $filename=$uri;
                   10230:     $uri=~s/\.meta$//;
1.172     www      10231: #
                   10232: # Is the metadata already cached?
1.177     www      10233: # Look at timestamp of caching
1.172     www      10234: # Everything is cached by the main uri, libraries are never directly cached
                   10235: #
1.428     albertel 10236:     if (!defined($liburi)) {
1.599     albertel 10237: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10238: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10239:     }
                   10240:     {
1.1069    www      10241: # Imported parts would go here
1.1070    www      10242:         my %importedids=();
                   10243:         my @origfileimportpartids=();
1.1069    www      10244:         my $importedparts=0;
1.172     www      10245: #
                   10246: # Is this a recursive call for a library?
                   10247: #
1.599     albertel 10248: #	if (! exists($metacache{$uri})) {
                   10249: #	    $metacache{$uri}={};
                   10250: #	}
1.924     albertel 10251: 	my $cachetime = 60*60;
1.171     www      10252:         if ($liburi) {
                   10253: 	    $liburi=&declutter($liburi);
                   10254:             $filename=$liburi;
1.401     bowersj2 10255:         } else {
1.599     albertel 10256: 	    &devalidate_cache_new('meta',$uri);
                   10257: 	    undef(%metaentry);
1.401     bowersj2 10258: 	}
1.140     www      10259:         my %metathesekeys=();
1.73      www      10260:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10261: 	my $metastring;
1.1140    www      10262: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10263: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10264: 	    $metastring = 
1.929     albertel 10265: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10266: 					  ('grade_target' => 'meta'));
                   10267: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10268: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10269:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10270: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10271: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10272: 	    $metastring=&getfile($file);
1.489     albertel 10273: 	}
1.208     albertel 10274:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10275:         my $token;
1.140     www      10276:         undef %metathesekeys;
1.71      www      10277:         while ($token=$parser->get_token) {
1.339     albertel 10278: 	    if ($token->[0] eq 'S') {
                   10279: 		if (defined($token->[2]->{'package'})) {
1.172     www      10280: #
                   10281: # This is a package - get package info
                   10282: #
1.339     albertel 10283: 		    my $package=$token->[2]->{'package'};
                   10284: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10285: 		    if (defined($token->[2]->{'id'})) { 
                   10286: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10287: 		    }
1.599     albertel 10288: 		    if ($metaentry{':packages'}) {
                   10289: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10290: 		    } else {
1.599     albertel 10291: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10292: 		    }
1.736     albertel 10293: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10294: 			my $part=$keyroot;
                   10295: 			$part=~s/^\_//;
1.736     albertel 10296: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10297: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10298: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10299: 			    # ignore package.tab specified default values
                   10300:                             # here &package_tab_default() will fetch those
                   10301: 			    if ($subp eq 'default') { next; }
1.736     albertel 10302: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10303: 			    my $unikey;
                   10304: 			    if ($pack =~ /_0$/) {
                   10305: 				$unikey='parameter_0_'.$name;
                   10306: 				$part=0;
                   10307: 			    } else {
                   10308: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10309: 			    }
1.339     albertel 10310: 			    if ($subp eq 'display') {
                   10311: 				$value.=' [Part: '.$part.']';
                   10312: 			    }
1.599     albertel 10313: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10314: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10315: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10316: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10317: 			    }
1.599     albertel 10318: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10319: 				$metaentry{':'.$unikey}=
                   10320: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10321: 			    }
1.339     albertel 10322: 			}
                   10323: 		    }
                   10324: 		} else {
1.172     www      10325: #
                   10326: # This is not a package - some other kind of start tag
1.339     albertel 10327: #
                   10328: 		    my $entry=$token->[1];
1.1068    www      10329: 		    my $unikey='';
1.175     www      10330: 
1.339     albertel 10331: 		    if ($entry eq 'import') {
1.175     www      10332: #
                   10333: # Importing a library here
1.339     albertel 10334: #
1.1067    www      10335:                         my $location=$parser->get_text('/import');
                   10336:                         my $dir=$filename;
                   10337:                         $dir=~s|[^/]*$||;
                   10338:                         $location=&filelocation($dir,$location);
1.1069    www      10339:                        
1.1068    www      10340:                         my $importmode=$token->[2]->{'importmode'};
                   10341:                         if ($importmode eq 'problem') {
1.1069    www      10342: # Import as problem/response
1.1068    www      10343:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10344:                         } elsif ($importmode eq 'part') {
                   10345: # Import as part(s)
1.1069    www      10346:                            $importedparts=1;
                   10347: # We need to get the original file and the imported file to get the part order correct
                   10348: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10349: # Load and inspect original file
1.1070    www      10350:                            if ($#origfileimportpartids<0) {
                   10351:                               undef(%importedpartids);
                   10352:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10353:                               my $origfile=&getfile($origfilelocation);
                   10354:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10355:                            }
                   10356: 
1.1069    www      10357: # Load and inspect imported file
                   10358:                            my $impfile=&getfile($location);
                   10359:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10360:                            if ($#impfilepartids>=0) {
                   10361: # This problem had parts
1.1070    www      10362:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10363:                            } else {
                   10364: # Importing by turning a single problem into a problem part
                   10365: # It gets the import-tags ID as part-ID
                   10366:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10367:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10368:                            }
1.1068    www      10369:                         } else {
                   10370: # Normal import
                   10371:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10372:                            if (defined($token->[2]->{'id'})) {
                   10373:                               $unikey.='_'.$token->[2]->{'id'};
                   10374:                            }
1.1067    www      10375:                         }
                   10376: 
1.339     albertel 10377: 			if ($depthcount<20) {
1.736     albertel 10378: 			    my $metadata = 
                   10379: 				&metadata($uri,'keys', $location,$unikey,
                   10380: 					  $depthcount+1);
                   10381: 			    foreach my $meta (split(',',$metadata)) {
                   10382: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10383: 				$metathesekeys{$meta}=1;
1.339     albertel 10384: 			    }
1.1068    www      10385: 			
                   10386:                         }
1.1067    www      10387: 		    } else {
                   10388: #
                   10389: # Not importing, some other kind of non-package, non-library start tag
                   10390: # 
                   10391:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10392:                         if (defined($token->[2]->{'id'})) {
                   10393:                             $unikey.='_'.$token->[2]->{'id'};
                   10394:                         }
1.339     albertel 10395: 			if (defined($token->[2]->{'name'})) { 
                   10396: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10397: 			}
                   10398: 			$metathesekeys{$unikey}=1;
1.736     albertel 10399: 			foreach my $param (@{$token->[3]}) {
                   10400: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10401: 				$token->[2]->{$param};
1.339     albertel 10402: 			}
                   10403: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10404: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10405: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10406: 		 # only ws inside the tag, and not in default, so use default
                   10407: 		 # as value
1.599     albertel 10408: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10409: 			} elsif ( $internaltext =~ /\S/ ) {
                   10410: 		  # something interesting inside the tag
                   10411: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10412: 			} else {
1.908     albertel 10413: 		  # no interesting values, don't set a default
1.339     albertel 10414: 			}
1.172     www      10415: # end of not-a-package not-a-library import
1.339     albertel 10416: 		    }
1.172     www      10417: # end of not-a-package start tag
1.339     albertel 10418: 		}
1.172     www      10419: # the next is the end of "start tag"
1.339     albertel 10420: 	    }
                   10421: 	}
1.483     albertel 10422: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10423: 	$extension = lc($extension);
                   10424: 	if ($extension eq 'htm') { $extension='html'; }
                   10425: 
1.737     albertel 10426: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10427: 	    #no specific packages #how's our extension
                   10428: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10429: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10430: 					 \%metathesekeys);
                   10431: 	}
1.883     albertel 10432: 
                   10433: 	if (!exists($metaentry{':packages'})
                   10434: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10435: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10436: 		#no specific packages well let's get default then
                   10437: 		if ($key!~/^default&/) { next; }
1.488     albertel 10438: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10439: 					     \%metathesekeys);
                   10440: 	    }
                   10441: 	}
1.338     www      10442: # are there custom rights to evaluate
1.599     albertel 10443: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10444: 
1.338     www      10445:     #
                   10446:     # Importing a rights file here
1.339     albertel 10447:     #
                   10448: 	    unless ($depthcount) {
1.599     albertel 10449: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10450: 		my $dir=$filename;
                   10451: 		$dir=~s|[^/]*$||;
                   10452: 		$location=&filelocation($dir,$location);
1.736     albertel 10453: 		my $rights_metadata =
                   10454: 		    &metadata($uri,'keys',$location,'_rights',
                   10455: 			      $depthcount+1);
                   10456: 		foreach my $rights (split(',',$rights_metadata)) {
                   10457: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10458: 		    $metathesekeys{$rights}=1;
1.339     albertel 10459: 		}
                   10460: 	    }
                   10461: 	}
1.737     albertel 10462: 	# uniqifiy package listing
                   10463: 	my %seen;
                   10464: 	my @uniq_packages =
                   10465: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10466: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10467: 
1.1070    www      10468:         if ($importedparts) {
                   10469: # We had imported parts and need to rebuild partorder
                   10470:            $metaentry{':partorder'}='';
                   10471:            $metathesekeys{'partorder'}=1;
                   10472:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10473:                if ($origfileimportpartids[$index] eq 'part') {
                   10474: # original part, part of the problem
                   10475:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10476:                } else {
                   10477: # we have imported parts at this position
                   10478:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10479:                }
                   10480:            }
                   10481:            $metaentry{':partorder'}=~s/^\,//;
                   10482:         }
                   10483: 
1.737     albertel 10484: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10485: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10486: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10487: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10488: # this is the end of "was not already recently cached
1.71      www      10489:     }
1.599     albertel 10490:     return $metaentry{':'.$what};
1.261     albertel 10491: }
                   10492: 
1.488     albertel 10493: sub metadata_create_package_def {
1.483     albertel 10494:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10495:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10496:     if ($subp eq 'default') { next; }
                   10497:     
1.599     albertel 10498:     if (defined($metaentry{':packages'})) {
                   10499: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10500:     } else {
1.599     albertel 10501: 	$metaentry{':packages'}=$package;
1.483     albertel 10502:     }
                   10503:     my $value=$packagetab{$key};
                   10504:     my $unikey;
                   10505:     $unikey='parameter_0_'.$name;
1.599     albertel 10506:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10507:     $$metathesekeys{$unikey}=1;
1.599     albertel 10508:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10509: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10510:     }
1.599     albertel 10511:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10512: 	$metaentry{':'.$unikey}=
                   10513: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10514:     }
                   10515: }
                   10516: 
1.261     albertel 10517: sub metadata_generate_part0 {
                   10518:     my ($metadata,$metacache,$uri) = @_;
                   10519:     my %allnames;
1.737     albertel 10520:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10521: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10522: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10523: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10524: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10525: 	    $allnames{$name}=$part;
                   10526: 	  }
                   10527: 	}
                   10528:     }
                   10529:     foreach my $name (keys(%allnames)) {
                   10530:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10531:       my $key=":parameter_0_$name";
1.261     albertel 10532:       $$metacache{"$key.part"}='0';
                   10533:       $$metacache{"$key.name"}=$name;
1.428     albertel 10534:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10535: 					   $allnames{$name}.'_'.$name.
                   10536: 					   '.type'};
1.428     albertel 10537:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10538: 			     '.display'};
1.644     www      10539:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10540:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10541:       $$metacache{"$key.display"}=$olddis;
                   10542:     }
1.71      www      10543: }
                   10544: 
1.764     albertel 10545: # ------------------------------------------------------ Devalidate title cache
                   10546: 
                   10547: sub devalidate_title_cache {
                   10548:     my ($url)=@_;
                   10549:     if (!$env{'request.course.id'}) { return; }
                   10550:     my $symb=&symbread($url);
                   10551:     if (!$symb) { return; }
                   10552:     my $key=$env{'request.course.id'}."\0".$symb;
                   10553:     &devalidate_cache_new('title',$key);
                   10554: }
                   10555: 
1.1014    droeschl 10556: # ------------------------------------------------- Get the title of a course
                   10557: 
                   10558: sub current_course_title {
                   10559:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10560: }
1.301     www      10561: # ------------------------------------------------- Get the title of a resource
                   10562: 
                   10563: sub gettitle {
                   10564:     my $urlsymb=shift;
                   10565:     my $symb=&symbread($urlsymb);
1.534     albertel 10566:     if ($symb) {
1.620     albertel 10567: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10568: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10569: 	if (defined($cached)) { 
                   10570: 	    return $result;
                   10571: 	}
1.534     albertel 10572: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10573: 	my $title='';
1.907     albertel 10574: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10575: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10576: 	} else {
                   10577: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10578: 		    &GDBM_READER(),0640)) {
                   10579: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10580: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10581: 		untie(%bighash);
                   10582: 	    }
1.534     albertel 10583: 	}
                   10584: 	$title=~s/\&colon\;/\:/gs;
                   10585: 	if ($title) {
1.1159    www      10586: # Remember both $symb and $title for dynamic metadata
                   10587:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10588:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10589: # Cache this title and then return it
1.599     albertel 10590: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10591: 	}
                   10592: 	$urlsymb=$url;
                   10593:     }
                   10594:     my $title=&metadata($urlsymb,'title');
                   10595:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10596:     return $title;
1.301     www      10597: }
1.613     albertel 10598: 
1.614     albertel 10599: sub get_slot {
                   10600:     my ($which,$cnum,$cdom)=@_;
                   10601:     if (!$cnum || !$cdom) {
1.790     albertel 10602: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10603: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10604: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10605:     }
1.703     albertel 10606:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10607:     my %slotinfo;
                   10608:     if (exists($remembered{$key})) {
                   10609: 	$slotinfo{$which} = $remembered{$key};
                   10610:     } else {
                   10611: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10612: 	&Apache::lonhomework::showhash(%slotinfo);
                   10613: 	my ($tmp)=keys(%slotinfo);
                   10614: 	if ($tmp=~/^error:/) { return (); }
                   10615: 	$remembered{$key} = $slotinfo{$which};
                   10616:     }
1.616     albertel 10617:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10618: 	return %{$slotinfo{$which}};
                   10619:     }
                   10620:     return $slotinfo{$which};
1.614     albertel 10621: }
1.1150    raeburn  10622: 
                   10623: sub get_reservable_slots {
                   10624:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10625:     my $now = time;
                   10626:     my $reservable_info;
                   10627:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10628:     if (exists($remembered{$key})) {
                   10629:         $reservable_info = $remembered{$key};
                   10630:     } else {
                   10631:         my %resv;
                   10632:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10633:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10634:         $reservable_info = \%resv;
                   10635:         $remembered{$key} = $reservable_info;
                   10636:     }
                   10637:     return $reservable_info;
                   10638: }
                   10639: 
                   10640: sub get_course_slots {
                   10641:     my ($cnum,$cdom) = @_;
                   10642:     my $hashid=$cnum.':'.$cdom;
                   10643:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10644:     if (defined($cached)) {
                   10645:         if (ref($result) eq 'HASH') {
                   10646:             return %{$result};
                   10647:         }
                   10648:     } else {
                   10649:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10650:         my ($tmp) = keys(%slots);
                   10651:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  10652:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10653:             return %slots;
                   10654:         }
                   10655:     }
                   10656:     return;
                   10657: }
                   10658: 
                   10659: sub devalidate_slots_cache {
                   10660:     my ($cnum,$cdom)=@_;
                   10661:     my $hashid=$cnum.':'.$cdom;
                   10662:     &devalidate_cache_new('allslots',$hashid);
                   10663: }
                   10664: 
1.1181    raeburn  10665: sub get_coursechange {
                   10666:     my ($cdom,$cnum) = @_;
                   10667:     if ($cdom eq '' || $cnum eq '') {
                   10668:         return unless ($env{'request.course.id'});
                   10669:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10670:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10671:     }
                   10672:     my $hashid=$cdom.'_'.$cnum;
                   10673:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10674:     if ((defined($cached)) && ($change ne '')) {
                   10675:         return $change;
                   10676:     } else {
                   10677:         my %crshash;
                   10678:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10679:         if ($crshash{'internal.contentchange'} eq '') {
                   10680:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10681:             if ($change eq '') {
                   10682:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10683:                 $change = $crshash{'internal.created'};
                   10684:             }
                   10685:         } else {
                   10686:             $change = $crshash{'internal.contentchange'};
                   10687:         }
                   10688:         my $cachetime = 600;
                   10689:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10690:     }
                   10691:     return $change;
                   10692: }
                   10693: 
                   10694: sub devalidate_coursechange_cache {
                   10695:     my ($cnum,$cdom)=@_;
                   10696:     my $hashid=$cnum.':'.$cdom;
                   10697:     &devalidate_cache_new('crschange',$hashid);
                   10698: }
                   10699: 
1.31      www      10700: # ------------------------------------------------- Update symbolic store links
                   10701: 
                   10702: sub symblist {
                   10703:     my ($mapname,%newhash)=@_;
1.438     www      10704:     $mapname=&deversion(&declutter($mapname));
1.31      www      10705:     my %hash;
1.620     albertel 10706:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10707:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10708:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10709: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10710: 		next if ($url eq 'last_known'
                   10711: 			 && $env{'form.no_update_last_known'});
                   10712: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10713: 						    $newhash{$url}->[1],
                   10714: 						    $newhash{$url}->[0]);
1.191     harris41 10715:             }
1.31      www      10716:             if (untie(%hash)) {
                   10717: 		return 'ok';
                   10718:             }
                   10719:         }
                   10720:     }
                   10721:     return 'error';
1.212     www      10722: }
                   10723: 
                   10724: # --------------------------------------------------------------- Verify a symb
                   10725: 
                   10726: sub symbverify {
1.1190    raeburn  10727:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10728:     my $thisfn=$thisurl;
1.439     www      10729:     $thisfn=&declutter($thisfn);
1.215     www      10730: # direct jump to resource in page or to a sequence - will construct own symbs
                   10731:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10732: # check URL part
1.409     www      10733:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10734: 
1.431     www      10735:     unless ($url eq $thisfn) { return 0; }
1.213     www      10736: 
1.216     www      10737:     $symb=&symbclean($symb);
1.510     www      10738:     $thisurl=&deversion($thisurl);
1.439     www      10739:     $thisfn=&deversion($thisfn);
1.213     www      10740: 
                   10741:     my %bighash;
                   10742:     my $okay=0;
1.431     www      10743: 
1.620     albertel 10744:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10745:                             &GDBM_READER(),0640)) {
1.1204    raeburn  10746:         my $noclutter;
1.1032    raeburn  10747:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10748:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  10749:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10750:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10751:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10752:                 $noclutter = 1;
                   10753:             }
                   10754:         }
                   10755:         my $ids;
                   10756:         if ($noclutter) {
                   10757:             $ids=$bighash{'ids_'.$thisurl};
                   10758:         } else {
                   10759:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10760:         }
1.1102    raeburn  10761:         unless ($ids) {
                   10762:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   10763:             $ids=$bighash{$idkey};
1.216     www      10764:         }
                   10765:         if ($ids) {
                   10766: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  10767:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  10768:                 $symb =~ s/\?.+$//;
1.1202    raeburn  10769:             }
1.800     albertel 10770: 	    foreach my $id (split(/\,/,$ids)) {
                   10771: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10772:                if (
                   10773:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  10774:    eq $symb) {
                   10775:                    if (ref($encstate)) {
                   10776:                        $$encstate = $bighash{'encrypted_'.$id};
                   10777:                    }
1.620     albertel 10778: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  10779: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   10780:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  10781: 		       $okay=1;
1.1202    raeburn  10782:                        last;
1.582     albertel 10783: 		   }
                   10784: 	       }
1.216     www      10785: 	   }
                   10786:         }
1.213     www      10787: 	untie(%bighash);
                   10788:     }
                   10789:     return $okay;
1.31      www      10790: }
                   10791: 
1.210     www      10792: # --------------------------------------------------------------- Clean-up symb
                   10793: 
                   10794: sub symbclean {
                   10795:     my $symb=shift;
1.568     albertel 10796:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10797: # remove version from map
                   10798:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10799: 
1.210     www      10800: # remove version from URL
                   10801:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10802: 
1.507     www      10803: # remove wrapper
                   10804: 
1.510     www      10805:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10806:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10807:     return $symb;
1.409     www      10808: }
                   10809: 
                   10810: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10811: 
                   10812: sub encode_symb {
                   10813:     my ($map,$resid,$url)=@_;
                   10814:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10815: }
1.409     www      10816: 
                   10817: sub decode_symb {
1.568     albertel 10818:     my $symb=shift;
                   10819:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10820:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10821:     return (&fixversion($map),$resid,&fixversion($url));
                   10822: }
                   10823: 
                   10824: sub fixversion {
                   10825:     my $fn=shift;
1.609     banghart 10826:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10827:     my %bighash;
                   10828:     my $uri=&clutter($fn);
1.620     albertel 10829:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10830: # is this cached?
1.599     albertel 10831:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10832:     if (defined($cached)) { return $result; }
                   10833: # unfortunately not cached, or expired
1.620     albertel 10834:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10835: 	    &GDBM_READER(),0640)) {
                   10836:  	if ($bighash{'version_'.$uri}) {
                   10837:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10838:  	    unless (($version eq 'mostrecent') || 
                   10839: 		    ($version==&getversion($uri))) {
1.440     www      10840:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10841:  	    }
                   10842:  	}
                   10843:  	untie %bighash;
1.413     www      10844:     }
1.599     albertel 10845:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10846: }
                   10847: 
                   10848: sub deversion {
                   10849:     my $url=shift;
                   10850:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10851:     return $url;
1.210     www      10852: }
                   10853: 
1.31      www      10854: # ------------------------------------------------------ Return symb list entry
                   10855: 
                   10856: sub symbread {
1.249     www      10857:     my ($thisfn,$donotrecurse)=@_;
1.1265    raeburn  10858:     my $cache_str='request.symbread.cached.'.$thisfn;
                   10859:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      10860: # no filename provided? try from environment
1.1265    raeburn  10861:     unless ($thisfn) {
1.620     albertel 10862:         if ($env{'request.symb'}) {
                   10863: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 10864: 	}
1.620     albertel 10865: 	$thisfn=$env{'request.filename'};
1.44      www      10866:     }
1.569     albertel 10867:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10868: # is that filename actually a symb? Verify, clean, and return
                   10869:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10870: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10871: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10872: 	}
1.242     www      10873:     }
1.44      www      10874:     $thisfn=declutter($thisfn);
1.31      www      10875:     my %hash;
1.37      www      10876:     my %bighash;
                   10877:     my $syval='';
1.620     albertel 10878:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10879:         my $targetfn = $thisfn;
1.609     banghart 10880:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10881:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10882:         }
1.687     albertel 10883: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10884: 	    $targetfn=$1;
                   10885: 	}
1.620     albertel 10886:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10887:                       &GDBM_READER(),0640)) {
1.481     raeburn  10888: 	    $syval=$hash{$targetfn};
1.37      www      10889:             untie(%hash);
                   10890:         }
                   10891: # ---------------------------------------------------------- There was an entry
                   10892:         if ($syval) {
1.601     albertel 10893: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10894: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10895: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10896: 		    #return $env{$cache_str}='';
1.601     albertel 10897: 		#}    
                   10898: 		#$syval.=$1;
                   10899: 	    #}
1.37      www      10900:         } else {
                   10901: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10902:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10903:                             &GDBM_READER(),0640)) {
1.37      www      10904: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10905:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10906:               unless ($ids) { 
                   10907:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10908:               }
                   10909:               unless ($ids) {
                   10910: # alias?
                   10911: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10912:               }
1.37      www      10913:               if ($ids) {
                   10914: # ------------------------------------------------------------------- Has ID(s)
                   10915:                  my @possibilities=split(/\,/,$ids);
1.39      www      10916:                  if ($#possibilities==0) {
                   10917: # ----------------------------------------------- There is only one possibility
1.37      www      10918: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10919: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10920: 						    $resid,$thisfn);
1.249     www      10921:                  } elsif (!$donotrecurse) {
1.39      www      10922: # ------------------------------------------ There is more than one possibility
                   10923:                      my $realpossible=0;
1.800     albertel 10924:                      foreach my $id (@possibilities) {
                   10925: 			 my $file=$bighash{'src_'.$id};
1.39      www      10926:                          if (&allowed('bre',$file)) {
1.800     albertel 10927:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10928:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10929: 				$realpossible++;
1.626     albertel 10930:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10931: 						    $resid,$thisfn);
1.39      www      10932:                             }
                   10933: 			 }
1.191     harris41 10934:                      }
1.39      www      10935: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10936:                  } else {
                   10937:                      $syval='';
1.37      www      10938:                  }
                   10939: 	      }
                   10940:               untie(%bighash)
1.481     raeburn  10941:            }
1.31      www      10942:         }
1.62      www      10943:         if ($syval) {
1.620     albertel 10944: 	    return $env{$cache_str}=$syval;
1.62      www      10945:         }
1.31      www      10946:     }
1.949     raeburn  10947:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10948:     return $env{$cache_str}='';
1.31      www      10949: }
                   10950: 
                   10951: # ---------------------------------------------------------- Return random seed
                   10952: 
1.32      www      10953: sub numval {
                   10954:     my $txt=shift;
                   10955:     $txt=~tr/A-J/0-9/;
                   10956:     $txt=~tr/a-j/0-9/;
                   10957:     $txt=~tr/K-T/0-9/;
                   10958:     $txt=~tr/k-t/0-9/;
                   10959:     $txt=~tr/U-Z/0-5/;
                   10960:     $txt=~tr/u-z/0-5/;
                   10961:     $txt=~s/\D//g;
1.564     albertel 10962:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10963:     return int($txt);
1.368     albertel 10964: }
                   10965: 
1.484     albertel 10966: sub numval2 {
                   10967:     my $txt=shift;
                   10968:     $txt=~tr/A-J/0-9/;
                   10969:     $txt=~tr/a-j/0-9/;
                   10970:     $txt=~tr/K-T/0-9/;
                   10971:     $txt=~tr/k-t/0-9/;
                   10972:     $txt=~tr/U-Z/0-5/;
                   10973:     $txt=~tr/u-z/0-5/;
                   10974:     $txt=~s/\D//g;
                   10975:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10976:     my $total;
                   10977:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10978:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10979:     return int($total);
                   10980: }
                   10981: 
1.575     albertel 10982: sub numval3 {
                   10983:     use integer;
                   10984:     my $txt=shift;
                   10985:     $txt=~tr/A-J/0-9/;
                   10986:     $txt=~tr/a-j/0-9/;
                   10987:     $txt=~tr/K-T/0-9/;
                   10988:     $txt=~tr/k-t/0-9/;
                   10989:     $txt=~tr/U-Z/0-5/;
                   10990:     $txt=~tr/u-z/0-5/;
                   10991:     $txt=~s/\D//g;
                   10992:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10993:     my $total;
                   10994:     foreach my $val (@txts) { $total+=$val; }
                   10995:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10996:     return $total;
                   10997: }
                   10998: 
1.675     albertel 10999: sub digest {
                   11000:     my ($data)=@_;
                   11001:     my $digest=&Digest::MD5::md5($data);
                   11002:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11003:     my ($e,$f);
                   11004:     {
                   11005:         use integer;
                   11006:         $e=($a+$b);
                   11007:         $f=($c+$d);
                   11008:         if ($_64bit) {
                   11009:             $e=(($e<<32)>>32);
                   11010:             $f=(($f<<32)>>32);
                   11011:         }
                   11012:     }
                   11013:     if (wantarray) {
                   11014: 	return ($e,$f);
                   11015:     } else {
                   11016: 	my $g;
                   11017: 	{
                   11018: 	    use integer;
                   11019: 	    $g=($e+$f);
                   11020: 	    if ($_64bit) {
                   11021: 		$g=(($g<<32)>>32);
                   11022: 	    }
                   11023: 	}
                   11024: 	return $g;
                   11025:     }
                   11026: }
                   11027: 
1.368     albertel 11028: sub latest_rnd_algorithm_id {
1.675     albertel 11029:     return '64bit5';
1.366     albertel 11030: }
1.32      www      11031: 
1.503     albertel 11032: sub get_rand_alg {
                   11033:     my ($courseid)=@_;
1.790     albertel 11034:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11035:     if ($courseid) {
1.620     albertel 11036: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11037:     }
                   11038:     return &latest_rnd_algorithm_id();
                   11039: }
                   11040: 
1.562     albertel 11041: sub validCODE {
                   11042:     my ($CODE)=@_;
                   11043:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11044:     return 0;
                   11045: }
                   11046: 
1.491     albertel 11047: sub getCODE {
1.620     albertel 11048:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11049:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11050: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11051: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11052: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11053:     }
                   11054:     return undef;
                   11055: }
1.1133    foxr     11056: #
                   11057: #  Determines the random seed for a specific context:
                   11058: #
                   11059: # parameters:
                   11060: #   symb      - in course context the symb for the seed.
                   11061: #   course_id - The course id of the form domain_coursenum.
                   11062: #   domain    - Domain for the user.
                   11063: #   course    - Course for the user.
                   11064: #   cenv      - environment of the course.
                   11065: #
                   11066: # NOTE:
                   11067: #   All parameters are picked out of the environment if missing
                   11068: #   or not defined.
                   11069: #   If a symb cannot be determined the current time is used instead.
                   11070: #
                   11071: #  For a given well defined symb, courside, domain, username,
                   11072: #  and course environment, the seed is reproducible.
                   11073: #
1.31      www      11074: sub rndseed {
1.1133    foxr     11075:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11076:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11077:     if (!defined($symb)) {
1.366     albertel 11078: 	unless ($symb=$wsymb) { return time; }
                   11079:     }
1.1146    foxr     11080:     if (!defined $courseid) { 
                   11081: 	$courseid=$wcourseid; 
                   11082:     }
                   11083:     if (!defined $domain) { $domain=$wdomain; }
                   11084:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11085: 
                   11086:     my $which;
                   11087:     if (defined($cenv->{'rndseed'})) {
                   11088: 	$which = $cenv->{'rndseed'};
                   11089:     } else {
                   11090: 	$which =&get_rand_alg($courseid);
                   11091:     }
1.491     albertel 11092:     if (defined(&getCODE())) {
1.1133    foxr     11093: 
1.675     albertel 11094: 	if ($which eq '64bit5') {
                   11095: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11096: 	} elsif ($which eq '64bit4') {
1.575     albertel 11097: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11098: 	} else {
                   11099: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11100: 	}
1.675     albertel 11101:     } elsif ($which eq '64bit5') {
                   11102: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11103:     } elsif ($which eq '64bit4') {
                   11104: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11105:     } elsif ($which eq '64bit3') {
                   11106: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11107:     } elsif ($which eq '64bit2') {
                   11108: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11109:     } elsif ($which eq '64bit') {
                   11110: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11111:     }
                   11112:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11113: }
                   11114: 
                   11115: sub rndseed_32bit {
                   11116:     my ($symb,$courseid,$domain,$username)=@_;
                   11117:     {
                   11118: 	use integer;
                   11119: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11120: 	my $symbseed=numval($symb) << 22;
                   11121: 	my $namechck=unpack("%32C*",$username) << 17;
                   11122: 	my $nameseed=numval($username) << 12;
                   11123: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11124: 	my $courseseed=unpack("%32C*",$courseid);
                   11125: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11126: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11127: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11128: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11129: 	return $num;
                   11130:     }
                   11131: }
                   11132: 
                   11133: sub rndseed_64bit {
                   11134:     my ($symb,$courseid,$domain,$username)=@_;
                   11135:     {
                   11136: 	use integer;
                   11137: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11138: 	my $symbseed=numval($symb) << 10;
                   11139: 	my $namechck=unpack("%32S*",$username);
                   11140: 	
                   11141: 	my $nameseed=numval($username) << 21;
                   11142: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11143: 	my $courseseed=unpack("%32S*",$courseid);
                   11144: 	
                   11145: 	my $num1=$symbchck+$symbseed+$namechck;
                   11146: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11147: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11148: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11149: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11150: 	return "$num1,$num2";
1.155     albertel 11151:     }
1.366     albertel 11152: }
                   11153: 
1.443     albertel 11154: sub rndseed_64bit2 {
                   11155:     my ($symb,$courseid,$domain,$username)=@_;
                   11156:     {
                   11157: 	use integer;
                   11158: 	# strings need to be an even # of cahracters long, it it is odd the
                   11159:         # last characters gets thrown away
                   11160: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11161: 	my $symbseed=numval($symb) << 10;
                   11162: 	my $namechck=unpack("%32S*",$username.' ');
                   11163: 	
                   11164: 	my $nameseed=numval($username) << 21;
1.501     albertel 11165: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11166: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11167: 	
                   11168: 	my $num1=$symbchck+$symbseed+$namechck;
                   11169: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11170: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11171: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11172: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11173: 	return "$num1,$num2";
                   11174:     }
                   11175: }
                   11176: 
                   11177: sub rndseed_64bit3 {
                   11178:     my ($symb,$courseid,$domain,$username)=@_;
                   11179:     {
                   11180: 	use integer;
                   11181: 	# strings need to be an even # of cahracters long, it it is odd the
                   11182:         # last characters gets thrown away
                   11183: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11184: 	my $symbseed=numval2($symb) << 10;
                   11185: 	my $namechck=unpack("%32S*",$username.' ');
                   11186: 	
                   11187: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11188: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11189: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11190: 	
                   11191: 	my $num1=$symbchck+$symbseed+$namechck;
                   11192: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11193: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11194: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11195: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11196: 	
1.503     albertel 11197: 	return "$num1:$num2";
1.443     albertel 11198:     }
                   11199: }
                   11200: 
1.575     albertel 11201: sub rndseed_64bit4 {
                   11202:     my ($symb,$courseid,$domain,$username)=@_;
                   11203:     {
                   11204: 	use integer;
                   11205: 	# strings need to be an even # of cahracters long, it it is odd the
                   11206:         # last characters gets thrown away
                   11207: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11208: 	my $symbseed=numval3($symb) << 10;
                   11209: 	my $namechck=unpack("%32S*",$username.' ');
                   11210: 	
                   11211: 	my $nameseed=numval3($username) << 21;
                   11212: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11213: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11214: 	
                   11215: 	my $num1=$symbchck+$symbseed+$namechck;
                   11216: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11217: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11218: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11219: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11220: 	
1.575     albertel 11221: 	return "$num1:$num2";
                   11222:     }
                   11223: }
                   11224: 
1.675     albertel 11225: sub rndseed_64bit5 {
                   11226:     my ($symb,$courseid,$domain,$username)=@_;
                   11227:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11228:     return "$num1:$num2";
                   11229: }
                   11230: 
1.366     albertel 11231: sub rndseed_CODE_64bit {
                   11232:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11233:     {
1.366     albertel 11234: 	use integer;
1.443     albertel 11235: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11236: 	my $symbseed=numval2($symb);
1.491     albertel 11237: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11238: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11239: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11240: 	my $num1=$symbseed+$CODEchck;
                   11241: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11242: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11243: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11244: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11245: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11246: 	return "$num1:$num2";
1.366     albertel 11247:     }
                   11248: }
                   11249: 
1.575     albertel 11250: sub rndseed_CODE_64bit4 {
                   11251:     my ($symb,$courseid,$domain,$username)=@_;
                   11252:     {
                   11253: 	use integer;
                   11254: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11255: 	my $symbseed=numval3($symb);
                   11256: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11257: 	my $CODEseed=numval3(&getCODE());
                   11258: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11259: 	my $num1=$symbseed+$CODEchck;
                   11260: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11261: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11262: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11263: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11264: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11265: 	return "$num1:$num2";
                   11266:     }
                   11267: }
                   11268: 
1.675     albertel 11269: sub rndseed_CODE_64bit5 {
                   11270:     my ($symb,$courseid,$domain,$username)=@_;
                   11271:     my $code = &getCODE();
                   11272:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11273:     return "$num1:$num2";
                   11274: }
                   11275: 
1.366     albertel 11276: sub setup_random_from_rndseed {
                   11277:     my ($rndseed)=@_;
1.503     albertel 11278:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  11279:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   11280:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   11281:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   11282:         } else {
                   11283:             &Math::Random::random_set_seed($num1,$num2);
                   11284:         }
1.366     albertel 11285:     } else {
                   11286: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11287:     }
1.36      albertel 11288: }
                   11289: 
1.474     albertel 11290: sub latest_receipt_algorithm_id {
1.835     albertel 11291:     return 'receipt3';
1.474     albertel 11292: }
                   11293: 
1.480     www      11294: sub recunique {
                   11295:     my $fucourseid=shift;
                   11296:     my $unique;
1.835     albertel 11297:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11298: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11299: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11300:     } else {
                   11301: 	$unique=$perlvar{'lonReceipt'};
                   11302:     }
                   11303:     return unpack("%32C*",$unique);
                   11304: }
                   11305: 
                   11306: sub recprefix {
                   11307:     my $fucourseid=shift;
                   11308:     my $prefix;
1.835     albertel 11309:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11310: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11311: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11312:     } else {
                   11313: 	$prefix=$perlvar{'lonHostID'};
                   11314:     }
                   11315:     return unpack("%32C*",$prefix);
                   11316: }
                   11317: 
1.76      www      11318: sub ireceipt {
1.474     albertel 11319:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11320: 
                   11321:     my $return =&recprefix($fucourseid).'-';
                   11322: 
                   11323:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11324: 	$env{'request.state'} eq 'construct') {
                   11325: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11326: 	return $return;
                   11327:     }
                   11328: 
1.76      www      11329:     my $cuname=unpack("%32C*",$funame);
                   11330:     my $cudom=unpack("%32C*",$fudom);
                   11331:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11332:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11333:     my $cunique=&recunique($fucourseid);
1.474     albertel 11334:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11335:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11336: 
1.790     albertel 11337: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11338: 			       
                   11339: 	$return.= ($cunique%$cuname+
                   11340: 		   $cunique%$cudom+
                   11341: 		   $cusymb%$cuname+
                   11342: 		   $cusymb%$cudom+
                   11343: 		   $cucourseid%$cuname+
                   11344: 		   $cucourseid%$cudom+
                   11345: 		   $cpart%$cuname+
                   11346: 		   $cpart%$cudom);
                   11347:     } else {
                   11348: 	$return.= ($cunique%$cuname+
                   11349: 		   $cunique%$cudom+
                   11350: 		   $cusymb%$cuname+
                   11351: 		   $cusymb%$cudom+
                   11352: 		   $cucourseid%$cuname+
                   11353: 		   $cucourseid%$cudom);
                   11354:     }
                   11355:     return $return;
1.76      www      11356: }
                   11357: 
                   11358: sub receipt {
1.474     albertel 11359:     my ($part)=@_;
1.790     albertel 11360:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11361:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11362: }
1.260     ng       11363: 
1.790     albertel 11364: sub whichuser {
                   11365:     my ($passedsymb)=@_;
                   11366:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11367:     if (defined($env{'form.grade_symb'})) {
                   11368: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11369: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11370: 	if (!$allowed &&
                   11371: 	    exists($env{'request.course.sec'}) &&
                   11372: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11373: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11374: 			      '/'.$env{'request.course.sec'});
                   11375: 	}
                   11376: 	if ($allowed) {
                   11377: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11378: 	    $courseid=$tmp_courseid;
                   11379: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11380: 	    ($name)=&get_env_multiple('form.grade_username');
                   11381: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11382: 	}
                   11383:     }
                   11384:     if (!$passedsymb) {
                   11385: 	$symb=&symbread();
                   11386:     } else {
                   11387: 	$symb=$passedsymb;
                   11388:     }
                   11389:     $courseid=$env{'request.course.id'};
                   11390:     $domain=$env{'user.domain'};
                   11391:     $name=$env{'user.name'};
                   11392:     if ($name eq 'public' && $domain eq 'public') {
                   11393: 	if (!defined($env{'form.username'})) {
                   11394: 	    $env{'form.username'}.=time.rand(10000000);
                   11395: 	}
                   11396: 	$name.=$env{'form.username'};
                   11397:     }
                   11398:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11399: 
                   11400: }
                   11401: 
1.36      albertel 11402: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11403: # returns either the contents of the file or 
                   11404: # -1 if the file doesn't exist
1.481     raeburn  11405: #
                   11406: # if the target is a file that was uploaded via DOCS, 
                   11407: # a check will be made to see if a current copy exists on the local server,
                   11408: # if it does this will be served, otherwise a copy will be retrieved from
                   11409: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11410: # the local server.   
1.472     albertel 11411: 
1.36      albertel 11412: sub getfile {
1.538     albertel 11413:     my ($file) = @_;
1.609     banghart 11414:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11415:     &repcopy($file);
                   11416:     return &readfile($file);
                   11417: }
                   11418: 
                   11419: sub repcopy_userfile {
                   11420:     my ($file)=@_;
1.1142    raeburn  11421:     my $londocroot = $perlvar{'lonDocRoot'};
                   11422:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11423:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11424:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11425: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11426:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11427:     if (-e "$file") {
1.828     www      11428: # we already have a local copy, check it out
1.538     albertel 11429: 	my @fileinfo = stat($file);
1.828     www      11430: 	my $rtncode;
                   11431: 	my $info;
1.538     albertel 11432: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11433: 	if ($lwpresp ne 'ok') {
1.828     www      11434: # there is no such file anymore, even though we had a local copy
1.482     albertel 11435: 	    if ($rtncode eq '404') {
1.538     albertel 11436: 		unlink($file);
1.482     albertel 11437: 	    }
                   11438: 	    return -1;
                   11439: 	}
                   11440: 	if ($info < $fileinfo[9]) {
1.828     www      11441: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11442: 	    return 'ok';
1.828     www      11443: 	} else {
                   11444: # the file is outdated, get rid of it
                   11445: 	    unlink($file);
1.482     albertel 11446: 	}
1.828     www      11447:     }
                   11448: # one way or the other, at this point, we don't have the file
                   11449: # construct the correct path for the file
                   11450:     my @parts = ($cdom,$cnum); 
                   11451:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11452: 	push @parts, split(/\//,$1);
                   11453:     }
                   11454:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11455:     foreach my $part (@parts) {
                   11456: 	$path .= '/'.$part;
                   11457: 	if (!-e $path) {
                   11458: 	    mkdir($path,0770);
1.482     albertel 11459: 	}
                   11460:     }
1.828     www      11461: # now the path exists for sure
                   11462: # get a user agent
                   11463:     my $ua=new LWP::UserAgent;
                   11464:     my $transferfile=$file.'.in.transfer';
                   11465: # FIXME: this should flock
                   11466:     if (-e $transferfile) { return 'ok'; }
                   11467:     my $request;
                   11468:     $uri=~s/^\///;
1.980     raeburn  11469:     my $homeserver = &homeserver($cnum,$cdom);
                   11470:     my $protocol = $protocol{$homeserver};
                   11471:     $protocol = 'http' if ($protocol ne 'https');
                   11472:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11473:     my $response=$ua->request($request,$transferfile);
                   11474: # did it work?
                   11475:     if ($response->is_error()) {
                   11476: 	unlink($transferfile);
                   11477: 	&logthis("Userfile repcopy failed for $uri");
                   11478: 	return -1;
                   11479:     }
                   11480: # worked, rename the transfer file
                   11481:     rename($transferfile,$file);
1.607     raeburn  11482:     return 'ok';
1.481     raeburn  11483: }
                   11484: 
1.517     albertel 11485: sub tokenwrapper {
                   11486:     my $uri=shift;
1.980     raeburn  11487:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11488:     $uri=~s|^/||;
1.620     albertel 11489:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11490:     my $token=$1;
1.552     albertel 11491:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11492:     if ($udom && $uname && $file) {
                   11493: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11494:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11495:         my $homeserver = &homeserver($uname,$udom);
                   11496:         my $protocol = $protocol{$homeserver};
                   11497:         $protocol = 'http' if ($protocol ne 'https');
                   11498:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11499:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11500:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11501:     } else {
                   11502:         return '/adm/notfound.html';
                   11503:     }
                   11504: }
                   11505: 
1.828     www      11506: # call with reqtype HEAD: get last modification time
                   11507: # call with reqtype GET: get the file contents
                   11508: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11509: #
1.481     raeburn  11510: sub getuploaded {
                   11511:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11512:     $uri=~s/^\///;
1.980     raeburn  11513:     my $homeserver = &homeserver($cnum,$cdom);
                   11514:     my $protocol = $protocol{$homeserver};
                   11515:     $protocol = 'http' if ($protocol ne 'https');
                   11516:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11517:     my $ua=new LWP::UserAgent;
                   11518:     my $request=new HTTP::Request($reqtype,$uri);
                   11519:     my $response=$ua->request($request);
                   11520:     $$rtncode = $response->code;
1.482     albertel 11521:     if (! $response->is_success()) {
                   11522: 	return 'failed';
                   11523:     }      
                   11524:     if ($reqtype eq 'HEAD') {
1.486     www      11525: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11526:     } elsif ($reqtype eq 'GET') {
                   11527: 	$$info = $response->content;
1.472     albertel 11528:     }
1.482     albertel 11529:     return 'ok';
1.36      albertel 11530: }
                   11531: 
1.481     raeburn  11532: sub readfile {
                   11533:     my $file = shift;
                   11534:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11535:     my $fh;
                   11536:     open($fh,"<$file");
                   11537:     my $a='';
1.800     albertel 11538:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11539:     return $a;
                   11540: }
                   11541: 
1.36      albertel 11542: sub filelocation {
1.590     banghart 11543:     my ($dir,$file) = @_;
                   11544:     my $location;
                   11545:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11546: 
                   11547:     if ($file =~ m-^/adm/-) {
                   11548: 	$file=~s-^/adm/wrapper/-/-;
                   11549: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11550:     }
1.882     albertel 11551: 
1.1139    www      11552:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11553:         $location = $file;
1.609     banghart 11554:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11555:         my ($udom,$uname,$filename)=
1.811     albertel 11556:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11557:         my $home=&homeserver($uname,$udom);
                   11558:         my $is_me=0;
                   11559:         my @ids=&current_machine_ids();
                   11560:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11561:         if ($is_me) {
1.1117    foxr     11562:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11563:         } else {
                   11564:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11565:   	      $udom.'/'.$uname.'/'.$filename;
                   11566:         }
1.882     albertel 11567:     } elsif ($file =~ m-^/adm/-) {
                   11568: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11569:     } else {
                   11570:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11571:         $file=~s:^/(res|priv)/:/:;
                   11572:         my $space=$1;
1.590     banghart 11573:         if ( !( $file =~ m:^/:) ) {
                   11574:             $location = $dir. '/'.$file;
                   11575:         } else {
1.1142    raeburn  11576:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11577:         }
1.59      albertel 11578:     }
1.590     banghart 11579:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11580:     while ($location=~m{/\.\./}) {
                   11581: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11582: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11583: 	} else {
                   11584: 	    $location=~ s{/\.\./}{/}g;
                   11585: 	}
                   11586:     } #remove dir/..
1.590     banghart 11587:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11588:     return $location;
1.46      www      11589: }
1.36      albertel 11590: 
1.46      www      11591: sub hreflocation {
                   11592:     my ($dir,$file)=@_;
1.980     raeburn  11593:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11594: 	$file=filelocation($dir,$file);
1.700     albertel 11595:     } elsif ($file=~m-^/adm/-) {
                   11596: 	$file=~s-^/adm/wrapper/-/-;
                   11597: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11598:     }
                   11599:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11600: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11601:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11602: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11603: 	        {/uploaded/$1/$2/}x;
1.46      www      11604:     }
1.913     albertel 11605:     if ($file=~ m{^/userfiles/}) {
                   11606: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11607:     }
1.462     albertel 11608:     return $file;
1.465     albertel 11609: }
                   11610: 
1.1139    www      11611: 
                   11612: 
                   11613: 
                   11614: 
1.465     albertel 11615: sub current_machine_domains {
1.853     albertel 11616:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11617: }
                   11618: 
                   11619: sub machine_domains {
                   11620:     my ($hostname) = @_;
1.465     albertel 11621:     my @domains;
1.838     albertel 11622:     my %hostname = &all_hostnames();
1.465     albertel 11623:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11624: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11625: 	if ($hostname eq $name) {
1.844     albertel 11626: 	    push(@domains,&host_domain($id));
1.465     albertel 11627: 	}
                   11628:     }
                   11629:     return @domains;
                   11630: }
                   11631: 
                   11632: sub current_machine_ids {
1.853     albertel 11633:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11634: }
                   11635: 
                   11636: sub machine_ids {
                   11637:     my ($hostname) = @_;
                   11638:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11639:     my @ids;
1.888     albertel 11640:     my %name_to_host = &all_names();
1.889     albertel 11641:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11642: 	return @{ $name_to_host{$hostname} };
                   11643:     }
                   11644:     return;
1.31      www      11645: }
                   11646: 
1.824     raeburn  11647: sub additional_machine_domains {
                   11648:     my @domains;
                   11649:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11650:     while( my $line = <$fh>) {
                   11651:         $line =~ s/\s//g;
                   11652:         push(@domains,$line);
                   11653:     }
                   11654:     return @domains;
                   11655: }
                   11656: 
                   11657: sub default_login_domain {
                   11658:     my $domain = $perlvar{'lonDefDomain'};
                   11659:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11660:     foreach my $posdom (&current_machine_domains(),
                   11661:                         &additional_machine_domains()) {
                   11662:         if (lc($posdom) eq lc($testdomain)) {
                   11663:             $domain=$posdom;
                   11664:             last;
                   11665:         }
                   11666:     }
                   11667:     return $domain;
                   11668: }
                   11669: 
1.31      www      11670: # ------------------------------------------------------------- Declutters URLs
                   11671: 
                   11672: sub declutter {
                   11673:     my $thisfn=shift;
1.569     albertel 11674:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  11675:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   11676:         $thisfn=~s{^/home/httpd/html}{};
                   11677:     }
1.31      www      11678:     $thisfn=~s/^\///;
1.697     albertel 11679:     $thisfn=~s|^adm/wrapper/||;
                   11680:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11681:     $thisfn=~s/^res\///;
1.1172    bisitz   11682:     $thisfn=~s/^priv\///;
1.1032    raeburn  11683:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11684:         $thisfn=~s/\?.+$//;
                   11685:     }
1.268     www      11686:     return $thisfn;
                   11687: }
                   11688: 
                   11689: # ------------------------------------------------------------- Clutter up URLs
                   11690: 
                   11691: sub clutter {
                   11692:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11693:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11694: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11695:        $thisfn='/res'.$thisfn; 
                   11696:     }
1.1031    raeburn  11697:     if ($thisfn !~m|^/adm|) {
                   11698: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11699: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11700: 	} else {
                   11701: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11702: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11703: 	    if ($embstyle eq 'ssi'
                   11704: 		|| ($embstyle eq 'hdn')
                   11705: 		|| ($embstyle eq 'rat')
                   11706: 		|| ($embstyle eq 'prv')
                   11707: 		|| ($embstyle eq 'ign')) {
                   11708: 		#do nothing with these
                   11709: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11710: 		|| ($embstyle eq 'emb')
                   11711: 		|| ($embstyle eq 'wrp')) {
                   11712: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11713: 	    } elsif ($embstyle eq 'unk'
                   11714: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11715: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11716: 	    } else {
1.718     www      11717: #		&logthis("Got a blank emb style");
1.695     albertel 11718: 	    }
1.694     albertel 11719: 	}
                   11720:     }
1.31      www      11721:     return $thisfn;
1.12      www      11722: }
                   11723: 
1.787     albertel 11724: sub clutter_with_no_wrapper {
                   11725:     my $uri = &clutter(shift);
                   11726:     if ($uri =~ m-^/adm/-) {
                   11727: 	$uri =~ s-^/adm/wrapper/-/-;
                   11728: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11729:     }
                   11730:     return $uri;
                   11731: }
                   11732: 
1.557     albertel 11733: sub freeze_escape {
                   11734:     my ($value)=@_;
                   11735:     if (ref($value)) {
                   11736: 	$value=&nfreeze($value);
                   11737: 	return '__FROZEN__'.&escape($value);
                   11738:     }
                   11739:     return &escape($value);
                   11740: }
                   11741: 
1.11      www      11742: 
1.557     albertel 11743: sub thaw_unescape {
                   11744:     my ($value)=@_;
                   11745:     if ($value =~ /^__FROZEN__/) {
                   11746: 	substr($value,0,10,undef);
                   11747: 	$value=&unescape($value);
                   11748: 	return &thaw($value);
                   11749:     }
                   11750:     return &unescape($value);
                   11751: }
                   11752: 
1.436     albertel 11753: sub correct_line_ends {
                   11754:     my ($result)=@_;
                   11755:     $$result =~s/\r\n/\n/mg;
                   11756:     $$result =~s/\r/\n/mg;
1.415     albertel 11757: }
1.1       albertel 11758: # ================================================================ Main Program
                   11759: 
1.184     www      11760: sub goodbye {
1.204     albertel 11761:    &logthis("Starting Shut down");
1.443     albertel 11762: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11763:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11764: #converted
1.599     albertel 11765: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11766:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11767: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11768: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11769: #1.1 only
1.870     albertel 11770: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11771: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11772: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11773: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11774:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11775:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11776:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11777:    &flushcourselogs();
                   11778:    &logthis("Shutting down");
                   11779: }
                   11780: 
1.852     albertel 11781: sub get_dns {
1.1210    raeburn  11782:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11783:     if (!$ignore_cache) {
                   11784: 	my ($content,$cached)=
                   11785: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11786: 	if ($cached) {
1.1210    raeburn  11787: 	    &$func($content,$hashref);
1.869     albertel 11788: 	    return;
                   11789: 	}
                   11790:     }
                   11791: 
                   11792:     my %alldns;
1.852     albertel 11793:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11794:     foreach my $dns (<$config>) {
                   11795: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11796:         my $line = $1;
                   11797:         my ($host,$protocol) = split(/:/,$line);
                   11798:         if ($protocol ne 'https') {
                   11799:             $protocol = 'http';
                   11800:         }
                   11801: 	$alldns{$host} = $protocol;
1.869     albertel 11802:     }
                   11803:     while (%alldns) {
1.1263    raeburn  11804: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 11805: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11806:         $ua->timeout(30);
1.979     raeburn  11807: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11808: 	my $response=$ua->request($request);
1.979     raeburn  11809:         delete($alldns{$dns});
1.852     albertel 11810: 	next if ($response->is_error());
                   11811: 	my @content = split("\n",$response->content);
1.1210    raeburn  11812: 	unless ($nocache) {
1.1219    raeburn  11813: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  11814: 	}
                   11815: 	&$func(\@content,$hashref);
1.869     albertel 11816: 	return;
1.852     albertel 11817:     }
                   11818:     close($config);
1.871     albertel 11819:     my $which = (split('/',$url))[3];
                   11820:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11821:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11822:     my @content = <$config>;
1.1210    raeburn  11823:     &$func(\@content,$hashref);
                   11824:     return;
                   11825: }
                   11826: 
                   11827: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  11828: sub parse_dns_checksums_tab {
1.1210    raeburn  11829:     my ($lines,$hashref) = @_;
1.1264    raeburn  11830:     my $lonhost = $perlvar{'lonHostID'};
                   11831:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  11832:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  11833:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   11834:     my $webconfdir = '/etc/httpd/conf';
                   11835:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   11836:         $webconfdir = '/etc/apache2';
                   11837:     } elsif ($distro =~ /^sles(\d+)$/) {
                   11838:         if ($1 >= 10) {
                   11839:             $webconfdir = '/etc/apache2';
                   11840:         }
                   11841:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   11842:         if ($1 >= 10.0) {
                   11843:             $webconfdir = '/etc/apache2';
                   11844:         }
                   11845:     }
1.1210    raeburn  11846:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11847:     my (%chksum,%revnum);
                   11848:     if (ref($lines) eq 'ARRAY') {
                   11849:         chomp(@{$lines});
1.1238    raeburn  11850:         my $version = shift(@{$lines});
                   11851:         if ($version eq $release) {  
1.1210    raeburn  11852:             foreach my $line (@{$lines}) {
1.1238    raeburn  11853:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  11854:                 if ($file =~ m{^/etc/httpd/conf}) {
                   11855:                     if ($webconfdir eq '/etc/apache2') {
                   11856:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   11857:                     }
                   11858:                 }
1.1238    raeburn  11859:                 $chksum{$file} = $shasum;
                   11860:                 $revnum{$file} = $version;
1.1210    raeburn  11861:             }
                   11862:             if (ref($hashref) eq 'HASH') {
                   11863:                 %{$hashref} = (
                   11864:                                 sums     => \%chksum,
                   11865:                                 versions => \%revnum,
                   11866:                               );
                   11867:             }
                   11868:         }
                   11869:     }
1.869     albertel 11870:     return;
1.852     albertel 11871: }
1.1210    raeburn  11872: 
                   11873: sub fetch_dns_checksums {
1.1238    raeburn  11874:     my %checksums;
                   11875:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  11876:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  11877:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11878:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  11879:              \%checksums);
1.1210    raeburn  11880:     return \%checksums;
                   11881: }
                   11882: 
1.327     albertel 11883: # ------------------------------------------------------------ Read domain file
                   11884: {
1.852     albertel 11885:     my $loaded;
1.846     albertel 11886:     my %domain;
                   11887: 
1.852     albertel 11888:     sub parse_domain_tab {
                   11889: 	my ($lines) = @_;
                   11890: 	foreach my $line (@$lines) {
                   11891: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11892: 
1.846     albertel 11893: 	    chomp($line);
1.852     albertel 11894: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11895: 	    my %this_domain;
                   11896: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11897: 			       'lang_def', 'city', 'longi', 'lati',
                   11898: 			       'primary') {
                   11899: 		$this_domain{$field} = shift(@elements);
                   11900: 	    }
                   11901: 	    $domain{$name} = \%this_domain;
1.852     albertel 11902: 	}
                   11903:     }
1.864     albertel 11904: 
                   11905:     sub reset_domain_info {
                   11906: 	undef($loaded);
                   11907: 	undef(%domain);
                   11908:     }
                   11909: 
1.852     albertel 11910:     sub load_domain_tab {
1.869     albertel 11911: 	my ($ignore_cache) = @_;
                   11912: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11913: 	my $fh;
                   11914: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11915: 	    my @lines = <$fh>;
                   11916: 	    &parse_domain_tab(\@lines);
1.448     albertel 11917: 	}
1.852     albertel 11918: 	close($fh);
                   11919: 	$loaded = 1;
1.327     albertel 11920:     }
1.846     albertel 11921: 
                   11922:     sub domain {
1.852     albertel 11923: 	&load_domain_tab() if (!$loaded);
                   11924: 
1.846     albertel 11925: 	my ($name,$what) = @_;
                   11926: 	return if ( !exists($domain{$name}) );
                   11927: 
                   11928: 	if (!$what) {
                   11929: 	    return $domain{$name}{'description'};
                   11930: 	}
                   11931: 	return $domain{$name}{$what};
                   11932:     }
1.974     raeburn  11933: 
                   11934:     sub domain_info {
                   11935:         &load_domain_tab() if (!$loaded);
                   11936:         return %domain;
                   11937:     }
                   11938: 
1.327     albertel 11939: }
                   11940: 
                   11941: 
1.1       albertel 11942: # ------------------------------------------------------------- Read hosts file
                   11943: {
1.838     albertel 11944:     my %hostname;
1.844     albertel 11945:     my %hostdom;
1.845     albertel 11946:     my %libserv;
1.852     albertel 11947:     my $loaded;
1.888     albertel 11948:     my %name_to_host;
1.1074    raeburn  11949:     my %internetdom;
1.1107    raeburn  11950:     my %LC_dns_serv;
1.852     albertel 11951: 
                   11952:     sub parse_hosts_tab {
                   11953: 	my ($file) = @_;
                   11954: 	foreach my $configline (@$file) {
                   11955: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11956:             chomp($configline);
                   11957: 	    if ($configline =~ /^\^/) {
                   11958:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11959:                     $LC_dns_serv{$1} = 1;
                   11960:                 }
                   11961:                 next;
                   11962:             }
1.1074    raeburn  11963: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11964: 	    $name=~s/\s//g;
                   11965: 	    if ($id && $domain && $role && $name) {
                   11966: 		$hostname{$id}=$name;
1.888     albertel 11967: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11968: 		$hostdom{$id}=$domain;
                   11969: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11970:                 if (defined($protocol)) {
                   11971:                     if ($protocol eq 'https') {
                   11972:                         $protocol{$id} = $protocol;
                   11973:                     } else {
                   11974:                         $protocol{$id} = 'http'; 
                   11975:                     }
1.968     raeburn  11976:                 } else {
1.969     raeburn  11977:                     $protocol{$id} = 'http';
1.968     raeburn  11978:                 }
1.1074    raeburn  11979:                 if (defined($intdom)) {
                   11980:                     $internetdom{$id} = $intdom;
                   11981:                 }
1.852     albertel 11982: 	    }
                   11983: 	}
                   11984:     }
1.864     albertel 11985:     
                   11986:     sub reset_hosts_info {
1.897     albertel 11987: 	&purge_remembered();
1.864     albertel 11988: 	&reset_domain_info();
                   11989: 	&reset_hosts_ip_info();
1.892     albertel 11990: 	undef(%name_to_host);
1.864     albertel 11991: 	undef(%hostname);
                   11992: 	undef(%hostdom);
                   11993: 	undef(%libserv);
                   11994: 	undef($loaded);
                   11995:     }
1.1       albertel 11996: 
1.852     albertel 11997:     sub load_hosts_tab {
1.869     albertel 11998: 	my ($ignore_cache) = @_;
                   11999: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 12000: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12001: 	my @config = <$config>;
                   12002: 	&parse_hosts_tab(\@config);
                   12003: 	close($config);
                   12004: 	$loaded=1;
1.1       albertel 12005:     }
1.852     albertel 12006: 
1.838     albertel 12007:     sub hostname {
1.852     albertel 12008: 	&load_hosts_tab() if (!$loaded);
                   12009: 
1.838     albertel 12010: 	my ($lonid) = @_;
                   12011: 	return $hostname{$lonid};
                   12012:     }
1.845     albertel 12013: 
1.838     albertel 12014:     sub all_hostnames {
1.852     albertel 12015: 	&load_hosts_tab() if (!$loaded);
                   12016: 
1.838     albertel 12017: 	return %hostname;
                   12018:     }
1.845     albertel 12019: 
1.888     albertel 12020:     sub all_names {
                   12021: 	&load_hosts_tab() if (!$loaded);
                   12022: 
                   12023: 	return %name_to_host;
                   12024:     }
                   12025: 
1.974     raeburn  12026:     sub all_host_domain {
                   12027:         &load_hosts_tab() if (!$loaded);
                   12028:         return %hostdom;
                   12029:     }
                   12030: 
1.845     albertel 12031:     sub is_library {
1.852     albertel 12032: 	&load_hosts_tab() if (!$loaded);
                   12033: 
1.845     albertel 12034: 	return exists($libserv{$_[0]});
                   12035:     }
                   12036: 
                   12037:     sub all_library {
1.852     albertel 12038: 	&load_hosts_tab() if (!$loaded);
                   12039: 
1.845     albertel 12040: 	return %libserv;
                   12041:     }
                   12042: 
1.1062    droeschl 12043:     sub unique_library {
                   12044: 	#2x reverse removes all hostnames that appear more than once
                   12045:         my %unique = reverse &all_library();
                   12046:         return reverse %unique;
                   12047:     }
                   12048: 
1.841     albertel 12049:     sub get_servers {
1.852     albertel 12050: 	&load_hosts_tab() if (!$loaded);
                   12051: 
1.841     albertel 12052: 	my ($domain,$type) = @_;
                   12053: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12054: 	                                          : %hostname;
                   12055: 	my %result;
1.842     albertel 12056: 	if (ref($domain) eq 'ARRAY') {
                   12057: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12058: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12059: 		    $result{$host} = $hostname;
                   12060: 		}
                   12061: 	    }
                   12062: 	} else {
                   12063: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12064: 		if ($hostdom{$host} eq $domain) {
                   12065: 		    $result{$host} = $hostname;
                   12066: 		}
1.841     albertel 12067: 	    }
                   12068: 	}
                   12069: 	return %result;
                   12070:     }
1.845     albertel 12071: 
1.1062    droeschl 12072:     sub get_unique_servers {
                   12073:         my %unique = reverse &get_servers(@_);
                   12074: 	return reverse %unique;
                   12075:     }
                   12076: 
1.844     albertel 12077:     sub host_domain {
1.852     albertel 12078: 	&load_hosts_tab() if (!$loaded);
                   12079: 
1.844     albertel 12080: 	my ($lonid) = @_;
                   12081: 	return $hostdom{$lonid};
                   12082:     }
                   12083: 
1.841     albertel 12084:     sub all_domains {
1.852     albertel 12085: 	&load_hosts_tab() if (!$loaded);
                   12086: 
1.841     albertel 12087: 	my %seen;
                   12088: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12089: 	return @uniq;
                   12090:     }
1.1074    raeburn  12091: 
                   12092:     sub internet_dom {
                   12093:         &load_hosts_tab() if (!$loaded);
                   12094: 
                   12095:         my ($lonid) = @_;
                   12096:         return $internetdom{$lonid};
                   12097:     }
1.1107    raeburn  12098: 
                   12099:     sub is_LC_dns {
                   12100:         &load_hosts_tab() if (!$loaded);
                   12101: 
                   12102:         my ($hostname) = @_;
                   12103:         return exists($LC_dns_serv{$hostname});
                   12104:     }
                   12105: 
1.1       albertel 12106: }
                   12107: 
1.847     albertel 12108: { 
                   12109:     my %iphost;
1.856     albertel 12110:     my %name_to_ip;
                   12111:     my %lonid_to_ip;
1.869     albertel 12112: 
1.847     albertel 12113:     sub get_hosts_from_ip {
                   12114: 	my ($ip) = @_;
                   12115: 	my %iphosts = &get_iphost();
                   12116: 	if (ref($iphosts{$ip})) {
                   12117: 	    return @{$iphosts{$ip}};
                   12118: 	}
                   12119: 	return;
1.839     albertel 12120:     }
1.864     albertel 12121:     
                   12122:     sub reset_hosts_ip_info {
                   12123: 	undef(%iphost);
                   12124: 	undef(%name_to_ip);
                   12125: 	undef(%lonid_to_ip);
                   12126:     }
1.856     albertel 12127: 
                   12128:     sub get_host_ip {
                   12129: 	my ($lonid) = @_;
                   12130: 	if (exists($lonid_to_ip{$lonid})) {
                   12131: 	    return $lonid_to_ip{$lonid};
                   12132: 	}
                   12133: 	my $name=&hostname($lonid);
                   12134:    	my $ip = gethostbyname($name);
                   12135: 	return if (!$ip || length($ip) ne 4);
                   12136: 	$ip=inet_ntoa($ip);
                   12137: 	$name_to_ip{$name}   = $ip;
                   12138: 	$lonid_to_ip{$lonid} = $ip;
                   12139: 	return $ip;
                   12140:     }
1.847     albertel 12141:     
                   12142:     sub get_iphost {
1.869     albertel 12143: 	my ($ignore_cache) = @_;
1.894     albertel 12144: 
1.869     albertel 12145: 	if (!$ignore_cache) {
                   12146: 	    if (%iphost) {
                   12147: 		return %iphost;
                   12148: 	    }
                   12149: 	    my ($ip_info,$cached)=
                   12150: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12151: 	    if ($cached) {
                   12152: 		%iphost      = %{$ip_info->[0]};
                   12153: 		%name_to_ip  = %{$ip_info->[1]};
                   12154: 		%lonid_to_ip = %{$ip_info->[2]};
                   12155: 		return %iphost;
                   12156: 	    }
                   12157: 	}
1.894     albertel 12158: 
                   12159: 	# get yesterday's info for fallback
                   12160: 	my %old_name_to_ip;
                   12161: 	my ($ip_info,$cached)=
                   12162: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12163: 	if ($cached) {
                   12164: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12165: 	}
                   12166: 
1.888     albertel 12167: 	my %name_to_host = &all_names();
                   12168: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12169: 	    my $ip;
                   12170: 	    if (!exists($name_to_ip{$name})) {
                   12171: 		$ip = gethostbyname($name);
                   12172: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12173: 		    if (defined($old_name_to_ip{$name})) {
                   12174: 			$ip = $old_name_to_ip{$name};
                   12175: 			&logthis("Can't find $name defaulting to old $ip");
                   12176: 		    } else {
                   12177: 			&logthis("Name $name no IP found");
                   12178: 			next;
                   12179: 		    }
                   12180: 		} else {
                   12181: 		    $ip=inet_ntoa($ip);
1.847     albertel 12182: 		}
                   12183: 		$name_to_ip{$name} = $ip;
                   12184: 	    } else {
                   12185: 		$ip = $name_to_ip{$name};
1.653     albertel 12186: 	    }
1.888     albertel 12187: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12188: 		$lonid_to_ip{$id} = $ip;
                   12189: 	    }
                   12190: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12191: 	}
1.1219    raeburn  12192: 	&do_cache_new('iphost','iphost',
                   12193: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12194: 		      48*60*60);
1.869     albertel 12195: 
1.847     albertel 12196: 	return %iphost;
1.598     albertel 12197:     }
                   12198: 
1.992     raeburn  12199:     #
                   12200:     #  Given a DNS returns the loncapa host name for that DNS 
                   12201:     # 
                   12202:     sub host_from_dns {
                   12203:         my ($dns) = @_;
                   12204:         my @hosts;
                   12205:         my $ip;
                   12206: 
1.993     raeburn  12207:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12208:             $ip = $name_to_ip{$dns};
                   12209:         }
                   12210:         if (!$ip) {
                   12211:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12212:             if (length($ip) == 4) { 
                   12213: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12214:             }
                   12215:         }
                   12216:         if ($ip) {
                   12217: 	    @hosts = get_hosts_from_ip($ip);
                   12218: 	    return $hosts[0];
                   12219:         }
                   12220:         return undef;
1.986     foxr     12221:     }
1.992     raeburn  12222: 
1.1074    raeburn  12223:     sub get_internet_names {
                   12224:         my ($lonid) = @_;
                   12225:         return if ($lonid eq '');
                   12226:         my ($idnref,$cached)=
                   12227:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12228:         if ($cached) {
                   12229:             return $idnref;
                   12230:         }
                   12231:         my $ip = &get_host_ip($lonid);
                   12232:         my @hosts = &get_hosts_from_ip($ip);
                   12233:         my %iphost = &get_iphost();
                   12234:         my (@idns,%seen);
                   12235:         foreach my $id (@hosts) {
                   12236:             my $dom = &host_domain($id);
                   12237:             my $prim_id = &domain($dom,'primary');
                   12238:             my $prim_ip = &get_host_ip($prim_id);
                   12239:             next if ($seen{$prim_ip});
                   12240:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12241:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12242:                     my $intdom = &internet_dom($id);
                   12243:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12244:                         push(@idns,$intdom);
                   12245:                     }
                   12246:                 }
                   12247:             }
                   12248:             $seen{$prim_ip} = 1;
                   12249:         }
1.1219    raeburn  12250:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12251:     }
                   12252: 
1.986     foxr     12253: }
                   12254: 
1.1079    raeburn  12255: sub all_loncaparevs {
1.1249    raeburn  12256:     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  12257: }
                   12258: 
1.1227    raeburn  12259: # ---------------------------------------------------------- Read loncaparev table
                   12260: {
                   12261:     sub load_loncaparevs { 
                   12262:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12263:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12264:                 while (my $configline=<$config>) {
                   12265:                     chomp($configline);
                   12266:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12267:                     $loncaparevs{$hostid}=$loncaparev;
                   12268:                 }
                   12269:                 close($config);
                   12270:             }
                   12271:         }
                   12272:     }
                   12273: }
                   12274: 
                   12275: # ---------------------------------------------------------- Read serverhostID table
                   12276: {
                   12277:     sub load_serverhomeIDs {
                   12278:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12279:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12280:                 while (my $configline=<$config>) {
                   12281:                     chomp($configline);
                   12282:                     my ($name,$id)=split(/:/,$configline);
                   12283:                     $serverhomeIDs{$name}=$id;
                   12284:                 }
                   12285:                 close($config);
                   12286:             }
                   12287:         }
                   12288:     }
                   12289: }
                   12290: 
                   12291: 
1.862     albertel 12292: BEGIN {
                   12293: 
                   12294: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12295:     unless ($readit) {
                   12296: {
                   12297:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12298:     %perlvar = (%perlvar,%{$configvars});
                   12299: }
                   12300: 
                   12301: 
1.1       albertel 12302: # ------------------------------------------------------ Read spare server file
                   12303: {
1.448     albertel 12304:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12305: 
                   12306:     while (my $configline=<$config>) {
                   12307:        chomp($configline);
1.284     matthew  12308:        if ($configline) {
1.784     albertel 12309: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12310: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12311: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12312:        }
                   12313:     }
1.448     albertel 12314:     close($config);
1.1       albertel 12315: }
1.11      www      12316: # ------------------------------------------------------------ Read permissions
                   12317: {
1.448     albertel 12318:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12319: 
                   12320:     while (my $configline=<$config>) {
1.448     albertel 12321: 	chomp($configline);
                   12322: 	if ($configline) {
                   12323: 	    my ($role,$perm)=split(/ /,$configline);
                   12324: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12325: 	}
1.11      www      12326:     }
1.448     albertel 12327:     close($config);
1.11      www      12328: }
                   12329: 
                   12330: # -------------------------------------------- Read plain texts for permissions
                   12331: {
1.448     albertel 12332:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12333: 
                   12334:     while (my $configline=<$config>) {
1.448     albertel 12335: 	chomp($configline);
                   12336: 	if ($configline) {
1.742     raeburn  12337: 	    my ($short,@plain)=split(/:/,$configline);
                   12338:             %{$prp{$short}} = ();
                   12339: 	    if (@plain > 0) {
                   12340:                 $prp{$short}{'std'} = $plain[0];
                   12341:                 for (my $i=1; $i<@plain; $i++) {
                   12342:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12343:                 }
                   12344:             }
1.448     albertel 12345: 	}
1.135     www      12346:     }
1.448     albertel 12347:     close($config);
1.135     www      12348: }
                   12349: 
                   12350: # ---------------------------------------------------------- Read package table
                   12351: {
1.448     albertel 12352:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12353: 
                   12354:     while (my $configline=<$config>) {
1.483     albertel 12355: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12356: 	chomp($configline);
                   12357: 	my ($short,$plain)=split(/:/,$configline);
                   12358: 	my ($pack,$name)=split(/\&/,$short);
                   12359: 	if ($plain ne '') {
                   12360: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12361: 	    $packagetab{$short}=$plain; 
                   12362: 	}
1.11      www      12363:     }
1.448     albertel 12364:     close($config);
1.329     matthew  12365: }
                   12366: 
1.1073    raeburn  12367: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  12368: 
                   12369: &load_loncaparevs();
1.1073    raeburn  12370: 
1.1074    raeburn  12371: # ---------------------------------------------------------- Read serverhostID table
                   12372: 
1.1227    raeburn  12373: &load_serverhomeIDs();
                   12374: 
                   12375: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12376: {
                   12377:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12378:     if (-e $file) {
                   12379:         my $parser = HTML::LCParser->new($file);
                   12380:         while (my $token = $parser->get_token()) {
                   12381:             if ($token->[0] eq 'S') {
                   12382:                 my $item = $token->[1];
                   12383:                 my $name = $token->[2]{'name'};
                   12384:                 my $value = $token->[2]{'value'};
                   12385:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12386:                     my $release = $parser->get_text();
                   12387:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12388:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12389:                 }
                   12390:             }
                   12391:         }
                   12392:     }
1.1073    raeburn  12393: }
                   12394: 
1.1138    raeburn  12395: # ---------------------------------------------------------- Read managers table
                   12396: {
                   12397:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12398:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12399:             while (my $configline=<$config>) {
                   12400:                 chomp($configline);
                   12401:                 next if ($configline =~ /^\#/);
                   12402:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12403:                     $managerstab{$configline} = 1;
                   12404:                 }
                   12405:             }
                   12406:             close($config);
                   12407:         }
                   12408:     }
                   12409: }
                   12410: 
1.329     matthew  12411: # ------------- set up temporary directory
                   12412: {
1.1117    foxr     12413:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12414: 
1.11      www      12415: }
                   12416: 
1.794     albertel 12417: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12418: 				'compress_threshold'=> 20_000,
                   12419:  			        });
1.185     www      12420: 
1.281     www      12421: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12422: $dumpcount=0;
1.958     www      12423: $locknum=0;
1.22      www      12424: 
1.163     harris41 12425: &logtouch();
1.672     albertel 12426: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12427: $readit=1;
1.564     albertel 12428:     {
                   12429: 	use integer;
                   12430: 	my $test=(2**32)+1;
1.568     albertel 12431: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12432: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12433:     }
1.195     www      12434: }
1.1       albertel 12435: }
1.179     www      12436: 
1.1       albertel 12437: 1;
1.191     harris41 12438: __END__
                   12439: 
1.243     albertel 12440: =pod
                   12441: 
1.191     harris41 12442: =head1 NAME
                   12443: 
1.243     albertel 12444: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12445: 
                   12446: =head1 SYNOPSIS
                   12447: 
1.243     albertel 12448: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12449: 
                   12450:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12451: 
1.243     albertel 12452: Common parameters:
                   12453: 
                   12454: =over 4
                   12455: 
                   12456: =item *
                   12457: 
                   12458: $uname : an internal username (if $cname expecting a course Id specifically)
                   12459: 
                   12460: =item *
                   12461: 
                   12462: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12463: 
                   12464: =item *
                   12465: 
                   12466: $symb : a resource instance identifier
                   12467: 
                   12468: =item *
                   12469: 
                   12470: $namespace : the name of a .db file that contains the data needed or
                   12471: being set.
                   12472: 
                   12473: =back
                   12474: 
1.394     bowersj2 12475: =head1 OVERVIEW
1.191     harris41 12476: 
1.394     bowersj2 12477: lonnet provides subroutines which interact with the
                   12478: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12479: about classes, users, and resources.
1.243     albertel 12480: 
                   12481: For many of these objects you can also use this to store data about
                   12482: them or modify them in various ways.
1.191     harris41 12483: 
1.394     bowersj2 12484: =head2 Symbs
1.191     harris41 12485: 
1.394     bowersj2 12486: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12487: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12488: map, the resource number of the resource in the map, and the URL of
                   12489: the resource itself. The latter is somewhat redundant, but might help
                   12490: if maps change.
                   12491: 
                   12492: An example is
                   12493: 
                   12494:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12495: 
                   12496: The respective map entry is
                   12497: 
                   12498:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12499:   title="Problem 2">
                   12500:  </resource>
                   12501: 
                   12502: Symbs are used by the random number generator, as well as to store and
                   12503: restore data specific to a certain instance of for example a problem.
                   12504: 
                   12505: =head2 Storing And Retrieving Data
                   12506: 
                   12507: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12508: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12509: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12510: is is the non-critical message twin of cstore. These functions are for
                   12511: handlers to store a perl hash to a user's permanent data space in an
                   12512: easy manner, and to retrieve it again on another call. It is expected
                   12513: that a handler would use this once at the beginning to retrieve data,
                   12514: and then again once at the end to send only the new data back.
                   12515: 
                   12516: The data is stored in the user's data directory on the user's
                   12517: homeserver under the ID of the course.
                   12518: 
                   12519: The hash that is returned by restore will have all of the previous
                   12520: value for all of the elements of the hash.
                   12521: 
                   12522: Example:
                   12523: 
                   12524:  #creating a hash
                   12525:  my %hash;
                   12526:  $hash{'foo'}='bar';
                   12527: 
                   12528:  #storing it
                   12529:  &Apache::lonnet::cstore(\%hash);
                   12530: 
                   12531:  #changing a value
                   12532:  $hash{'foo'}='notbar';
                   12533: 
                   12534:  #adding a new value
                   12535:  $hash{'bar'}='foo';
                   12536:  &Apache::lonnet::cstore(\%hash);
                   12537: 
                   12538:  #retrieving the hash
                   12539:  my %history=&Apache::lonnet::restore();
                   12540: 
                   12541:  #print the hash
                   12542:  foreach my $key (sort(keys(%history))) {
                   12543:    print("\%history{$key} = $history{$key}");
                   12544:  }
                   12545: 
                   12546: Will print out:
1.191     harris41 12547: 
1.394     bowersj2 12548:  %history{1:foo} = bar
                   12549:  %history{1:keys} = foo:timestamp
                   12550:  %history{1:timestamp} = 990455579
                   12551:  %history{2:bar} = foo
                   12552:  %history{2:foo} = notbar
                   12553:  %history{2:keys} = foo:bar:timestamp
                   12554:  %history{2:timestamp} = 990455580
                   12555:  %history{bar} = foo
                   12556:  %history{foo} = notbar
                   12557:  %history{timestamp} = 990455580
                   12558:  %history{version} = 2
                   12559: 
                   12560: Note that the special hash entries C<keys>, C<version> and
                   12561: C<timestamp> were added to the hash. C<version> will be equal to the
                   12562: total number of versions of the data that have been stored. The
                   12563: C<timestamp> attribute will be the UNIX time the hash was
                   12564: stored. C<keys> is available in every historical section to list which
                   12565: keys were added or changed at a specific historical revision of a
                   12566: hash.
                   12567: 
                   12568: B<Warning>: do not store the hash that restore returns directly. This
                   12569: will cause a mess since it will restore the historical keys as if the
                   12570: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12571: 
1.394     bowersj2 12572: Calling convention:
1.191     harris41 12573: 
1.1225    raeburn  12574:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
                   12575:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191     harris41 12576: 
1.394     bowersj2 12577: For more detailed information, see lonnet specific documentation.
1.191     harris41 12578: 
1.394     bowersj2 12579: =head1 RETURN MESSAGES
1.191     harris41 12580: 
1.394     bowersj2 12581: =over 4
1.191     harris41 12582: 
1.394     bowersj2 12583: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12584: 
1.394     bowersj2 12585: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12586: when the connection is brought back up
1.191     harris41 12587: 
1.394     bowersj2 12588: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12589: for later delivery
1.191     harris41 12590: 
1.967     bisitz   12591: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12592: 
1.394     bowersj2 12593: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12594: that was requested
1.191     harris41 12595: 
1.243     albertel 12596: =back
1.191     harris41 12597: 
1.243     albertel 12598: =head1 PUBLIC SUBROUTINES
1.191     harris41 12599: 
1.243     albertel 12600: =head2 Session Environment Functions
1.191     harris41 12601: 
1.243     albertel 12602: =over 4
1.191     harris41 12603: 
1.394     bowersj2 12604: =item * 
                   12605: X<appenv()>
1.949     raeburn  12606: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12607: the user envirnoment file, and will be restored for each access this
1.620     albertel 12608: user makes during this session, also modifies the %env for the current
1.949     raeburn  12609: process. Optional rolesarrayref - if defined contains a reference to an array
                   12610: of roles which are exempt from the restriction on modifying user.role entries 
                   12611: in the user's environment.db and in %env.    
1.191     harris41 12612: 
                   12613: =item *
1.394     bowersj2 12614: X<delenv()>
1.987     raeburn  12615: B<delenv($delthis,$regexp)>: removes all items from the session
                   12616: environment file that begin with $delthis. If the 
                   12617: optional second arg - $regexp - is true, $delthis is treated as a 
                   12618: regular expression, otherwise \Q$delthis\E is used. 
                   12619: The values are also deleted from the current processes %env.
1.191     harris41 12620: 
1.795     albertel 12621: =item * get_env_multiple($name) 
                   12622: 
                   12623: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12624: values may be defined and end up as an array ref.
                   12625: 
                   12626: returns an array of values
                   12627: 
1.243     albertel 12628: =back
                   12629: 
                   12630: =head2 User Information
1.191     harris41 12631: 
1.243     albertel 12632: =over 4
1.191     harris41 12633: 
                   12634: =item *
1.394     bowersj2 12635: X<queryauthenticate()>
                   12636: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12637: authentication scheme
                   12638: 
                   12639: =item *
1.394     bowersj2 12640: X<authenticate()>
1.1073    raeburn  12641: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12642: authenticate user from domain's lib servers (first use the current
                   12643: one). C<$upass> should be the users password.
1.1073    raeburn  12644: $checkdefauth is optional (value is 1 if a check should be made to
                   12645:    authenticate user using default authentication method, and allow
                   12646:    account creation if username does not have account in the domain).
                   12647: $clientcancheckhost is optional (value is 1 if checking whether the
                   12648:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12649: 
                   12650: =item *
1.394     bowersj2 12651: X<homeserver()>
                   12652: B<homeserver($uname,$udom)>: find the server which has
                   12653: the user's directory and files (there must be only one), this caches
                   12654: the answer, and also caches if there is a borken connection.
1.191     harris41 12655: 
                   12656: =item *
1.394     bowersj2 12657: X<idget()>
                   12658: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12659: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12660: username, and only 1 username per ID in a specific domain) (returns
                   12661: hash: id=>name,id=>name)
1.191     harris41 12662: 
                   12663: =item *
1.394     bowersj2 12664: X<idrget()>
                   12665: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12666: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12667: 
                   12668: =item *
1.394     bowersj2 12669: X<idput()>
                   12670: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12671: 
                   12672: =item *
1.394     bowersj2 12673: X<rolesinit()>
1.1169    droeschl 12674: B<rolesinit($udom,$username)>: get user privileges.
                   12675: returns user role, first access and timer interval hashes
1.243     albertel 12676: 
                   12677: =item *
1.1171    droeschl 12678: X<privileged()>
                   12679: B<privileged($username,$domain)>: returns a true if user has a
                   12680: privileged and active role (i.e. su or dc), false otherwise.
                   12681: 
                   12682: =item *
1.551     albertel 12683: X<getsection()>
                   12684: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12685: course $cname, return section name/number or '' for "not in course"
                   12686: and '-1' for "no section"
                   12687: 
                   12688: =item *
1.394     bowersj2 12689: X<userenvironment()>
                   12690: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12691: passed in @what from the requested user's environment, returns a hash
                   12692: 
1.858     raeburn  12693: =item * 
                   12694: X<userlog_query()>
1.859     albertel 12695: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12696: activity.log file. %filters defines filters applied when parsing the
                   12697: log file. These can be start or end timestamps, or the type of action
                   12698: - log to look for Login or Logout events, check for Checkin or
                   12699: Checkout, role for role selection. The response is in the form
                   12700: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12701: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12702: 
1.243     albertel 12703: =back
                   12704: 
                   12705: =head2 User Roles
                   12706: 
                   12707: =over 4
                   12708: 
                   12709: =item *
                   12710: 
1.810     raeburn  12711: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12712:  F: full access
                   12713:  U,I,K: authentication modes (cxx only)
                   12714:  '': forbidden
                   12715:  1: user needs to choose course
                   12716:  2: browse allowed
1.766     albertel 12717:  A: passphrase authentication needed
1.243     albertel 12718: 
                   12719: =item *
                   12720: 
1.1192    raeburn  12721: constructaccess($url,$setpriv) : check for access to construction space URL
                   12722: 
                   12723: See if the owner domain and name in the URL match those in the
                   12724: expected environment.  If so, return three element list
                   12725: ($ownername,$ownerdomain,$ownerhome).
                   12726: 
                   12727: Otherwise return the null string.
                   12728: 
                   12729: If second argument 'setpriv' is true, it assigns the privileges,
                   12730: and returns the same three element list, unless the owner has
                   12731: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12732: in which case the null string is returned.
                   12733: 
                   12734: =item *
                   12735: 
1.243     albertel 12736: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12737: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12738: and course level
                   12739: 
                   12740: =item *
                   12741: 
1.988     raeburn  12742: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12743: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12744: $type is Course (default) or Community.
1.988     raeburn  12745: If $forcedefault evaluates to true, text returned will be default 
                   12746: text for $type. Otherwise, if this is a course, the text returned 
                   12747: will be a custom name for the role (if defined in the course's 
                   12748: environment).  If no custom name is defined the default is returned.
                   12749:    
1.832     raeburn  12750: =item *
                   12751: 
1.1219    raeburn  12752: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12753: All arguments are optional. Returns a hash of a roles, either for
                   12754: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12755: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12756: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12757: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12758: For each key, value is set to colon-separated start and end times for
                   12759: the role.  If no username and domain are specified, will default to
1.934     raeburn  12760: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12761: of role statuses (active, future or previous), roles 
                   12762: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12763: to restrict the list of roles reported. If no array ref is 
                   12764: provided for types, will default to return only active roles.
1.834     albertel 12765: 
1.1195    raeburn  12766: =item *
                   12767: 
                   12768: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  12769: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   12770: 
                   12771: Additional optional arguments are: $type (if role checking is to be restricted 
                   12772: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  12773: available roles) or future (roles available in the future), and
                   12774: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  12775: have active Domain Coordinator role in course's domain or in additional
                   12776: domains (specified in 'Domains to check for privileged users' in course
                   12777: environment -- set via:  Course Settings -> Classlists and staff listing).
                   12778: 
                   12779: =item *
                   12780: 
                   12781: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   12782: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   12783: $possdomains and $possroles are optional array refs -- to domains to check and
                   12784: roles to check.  If $possdomains is not specified, a dump will be done of the
                   12785: users' roles.db to check for a dc or su role in any domain. This can be
                   12786: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   12787: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   12788: this then allows &privileged_by_domain() to be used, which caches the identity
                   12789: of privileged users, eliminating the need for repeated calls to &dump().
                   12790: 
                   12791: =item *
                   12792: 
                   12793: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   12794: where the outer hash keys are domains specified in the $possdomains array ref,
                   12795: next inner hash keys are privileged roles specified in the $roles array ref,
                   12796: and the innermost hash contains key = value pairs for username:domain = end:start
                   12797: for active or future "privileged" users with that role in that domain. To avoid
                   12798: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   12799: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  12800: 
1.243     albertel 12801: =back
                   12802: 
                   12803: =head2 User Modification
                   12804: 
                   12805: =over 4
                   12806: 
                   12807: =item *
                   12808: 
1.957     raeburn  12809: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12810: user for the level given by URL.  Optional start and end dates (leave empty
                   12811: string or zero for "no date")
1.191     harris41 12812: 
                   12813: =item *
                   12814: 
1.243     albertel 12815: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12816: change a users, password, possible return values are: ok,
                   12817: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12818: refused
1.191     harris41 12819: 
                   12820: =item *
                   12821: 
1.243     albertel 12822: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12823: 
                   12824: =item *
                   12825: 
1.1058    raeburn  12826: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12827:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12828: 
                   12829: will update user information (firstname,middlename,lastname,generation,
                   12830: permanentemail), and if forceid is true, student/employee ID also.
                   12831: A user's institutional affiliation(s) can also be updated.
                   12832: User information fields will not be overwritten with empty entries 
                   12833: unless the field is included in the $candelete array reference.
                   12834: This array is included when a single user is modified via "Manage Users",
                   12835: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12836: 
                   12837: =item *
                   12838: 
1.286     matthew  12839: modifystudent
                   12840: 
1.957     raeburn  12841: modify a student's enrollment and identification information.
1.1235    raeburn  12842: The course id is resolved based on the current user's environment.  
                   12843: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  12844: associated with a course.
                   12845: 
1.297     matthew  12846: This call is essentially a wrapper for lonnet::modifyuser and
                   12847: lonnet::modify_student_enrollment
1.286     matthew  12848: 
                   12849: Inputs: 
                   12850: 
                   12851: =over 4
                   12852: 
1.957     raeburn  12853: =item B<$udom> Student's loncapa domain
1.286     matthew  12854: 
1.957     raeburn  12855: =item B<$uname> Student's loncapa login name
1.286     matthew  12856: 
1.964     bisitz   12857: =item B<$uid> Student/Employee ID
1.286     matthew  12858: 
1.957     raeburn  12859: =item B<$umode> Student's authentication mode
1.286     matthew  12860: 
1.957     raeburn  12861: =item B<$upass> Student's password
1.286     matthew  12862: 
1.957     raeburn  12863: =item B<$first> Student's first name
1.286     matthew  12864: 
1.957     raeburn  12865: =item B<$middle> Student's middle name
1.286     matthew  12866: 
1.957     raeburn  12867: =item B<$last> Student's last name
1.286     matthew  12868: 
1.957     raeburn  12869: =item B<$gene> Student's generation
1.286     matthew  12870: 
1.957     raeburn  12871: =item B<$usec> Student's section in course
1.286     matthew  12872: 
                   12873: =item B<$end> Unix time of the roles expiration
                   12874: 
                   12875: =item B<$start> Unix time of the roles start date
                   12876: 
                   12877: =item B<$forceid> If defined, allow $uid to be changed
                   12878: 
                   12879: =item B<$desiredhome> server to use as home server for student
                   12880: 
1.957     raeburn  12881: =item B<$email> Student's permanent e-mail address
                   12882: 
                   12883: =item B<$type> Type of enrollment (auto or manual)
                   12884: 
1.963     raeburn  12885: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12886: 
                   12887: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12888: 
1.963     raeburn  12889: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12890: 
1.963     raeburn  12891: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12892: 
1.1216    raeburn  12893: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12894: 
                   12895: =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  12896: 
1.286     matthew  12897: =back
1.297     matthew  12898: 
                   12899: =item *
                   12900: 
                   12901: modify_student_enrollment
                   12902: 
1.1235    raeburn  12903: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  12904: 'role.request.course' must be defined for this function to proceed.
                   12905: 
                   12906: Inputs:
                   12907: 
                   12908: =over 4
                   12909: 
1.1235    raeburn  12910: =item $udom, student's domain
1.297     matthew  12911: 
1.1235    raeburn  12912: =item $uname, student's name
1.297     matthew  12913: 
1.1235    raeburn  12914: =item $uid, student's user id
1.297     matthew  12915: 
1.1235    raeburn  12916: =item $first, student's first name
1.297     matthew  12917: 
                   12918: =item $middle
                   12919: 
                   12920: =item $last
                   12921: 
                   12922: =item $gene
                   12923: 
                   12924: =item $usec
                   12925: 
                   12926: =item $end
                   12927: 
                   12928: =item $start
                   12929: 
1.957     raeburn  12930: =item $type
                   12931: 
                   12932: =item $locktype
                   12933: 
                   12934: =item $cid
                   12935: 
                   12936: =item $selfenroll
                   12937: 
                   12938: =item $context
                   12939: 
1.1216    raeburn  12940: =item $credits, number of credits student will earn from this class
                   12941: 
1.297     matthew  12942: =back
                   12943: 
1.191     harris41 12944: 
                   12945: =item *
                   12946: 
1.243     albertel 12947: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12948: custom role; give a custom role to a user for the level given by URL.  Specify
                   12949: name and domain of role author, and role name
1.191     harris41 12950: 
                   12951: =item *
                   12952: 
1.243     albertel 12953: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12954: 
                   12955: =item *
                   12956: 
1.243     albertel 12957: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12958: 
                   12959: =back
                   12960: 
                   12961: =head2 Course Infomation
                   12962: 
                   12963: =over 4
1.191     harris41 12964: 
                   12965: =item *
                   12966: 
1.1118    foxr     12967: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12968: specified course id, including all environment settings for the
                   12969: course, the description of the course will be in the hash under the
                   12970: key 'description'
1.191     harris41 12971: 
1.1118    foxr     12972: $options is an optional parameter that if supplied is a hash reference that controls
                   12973: what how this function works.  It has the following key/values:
                   12974: 
                   12975: =over 4
                   12976: 
                   12977: =item freshen_cache
                   12978: 
                   12979: If defined, and the environment cache for the course is valid, it is 
                   12980: returned in the returned hash.
                   12981: 
                   12982: =item one_time
                   12983: 
                   12984: If defined, the last cache time is set to _now_
                   12985: 
                   12986: =item user
                   12987: 
                   12988: If defined, the supplied username is used instead of the current user.
                   12989: 
                   12990: 
                   12991: =back
                   12992: 
1.191     harris41 12993: =item *
                   12994: 
1.624     albertel 12995: resdata($name,$domain,$type,@which) : request for current parameter
                   12996: setting for a specific $type, where $type is either 'course' or 'user',
                   12997: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  12998: answers for 10 minutes.
1.243     albertel 12999: 
1.877     foxr     13000: =item *
                   13001: 
                   13002: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13003: data base, returning a hash that is keyed by the resource name and has
                   13004: values that are the resource value.  I believe that the timestamps and
                   13005: versions are also returned.
                   13006: 
1.1236    raeburn  13007: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13008: supplemental content area. This routine caches the number of files for 
                   13009: 10 minutes.
                   13010: 
1.243     albertel 13011: =back
                   13012: 
                   13013: =head2 Course Modification
                   13014: 
                   13015: =over 4
1.191     harris41 13016: 
                   13017: =item *
                   13018: 
1.243     albertel 13019: writecoursepref($courseid,%prefs) : write preferences (environment
                   13020: database) for a course
1.191     harris41 13021: 
                   13022: =item *
                   13023: 
1.1011    raeburn  13024: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13025: 
                   13026: =item *
                   13027: 
1.1038    raeburn  13028: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13029: 
1.1167    droeschl 13030: =item *
                   13031: 
                   13032: is_course($courseid), is_course($cdom, $cnum)
                   13033: 
                   13034: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13035: two component version $cdom, $cnum. It checks if the specified course exists.
                   13036: 
                   13037: Returns:
                   13038:     undef if the course doesn't exist, otherwise
                   13039:     in scalar context the combined courseid.
                   13040:     in list context the two components of the course identifier, domain and 
                   13041:     courseid.    
                   13042: 
1.243     albertel 13043: =back
                   13044: 
                   13045: =head2 Resource Subroutines
                   13046: 
                   13047: =over 4
1.191     harris41 13048: 
                   13049: =item *
                   13050: 
1.243     albertel 13051: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13052: 
                   13053: =item *
                   13054: 
1.243     albertel 13055: repcopy($filename) : subscribes to the requested file, and attempts to
                   13056: replicate from the owning library server, Might return
1.607     raeburn  13057: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13058: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13059: resource. Expects the local filesystem pathname
                   13060: (/home/httpd/html/res/....)
                   13061: 
                   13062: =back
                   13063: 
                   13064: =head2 Resource Information
                   13065: 
                   13066: =over 4
1.191     harris41 13067: 
                   13068: =item *
                   13069: 
1.1228    raeburn  13070: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13071: and returns the value of a variety of different possible values,
                   13072: $varname should be a request string, and the other parameters can be
                   13073: used to specify who and what one is asking about. Ordinarily, $cid 
                   13074: does not need to be specified, as it is retrived from 
                   13075: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13076: within lonuserstate::loadmap() when initializing a course, before
                   13077: $env{'request.course.id'} has been set, so it needs to be provided
                   13078: in that one case.
1.243     albertel 13079: 
                   13080: Possible values for $varname are environment.lastname (or other item
                   13081: from the envirnment hash), user.name (or someother aspect about the
                   13082: user), resource.0.maxtries (or some other part and parameter of a
                   13083: resource)
1.204     albertel 13084: 
                   13085: =item *
                   13086: 
1.243     albertel 13087: directcondval($number) : get current value of a condition; reads from a state
                   13088: string
1.204     albertel 13089: 
                   13090: =item *
                   13091: 
1.243     albertel 13092: condval($condidx) : value of condition index based on state
1.204     albertel 13093: 
                   13094: =item *
                   13095: 
1.243     albertel 13096: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13097: resource's metadata, $what should be either a specific key, or either
                   13098: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13099: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13100: 
                   13101: this function automatically caches all requests
1.191     harris41 13102: 
                   13103: =item *
                   13104: 
1.243     albertel 13105: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13106: network of library servers; returns file handle of where SQL and regex results
                   13107: will be stored for query
1.191     harris41 13108: 
                   13109: =item *
                   13110: 
1.243     albertel 13111: symbread($filename) : return symbolic list entry (filename argument optional);
                   13112: returns the data handle
1.191     harris41 13113: 
                   13114: =item *
                   13115: 
1.1190    raeburn  13116: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   13117: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13118: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  13119: on failure, user must be in a course, as it assumes the existence of
                   13120: the course initial hash, and uses $env('request.course.id'}.  The third
                   13121: arg is an optional reference to a scalar.  If this arg is passed in the 
                   13122: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13123: encrypted; otherwise it will be null.  
1.191     harris41 13124: 
                   13125: =item *
                   13126: 
1.243     albertel 13127: symbclean($symb) : removes versions numbers from a symb, returns the
                   13128: cleaned symb
1.191     harris41 13129: 
                   13130: =item *
                   13131: 
1.243     albertel 13132: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13133: course map, user must be in a course for it to work.
1.191     harris41 13134: 
                   13135: =item *
                   13136: 
1.243     albertel 13137: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13138: 
                   13139: =item *
                   13140: 
1.243     albertel 13141: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13142: a random seed, all arguments are optional, if they aren't sent it uses the
                   13143: environment to derive them. Note: if symb isn't sent and it can't get one
                   13144: from &symbread it will use the current time as its return value
1.191     harris41 13145: 
                   13146: =item *
                   13147: 
1.243     albertel 13148: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13149: unfakeable, receipt
1.191     harris41 13150: 
                   13151: =item *
                   13152: 
1.620     albertel 13153: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13154: 
                   13155: =item *
                   13156: 
1.243     albertel 13157: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13158: 
                   13159: =item *
                   13160: 
1.243     albertel 13161: 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 13162: 
                   13163: =item *
                   13164: 
1.243     albertel 13165: 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 13166: 
                   13167: =item *
                   13168: 
1.243     albertel 13169: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13170: 
                   13171: =item *
                   13172: 
1.243     albertel 13173: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13174: forcing spreadsheet to reevaluate the resource scores next time.
                   13175: 
1.1195    raeburn  13176: =item * 
                   13177: 
1.1196    raeburn  13178: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13179: when viewing in course context.
1.1195    raeburn  13180: 
1.1196    raeburn  13181:  input: six args -- filename (decluttered), course number, course domain,
                   13182:                     url, symb (if registered) and group (if this is a 
                   13183:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  13184: 
1.1196    raeburn  13185:  output: array of five scalars --
1.1195    raeburn  13186:          $cfile -- url for file editing if editable on current server
                   13187:          $home -- homeserver of resource (i.e., for author if published,
                   13188:                                           or course if uploaded.).
                   13189:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  13190:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   13191:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  13192: 
                   13193: =item *
                   13194: 
                   13195: is_course_upload($file,$cnum,$cdom)
                   13196: 
                   13197: Used in course context to determine if current file was uploaded to 
                   13198: the course (i.e., would be found in /userfiles/docs on the course's 
                   13199: homeserver.
                   13200: 
                   13201:   input: 3 args -- filename (decluttered), course number and course domain.
                   13202:   output: boolean -- 1 if file was uploaded.
                   13203: 
1.243     albertel 13204: =back
                   13205: 
                   13206: =head2 Storing/Retreiving Data
                   13207: 
                   13208: =over 4
1.191     harris41 13209: 
                   13210: =item *
                   13211: 
1.243     albertel 13212: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   13213: for this url; hashref needs to be given and should be a \%hashname; the
                   13214: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 13215: be derived from the env
1.191     harris41 13216: 
                   13217: =item *
                   13218: 
1.243     albertel 13219: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   13220: uses critical subroutine
1.191     harris41 13221: 
                   13222: =item *
                   13223: 
1.243     albertel 13224: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13225: all args are optional
1.191     harris41 13226: 
                   13227: =item *
                   13228: 
1.717     albertel 13229: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13230: dumps the complete (or key matching regexp) namespace into a hash
                   13231: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13232: normally &store()ed into
                   13233: 
                   13234: $range should be either an integer '100' (give me the first 100
                   13235:                                            matching records)
                   13236:               or be  two integers sperated by a - with no spaces
                   13237:                  '30-50' (give me the 30th through the 50th matching
                   13238:                           records)
                   13239: 
                   13240: 
                   13241: =item *
                   13242: 
                   13243: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   13244: replaces a &store() version of data with a replacement set of data
                   13245: for a particular resource in a namespace passed in the $storehash hash 
                   13246: reference
                   13247: 
                   13248: =item *
                   13249: 
1.243     albertel 13250: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13251: works very similar to store/cstore, but all data is stored in a
                   13252: temporary location and can be reset using tmpreset, $storehash should
                   13253: be a hash reference, returns nothing on success
1.191     harris41 13254: 
                   13255: =item *
                   13256: 
1.243     albertel 13257: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13258: similar to restore, but all data is stored in a temporary location and
                   13259: can be reset using tmpreset. Returns a hash of values on success,
                   13260: error string otherwise.
1.191     harris41 13261: 
                   13262: =item *
                   13263: 
1.243     albertel 13264: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13265: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13266: 
                   13267: =item *
                   13268: 
1.243     albertel 13269: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13270: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13271: 
                   13272: =item *
                   13273: 
1.243     albertel 13274: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13275: namesp ($udom and $uname are optional)
1.191     harris41 13276: 
                   13277: =item *
                   13278: 
1.702     albertel 13279: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13280: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13281: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13282: 
1.702     albertel 13283: $range should be either an integer '100' (give me the first 100
                   13284:                                            matching records)
                   13285:               or be  two integers sperated by a - with no spaces
                   13286:                  '30-50' (give me the 30th through the 50th matching
                   13287:                           records)
1.449     matthew  13288: =item *
                   13289: 
                   13290: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13291: $store can be a scalar, an array reference, or if the amount to be 
                   13292: incremented is > 1, a hash reference.
                   13293: 
                   13294: ($udom and $uname are optional)
1.191     harris41 13295: 
                   13296: =item *
                   13297: 
1.243     albertel 13298: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13299: ($udom and $uname are optional)
1.191     harris41 13300: 
                   13301: =item *
                   13302: 
1.243     albertel 13303: cput($namespace,$storehash,$udom,$uname) : critical put
                   13304: ($udom and $uname are optional)
1.191     harris41 13305: 
                   13306: =item *
                   13307: 
1.748     albertel 13308: newput($namespace,$storehash,$udom,$uname) :
                   13309: 
                   13310: Attempts to store the items in the $storehash, but only if they don't
                   13311: currently exist, if this succeeds you can be certain that you have 
                   13312: successfully created a new key value pair in the $namespace db.
                   13313: 
                   13314: 
                   13315: Args:
                   13316:  $namespace: name of database to store values to
                   13317:  $storehash: hashref to store to the db
                   13318:  $udom: (optional) domain of user containing the db
                   13319:  $uname: (optional) name of user caontaining the db
                   13320: 
                   13321: Returns:
                   13322:  'ok' -> succeeded in storing all keys of $storehash
                   13323:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13324:                         least <key> already existed in the db (other
                   13325:                         requested keys may also already exist)
1.967     bisitz   13326:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13327:  'con_lost' -> unable to contact request server
                   13328:  'refused' -> action was not allowed by remote machine
                   13329: 
                   13330: 
                   13331: =item *
                   13332: 
1.243     albertel 13333: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13334: reference filled in from namesp (encrypts the return communication)
                   13335: ($udom and $uname are optional)
1.191     harris41 13336: 
                   13337: =item *
                   13338: 
1.243     albertel 13339: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13340: critical subroutine
                   13341: 
1.806     raeburn  13342: =item *
                   13343: 
1.860     raeburn  13344: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13345: array reference filled in from namespace found in domain level on either
                   13346: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13347: 
                   13348: =item *
                   13349: 
1.860     raeburn  13350: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13351: domain level either on specified domain server ($uhome) or primary domain 
                   13352: server ($udom and $uhome are optional)
1.806     raeburn  13353: 
1.943     raeburn  13354: =item * 
                   13355: 
1.1240    raeburn  13356: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   13357: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13358: the target domain.
                   13359: 
                   13360: May also include additional key => value pairs for the following groups:
                   13361: 
                   13362: =over
                   13363: 
                   13364: =item
                   13365: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13366: 
                   13367: =over
                   13368: 
                   13369: =item defaultquota, authorquota
                   13370: 
                   13371: =back
                   13372: 
                   13373: =item
                   13374: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13375: portfolio for users).
                   13376: 
                   13377: =over
                   13378: 
                   13379: =item
                   13380: aboutme, blog, webdav, portfolio
                   13381: 
                   13382: =back
                   13383: 
                   13384: =item
                   13385: requestcourses: ability to request courses, and how requests are processed.
                   13386: 
                   13387: =over
                   13388: 
                   13389: =item
1.1246    raeburn  13390: official, unofficial, community, textbook
1.1240    raeburn  13391: 
                   13392: =back
                   13393: 
                   13394: =item
                   13395: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13396: 
                   13397: =over
                   13398: 
                   13399: =item
1.1256    raeburn  13400: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  13401: 
                   13402: =back
                   13403: 
                   13404: =item
                   13405: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13406: for course's uploaded content.
                   13407: 
                   13408: =over
                   13409: 
                   13410: =item
1.1246    raeburn  13411: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
                   13412: communityquota, textbookquota
1.1240    raeburn  13413: 
                   13414: =back
                   13415: 
                   13416: =item
                   13417: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13418: on your servers.
                   13419: 
                   13420: =over
                   13421: 
                   13422: =item 
                   13423: remotesessions, hostedsessions
                   13424: 
                   13425: =back
                   13426: 
                   13427: =back
                   13428: 
                   13429: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13430: utility to create a configuration.db file on a domain's primary library server 
                   13431: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13432: -- corresponding values are authentication type (internal, krb4, krb5,
                   13433: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   13434: will be available. Values are retrieved from cache (if current), unless the
                   13435: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13436: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13437: 
                   13438: Typical usage:
1.943     raeburn  13439: 
1.1240    raeburn  13440: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13441: 
1.243     albertel 13442: =back
                   13443: 
                   13444: =head2 Network Status Functions
                   13445: 
                   13446: =over 4
1.191     harris41 13447: 
                   13448: =item *
                   13449: 
1.1137    raeburn  13450: dirlist() : return directory list based on URI (first arg).
                   13451: 
                   13452: Inputs: 1 required, 5 optional.
                   13453: 
                   13454: =over
                   13455: 
                   13456: =item 
                   13457: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13458: 
                   13459: =item
                   13460: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13461: 
                   13462: =item
                   13463: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13464: 
                   13465: =item
                   13466: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13467: 
                   13468: =item
                   13469: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13470: 
                   13471: =item 
                   13472: $alternateRoot - path to prepend in place of path from $uri.
                   13473: 
                   13474: =back
                   13475: 
                   13476: Returns: Array of up to two items.
                   13477: 
                   13478: =over
                   13479: 
                   13480: a reference to an array of files/subdirectories
                   13481: 
                   13482: =over
                   13483: 
                   13484: Each element in the array of files/subdirectories is a & separated list of
                   13485: item name and the result of running stat on the item.  If dirlist was requested
                   13486: for a file instead of a directory, the item name will be ''. For a directory 
                   13487: listing, if the item is a metadata file, the element will end &N&M 
                   13488: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13489: default copyright set (1).  
                   13490: 
                   13491: =back
                   13492: 
                   13493: a scalar containing error condition (if encountered).
                   13494: 
                   13495: =over
                   13496: 
                   13497: =item 
                   13498: no_host (no homeserver identified for $username:$domain).
                   13499: 
                   13500: =item 
                   13501: no_such_host (server contacted for listing not identified as valid host).
                   13502: 
                   13503: =item 
                   13504: con_lost (connection to remote server failed).
                   13505: 
                   13506: =item 
                   13507: refused (invalid $username:$domain received on lond side).
                   13508: 
                   13509: =item 
                   13510: no_such_dir (directory at specified path on lond side does not exist). 
                   13511: 
                   13512: =item 
                   13513: empty (directory at specified path on lond side is empty).
                   13514: 
                   13515: =over
                   13516: 
                   13517: This is currently not encountered because the &ls3, &ls2, 
                   13518: &ls (_handler) routines on the lond side do not filter out
                   13519: . and .. from a directory listing. 
                   13520: 
                   13521: =back
                   13522: 
                   13523: =back
                   13524: 
                   13525: =back
1.191     harris41 13526: 
                   13527: =item *
                   13528: 
1.243     albertel 13529: spareserver() : find server with least workload from spare.tab
                   13530: 
1.986     foxr     13531: 
                   13532: =item *
                   13533: 
                   13534: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13535: if there is no corresponding loncapa host.
                   13536: 
1.243     albertel 13537: =back
                   13538: 
1.986     foxr     13539: 
1.243     albertel 13540: =head2 Apache Request
                   13541: 
                   13542: =over 4
1.191     harris41 13543: 
                   13544: =item *
                   13545: 
1.243     albertel 13546: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13547: localhost, posts hash
                   13548: 
                   13549: =back
                   13550: 
                   13551: =head2 Data to String to Data
                   13552: 
                   13553: =over 4
1.191     harris41 13554: 
                   13555: =item *
                   13556: 
1.243     albertel 13557: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13558: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13559: 
                   13560: =item *
                   13561: 
1.243     albertel 13562: hashref2str($hashref) : convert a hashref into a string complete with
                   13563: escaping and '=' and '&' separators, supports elements that are
                   13564: arrayrefs and hashrefs
1.191     harris41 13565: 
                   13566: =item *
                   13567: 
1.243     albertel 13568: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13569: with escaping and '&' separators, supports elements that are arrayrefs
                   13570: and hashrefs
1.191     harris41 13571: 
                   13572: =item *
                   13573: 
1.243     albertel 13574: str2hash($string) : convert string to hash using unescaping and
                   13575: splitting on '=' and '&', supports elements that are arrayrefs and
                   13576: hashrefs
1.191     harris41 13577: 
                   13578: =item *
                   13579: 
1.243     albertel 13580: str2array($string) : convert string to hash using unescaping and
                   13581: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13582: 
                   13583: =back
                   13584: 
                   13585: =head2 Logging Routines
                   13586: 
                   13587: 
                   13588: These routines allow one to make log messages in the lonnet.log and
                   13589: lonnet.perm logfiles.
1.191     harris41 13590: 
1.1119    foxr     13591: =over 4
                   13592: 
1.191     harris41 13593: =item *
                   13594: 
1.243     albertel 13595: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13596: 
                   13597: =item *
                   13598: 
1.243     albertel 13599: logthis() : append message to the normal lonnet.log file, it gets
                   13600: preiodically rolled over and deleted.
1.191     harris41 13601: 
                   13602: =item *
                   13603: 
1.243     albertel 13604: logperm() : append a permanent message to lonnet.perm.log, this log
                   13605: file never gets deleted by any automated portion of the system, only
                   13606: messages of critical importance should go in here.
                   13607: 
1.1119    foxr     13608: 
1.243     albertel 13609: =back
                   13610: 
                   13611: =head2 General File Helper Routines
                   13612: 
                   13613: =over 4
1.191     harris41 13614: 
                   13615: =item *
                   13616: 
1.481     raeburn  13617: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13618: (a) files in /uploaded
                   13619:   (i) If a local copy of the file exists - 
                   13620:       compares modification date of local copy with last-modified date for 
                   13621:       definitive version stored on home server for course. If local copy is 
                   13622:       stale, requests a new version from the home server and stores it. 
                   13623:       If the original has been removed from the home server, then local copy 
                   13624:       is unlinked.
                   13625:   (ii) If local copy does not exist -
                   13626:       requests the file from the home server and stores it. 
                   13627:   
                   13628:   If $caller is 'uploadrep':  
                   13629:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13630:     for request for files originally uploaded via DOCS. 
                   13631:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13632:   
                   13633:   Otherwise:
                   13634:      This indicates a call from the content generation phase of the request.
                   13635:      -  returns the entire contents of the file or -1.
                   13636:      
                   13637: (b) files in /res
                   13638:    - returns the entire contents of a file or -1; 
                   13639:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13640: 
1.712     albertel 13641: 
                   13642: =item *
                   13643: 
                   13644: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13645:                   reference
                   13646: 
                   13647: returns either a stat() list of data about the file or an empty list
                   13648: if the file doesn't exist or couldn't find out about it (connection
                   13649: problems or user unknown)
                   13650: 
1.191     harris41 13651: =item *
                   13652: 
1.243     albertel 13653: filelocation($dir,$file) : returns file system location of a file
                   13654: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13655: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13656: and a file of ../bob will become /a/bob)
1.191     harris41 13657: 
                   13658: =item *
                   13659: 
                   13660: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13661: filelocation except for hrefs
                   13662: 
                   13663: =item *
                   13664: 
1.1261    raeburn  13665: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   13666: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 13667: 
1.243     albertel 13668: =back
                   13669: 
1.608     albertel 13670: =head2 Usererfile file routines (/uploaded*)
                   13671: 
                   13672: =over 4
                   13673: 
                   13674: =item *
                   13675: 
                   13676: userfileupload(): main rotine for putting a file in a user or course's
                   13677:                   filespace, arguments are,
                   13678: 
1.620     albertel 13679:  formname - required - this is the name of the element in $env where the
1.608     albertel 13680:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13681:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13682:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13683:  context - if coursedoc, store the file in the course of the active role
                   13684:              of the current user; 
                   13685:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13686:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13687:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13688:          if undefined, it will be placed in "unknown"
                   13689: 
                   13690:  (This routine calls clean_filename() to remove any dangerous
                   13691:  characters from the filename, and then calls finuserfileupload() to
                   13692:  complete the transaction)
                   13693: 
                   13694:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13695:  and /adm/notfound.html if unsuccessful
                   13696: 
                   13697: =item *
                   13698: 
                   13699: clean_filename(): routine for cleaing a filename up for storage in
                   13700:                  userfile space, argument is:
                   13701: 
                   13702:  filename - proposed filename
                   13703: 
                   13704: returns: the new clean filename
                   13705: 
                   13706: =item *
                   13707: 
1.1090    raeburn  13708: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13709: userspace, probably shouldn't be called directly
                   13710: 
                   13711:   docuname: username or courseid of destination for the file
                   13712:   docudom: domain of user/course of destination for the file
                   13713:   formname: same as for userfileupload()
1.1090    raeburn  13714:   fname: filename (including subdirectories) for the file
                   13715:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13716:   allfiles: reference to hash used to store objects found by parser
                   13717:   codebase: reference to hash used for codebases of java objects found by parser
                   13718:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13719:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13720:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13721:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13722:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13723:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13724:   mimetype: reference to scalar to accommodate mime type determined
                   13725:             from File::MMagic if $parser = parse.
1.608     albertel 13726: 
                   13727:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13728:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13729:  was 'overwrite').
                   13730:  
1.608     albertel 13731: 
                   13732: =item *
                   13733: 
                   13734: renameuserfile(): renames an existing userfile to a new name
                   13735: 
                   13736:   Args:
                   13737:    docuname: username or courseid of destination for the file
                   13738:    docudom: domain of user/course of destination for the file
                   13739:    old: current file name (including any subdirs under userfiles)
                   13740:    new: desired file name (including any subdirs under userfiles)
                   13741: 
                   13742: =item *
                   13743: 
                   13744: mkdiruserfile(): creates a directory is a userfiles dir
                   13745: 
                   13746:   Args:
                   13747:    docuname: username or courseid of destination for the file
                   13748:    docudom: domain of user/course of destination for the file
                   13749:    dir: dir to create (including any subdirs under userfiles)
                   13750: 
                   13751: =item *
                   13752: 
                   13753: removeuserfile(): removes a file that exists in userfiles
                   13754: 
                   13755:   Args:
                   13756:    docuname: username or courseid of destination for the file
                   13757:    docudom: domain of user/course of destination for the file
                   13758:    fname: filname to delete (including any subdirs under userfiles)
                   13759: 
                   13760: =item *
                   13761: 
                   13762: removeuploadedurl(): convience function for removeuserfile()
                   13763: 
                   13764:   Args:
                   13765:    url:  a full /uploaded/... url to delete
                   13766: 
1.747     albertel 13767: =item * 
                   13768: 
                   13769: get_portfile_permissions():
                   13770:   Args:
                   13771:     domain: domain of user or course contain the portfolio files
                   13772:     user: name of user or num of course contain the portfolio files
                   13773:   Returns:
                   13774:     hashref of a dump of the proper file_permissions.db
                   13775:    
                   13776: 
                   13777: =item * 
                   13778: 
                   13779: get_access_controls():
                   13780: 
                   13781: Args:
                   13782:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13783:   group: (optional) the group you want the files associated with
                   13784:   file: (optional) the file you want access info on
                   13785: 
                   13786: Returns:
1.749     raeburn  13787:     a hash (keys are file names) of hashes containing
                   13788:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13789:         values are XML containing access control settings (see below) 
1.747     albertel 13790: 
                   13791: Internal notes:
                   13792: 
1.749     raeburn  13793:  access controls are stored in file_permissions.db as key=value pairs.
                   13794:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13795:         where scope -> public,guest,course,group,domains or users.
                   13796:               end -> UNIX time for end of access (0 -> no end date)
                   13797:               start -> UNIX time for start of access
                   13798: 
                   13799:     value -> XML description of access control
                   13800:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13801:             <start></start>
                   13802:             <end></end>
                   13803: 
                   13804:             <password></password>  for scope type = guest
                   13805: 
                   13806:             <domain></domain>     for scope type = course or group
                   13807:             <number></number>
                   13808:             <roles id="">
                   13809:              <role></role>
                   13810:              <access></access>
                   13811:              <section></section>
                   13812:              <group></group>
                   13813:             </roles>
                   13814: 
                   13815:             <dom></dom>         for scope type = domains
                   13816: 
                   13817:             <users>             for scope type = users
                   13818:              <user>
                   13819:               <uname></uname>
                   13820:               <udom></udom>
                   13821:              </user>
                   13822:             </users>
                   13823:            </scope> 
                   13824:               
                   13825:  Access data is also aggregated for each file in an additional key=value pair:
                   13826:  key -> path to file/file_name\0accesscontrol 
                   13827:  value -> reference to hash
                   13828:           hash contains key = value pairs
                   13829:           where key = uniqueID:scope_end_start
                   13830:                 value = UNIX time record was last updated
                   13831: 
                   13832:           Used to improve speed of look-ups of access controls for each file.  
                   13833:  
                   13834:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13835: 
1.1198    raeburn  13836: =item *
                   13837: 
1.749     raeburn  13838: modify_access_controls():
                   13839: 
                   13840: Modifies access controls for a portfolio file
                   13841: Args
                   13842: 1. file name
                   13843: 2. reference to hash of required changes,
                   13844: 3. domain
                   13845: 4. username
                   13846:   where domain,username are the domain of the portfolio owner 
                   13847:   (either a user or a course) 
                   13848: 
                   13849: Returns:
                   13850: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13851: 2. result of deletions ('ok' or 'error', with error message).
                   13852: 3. reference to hash of any new or updated access controls.
                   13853: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13854:    key = integer (inbound ID)
1.1198    raeburn  13855:    value = uniqueID
                   13856: 
                   13857: =item *
                   13858: 
                   13859: get_timebased_id():
                   13860: 
                   13861: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   13862: course via the Course Editor (e.g., folders, composite pages, 
                   13863: group bulletin boards).
                   13864: 
                   13865: Args: (first three required; six others optional)
                   13866: 
                   13867: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13868:    docssequence, or name of group
                   13869: 
                   13870: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13871:    e.g., num, boardids
                   13872: 
                   13873: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   13874:    file will be named nohist_namespace.db
                   13875: 
                   13876: 4. cdom: domain of course; default is current course domain from %env
                   13877: 
                   13878: 5. cnum: course number; default is current course number from %env
                   13879: 
                   13880: 6. idtype: set to concat if an additional digit is to be appended to the 
                   13881:    unix timestamp to form the suffix, if the plain timestamp is already
                   13882:    in use.  Default is to not do this, but simply increment the unix 
                   13883:    timestamp by 1 until a unique key is obtained.
                   13884: 
                   13885: 7. who: holder of locking key; defaults to user:domain for user.
                   13886: 
                   13887: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   13888:    retrying); default is 3.
                   13889: 
                   13890: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   13891: 
                   13892: Returns:
                   13893: 
                   13894: 1. suffix obtained (numeric)
                   13895: 
                   13896: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13897: 
                   13898: 3. error: contains (localized) error message if an error occurred.
                   13899: 
1.747     albertel 13900: 
1.608     albertel 13901: =back
                   13902: 
1.243     albertel 13903: =head2 HTTP Helper Routines
                   13904: 
                   13905: =over 4
                   13906: 
1.191     harris41 13907: =item *
                   13908: 
                   13909: escape() : unpack non-word characters into CGI-compatible hex codes
                   13910: 
                   13911: =item *
                   13912: 
                   13913: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13914: 
1.243     albertel 13915: =back
                   13916: 
                   13917: =head1 PRIVATE SUBROUTINES
                   13918: 
                   13919: =head2 Underlying communication routines (Shouldn't call)
                   13920: 
                   13921: =over 4
                   13922: 
                   13923: =item *
                   13924: 
                   13925: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13926: 
                   13927: =item *
                   13928: 
                   13929: reply() : uses subreply to send a message to remote machine, logs all failures
                   13930: 
                   13931: =item *
                   13932: 
                   13933: critical() : passes a critical message to another server; if cannot
                   13934: get through then place message in connection buffer directory and
                   13935: returns con_delayed, if incapable of saving message, returns
                   13936: con_failed
                   13937: 
                   13938: =item *
                   13939: 
                   13940: reconlonc() : tries to reconnect lonc client processes.
                   13941: 
                   13942: =back
                   13943: 
                   13944: =head2 Resource Access Logging
                   13945: 
                   13946: =over 4
                   13947: 
                   13948: =item *
                   13949: 
                   13950: flushcourselogs() : flush (save) buffer logs and access logs
                   13951: 
                   13952: =item *
                   13953: 
                   13954: courselog($what) : save message for course in hash
                   13955: 
                   13956: =item *
                   13957: 
                   13958: courseacclog($what) : save message for course using &courselog().  Perform
                   13959: special processing for specific resource types (problems, exams, quizzes, etc).
                   13960: 
1.191     harris41 13961: =item *
                   13962: 
                   13963: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13964: as a PerlChildExitHandler
1.243     albertel 13965: 
                   13966: =back
                   13967: 
                   13968: =head2 Other
                   13969: 
                   13970: =over 4
                   13971: 
                   13972: =item *
                   13973: 
                   13974: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13975: 
                   13976: =back
                   13977: 
                   13978: =cut
1.877     foxr     13979: 

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