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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1271  ! raeburn     4: # $Id: lonnet.pm,v 1.1270 2014/12/01 22:53:00 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.1267    raeburn  1655:     return if ($udom eq 'public');
1.806     raeburn  1656:     my $items='';
                   1657:     foreach my $item (@$storearr) {
                   1658:         $items.=&escape($item).'&';
                   1659:     }
                   1660:     $items=~s/\&$//;
1.860     raeburn  1661:     if (!$udom) {
                   1662:         $udom=$env{'user.domain'};
1.1267    raeburn  1663:         return if ($udom eq 'public');
1.860     raeburn  1664:         if (defined(&domain($udom,'primary'))) {
                   1665:             $uhome=&domain($udom,'primary');
                   1666:         } else {
1.874     albertel 1667:             undef($uhome);
1.860     raeburn  1668:         }
                   1669:     } else {
                   1670:         if (!$uhome) {
                   1671:             if (defined(&domain($udom,'primary'))) {
                   1672:                 $uhome=&domain($udom,'primary');
                   1673:             }
                   1674:         }
                   1675:     }
                   1676:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1677:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1678:         my %returnhash;
1.875     albertel 1679:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1680:             return %returnhash;
                   1681:         }
1.806     raeburn  1682:         my @pairs=split(/\&/,$rep);
                   1683:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1684:             return @pairs;
                   1685:         }
                   1686:         my $i=0;
                   1687:         foreach my $item (@$storearr) {
                   1688:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1689:             $i++;
                   1690:         }
                   1691:         return %returnhash;
                   1692:     } else {
1.880     banghart 1693:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1694:     }
                   1695: }
                   1696: 
                   1697: # -------------------------------------------- put items in domain db files 
                   1698: 
                   1699: sub put_dom {
1.860     raeburn  1700:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1701:     if (!$udom) {
                   1702:         $udom=$env{'user.domain'};
                   1703:         if (defined(&domain($udom,'primary'))) {
                   1704:             $uhome=&domain($udom,'primary');
                   1705:         } else {
1.874     albertel 1706:             undef($uhome);
1.860     raeburn  1707:         }
                   1708:     } else {
                   1709:         if (!$uhome) {
                   1710:             if (defined(&domain($udom,'primary'))) {
                   1711:                 $uhome=&domain($udom,'primary');
                   1712:             }
                   1713:         }
                   1714:     } 
                   1715:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1716:         my $items='';
                   1717:         foreach my $item (keys(%$storehash)) {
                   1718:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1719:         }
                   1720:         $items=~s/\&$//;
                   1721:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1722:     } else {
1.860     raeburn  1723:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1724:     }
                   1725: }
                   1726: 
1.1023    raeburn  1727: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1728: sub newput_dom {
1.1023    raeburn  1729:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1730:     my $result;
                   1731:     if (!$udom) {
                   1732:         $udom=$env{'user.domain'};
                   1733:     }
1.1023    raeburn  1734:     if ($udom) {
                   1735:         my $uname = &get_domainconfiguser($udom);
                   1736:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1737:     }
                   1738:     return $result;
                   1739: }
                   1740: 
1.1023    raeburn  1741: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1742: sub del_dom {
1.1023    raeburn  1743:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1744:     if (ref($storearr) eq 'ARRAY') {
                   1745:         if (!$udom) {
                   1746:             $udom=$env{'user.domain'};
                   1747:         }
1.1023    raeburn  1748:         if ($udom) {
                   1749:             my $uname = &get_domainconfiguser($udom); 
                   1750:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1751:         }
                   1752:     }
                   1753: }
                   1754: 
1.1023    raeburn  1755: # ----------------------------------construct domainconfig user for a domain 
                   1756: sub get_domainconfiguser {
                   1757:     my ($udom) = @_;
                   1758:     return $udom.'-domainconfig';
                   1759: }
                   1760: 
1.837     raeburn  1761: sub retrieve_inst_usertypes {
                   1762:     my ($udom) = @_;
                   1763:     my (%returnhash,@order);
1.989     raeburn  1764:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1765:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1766:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  1767:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1768:     } else {
                   1769:         if (defined(&domain($udom,'primary'))) {
                   1770:             my $uhome=&domain($udom,'primary');
                   1771:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1772:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  1773:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1774:                 return (\%returnhash,\@order);
                   1775:             }
                   1776:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1777:             my @pairs=split(/\&/,$hashitems);
                   1778:             foreach my $item (@pairs) {
                   1779:                 my ($key,$value)=split(/=/,$item,2);
                   1780:                 $key = &unescape($key);
                   1781:                 next if ($key =~ /^error: 2 /);
                   1782:                 $returnhash{$key}=&thaw_unescape($value);
                   1783:             }
                   1784:             my @esc_order = split(/\&/,$orderitems);
                   1785:             foreach my $item (@esc_order) {
                   1786:                 push(@order,&unescape($item));
                   1787:             }
                   1788:         } else {
1.1256    raeburn  1789:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1790:         }
1.1256    raeburn  1791:         return (\%returnhash,\@order);
1.837     raeburn  1792:     }
                   1793: }
                   1794: 
1.868     raeburn  1795: sub is_domainimage {
                   1796:     my ($url) = @_;
                   1797:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1798:         if (&domain($1) ne '') {
                   1799:             return '1';
                   1800:         }
                   1801:     }
                   1802:     return;
                   1803: }
                   1804: 
1.899     raeburn  1805: sub inst_directory_query {
                   1806:     my ($srch) = @_;
                   1807:     my $udom = $srch->{'srchdomain'};
                   1808:     my %results;
                   1809:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1810:     my $outcome;
1.899     raeburn  1811:     if ($homeserver ne '') {
1.904     albertel 1812: 	my $queryid=&reply("querysend:instdirsearch:".
                   1813: 			   &escape($srch->{'srchby'}).':'.
                   1814: 			   &escape($srch->{'srchterm'}).':'.
                   1815: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1816: 	my $host=&hostname($homeserver);
                   1817: 	if ($queryid !~/^\Q$host\E\_/) {
                   1818: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1819: 	    return;
                   1820: 	}
                   1821: 	my $response = &get_query_reply($queryid);
                   1822: 	my $maxtries = 5;
                   1823: 	my $tries = 1;
                   1824: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1825: 	    $response = &get_query_reply($queryid);
                   1826: 	    $tries ++;
                   1827: 	}
                   1828: 
                   1829:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1830:             if ($response eq 'unavailable') {
                   1831:                 $outcome = $response;
                   1832:             } else {
                   1833:                 $outcome = 'ok';
                   1834:                 my @matches = split(/\n/,$response);
                   1835:                 foreach my $match (@matches) {
                   1836:                     my ($key,$value) = split(/=/,$match);
                   1837:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1838:                 }
1.899     raeburn  1839:             }
                   1840:         }
                   1841:     }
1.909     raeburn  1842:     return ($outcome,%results);
1.899     raeburn  1843: }
                   1844: 
                   1845: sub usersearch {
                   1846:     my ($srch) = @_;
                   1847:     my $dom = $srch->{'srchdomain'};
                   1848:     my %results;
                   1849:     my %libserv = &all_library();
                   1850:     my $query = 'usersearch';
                   1851:     foreach my $tryserver (keys(%libserv)) {
                   1852:         if (&host_domain($tryserver) eq $dom) {
                   1853:             my $host=&hostname($tryserver);
                   1854:             my $queryid=
1.911     raeburn  1855:                 &reply("querysend:".&escape($query).':'.
                   1856:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1857:                        &escape($srch->{'srchtype'}).':'.
                   1858:                        &escape($srch->{'srchterm'}),$tryserver);
                   1859:             if ($queryid !~/^\Q$host\E\_/) {
                   1860:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1861:                 next;
1.899     raeburn  1862:             }
                   1863:             my $reply = &get_query_reply($queryid);
                   1864:             my $maxtries = 1;
                   1865:             my $tries = 1;
                   1866:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1867:                 $reply = &get_query_reply($queryid);
                   1868:                 $tries ++;
                   1869:             }
                   1870:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1871:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1872:             } else {
1.911     raeburn  1873:                 my @matches;
                   1874:                 if ($reply =~ /\n/) {
                   1875:                     @matches = split(/\n/,$reply);
                   1876:                 } else {
                   1877:                     @matches = split(/\&/,$reply);
                   1878:                 }
1.899     raeburn  1879:                 foreach my $match (@matches) {
                   1880:                     my ($uname,$udom,%userhash);
1.911     raeburn  1881:                     foreach my $entry (split(/:/,$match)) {
                   1882:                         my ($key,$value) =
                   1883:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1884:                         $userhash{$key} = $value;
                   1885:                         if ($key eq 'username') {
                   1886:                             $uname = $value;
                   1887:                         } elsif ($key eq 'domain') {
                   1888:                             $udom = $value;
1.911     raeburn  1889:                         }
1.899     raeburn  1890:                     }
                   1891:                     $results{$uname.':'.$udom} = \%userhash;
                   1892:                 }
                   1893:             }
                   1894:         }
                   1895:     }
                   1896:     return %results;
                   1897: }
                   1898: 
1.912     raeburn  1899: sub get_instuser {
                   1900:     my ($udom,$uname,$id) = @_;
                   1901:     my $homeserver = &domain($udom,'primary');
                   1902:     my ($outcome,%results);
                   1903:     if ($homeserver ne '') {
                   1904:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1905:                            &escape($id).':'.&escape($udom),$homeserver);
                   1906:         my $host=&hostname($homeserver);
                   1907:         if ($queryid !~/^\Q$host\E\_/) {
                   1908:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1909:             return;
                   1910:         }
                   1911:         my $response = &get_query_reply($queryid);
                   1912:         my $maxtries = 5;
                   1913:         my $tries = 1;
                   1914:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1915:             $response = &get_query_reply($queryid);
                   1916:             $tries ++;
                   1917:         }
                   1918:         if (!&error($response) && $response ne 'refused') {
                   1919:             if ($response eq 'unavailable') {
                   1920:                 $outcome = $response;
                   1921:             } else {
                   1922:                 $outcome = 'ok';
                   1923:                 my @matches = split(/\n/,$response);
                   1924:                 foreach my $match (@matches) {
                   1925:                     my ($key,$value) = split(/=/,$match);
                   1926:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1927:                 }
                   1928:             }
                   1929:         }
                   1930:     }
                   1931:     my %userinfo;
                   1932:     if (ref($results{$uname}) eq 'HASH') {
                   1933:         %userinfo = %{$results{$uname}};
                   1934:     } 
                   1935:     return ($outcome,%userinfo);
                   1936: }
                   1937: 
                   1938: sub inst_rulecheck {
1.923     raeburn  1939:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1940:     my %returnhash;
                   1941:     if ($udom ne '') {
                   1942:         if (ref($rules) eq 'ARRAY') {
                   1943:             @{$rules} = map {&escape($_);} (@{$rules});
                   1944:             my $rulestr = join(':',@{$rules});
                   1945:             my $homeserver=&domain($udom,'primary');
                   1946:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1947:                 my $response;
                   1948:                 if ($item eq 'username') {                
                   1949:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1950:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1951:                                               $homeserver));
1.923     raeburn  1952:                 } elsif ($item eq 'id') {
                   1953:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1954:                                               ':'.&escape($id).':'.$rulestr,
                   1955:                                               $homeserver));
1.945     raeburn  1956:                 } elsif ($item eq 'selfcreate') {
                   1957:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1958:                                                &escape($udom).':'.&escape($uname).
                   1959:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1960:                 }
1.912     raeburn  1961:                 if ($response ne 'refused') {
                   1962:                     my @pairs=split(/\&/,$response);
                   1963:                     foreach my $item (@pairs) {
                   1964:                         my ($key,$value)=split(/=/,$item,2);
                   1965:                         $key = &unescape($key);
                   1966:                         next if ($key =~ /^error: 2 /);
                   1967:                         $returnhash{$key}=&thaw_unescape($value);
                   1968:                     }
                   1969:                 }
                   1970:             }
                   1971:         }
                   1972:     }
                   1973:     return %returnhash;
                   1974: }
                   1975: 
                   1976: sub inst_userrules {
1.923     raeburn  1977:     my ($udom,$check) = @_;
1.912     raeburn  1978:     my (%ruleshash,@ruleorder);
                   1979:     if ($udom ne '') {
                   1980:         my $homeserver=&domain($udom,'primary');
                   1981:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1982:             my $response;
                   1983:             if ($check eq 'id') {
                   1984:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1985:                                  $homeserver);
1.943     raeburn  1986:             } elsif ($check eq 'email') {
                   1987:                 $response=&reply('instemailrules:'.&escape($udom),
                   1988:                                  $homeserver);
1.923     raeburn  1989:             } else {
                   1990:                 $response=&reply('instuserrules:'.&escape($udom),
                   1991:                                  $homeserver);
                   1992:             }
1.912     raeburn  1993:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1994:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1995:                 ($response ne 'no_such_host')) {
                   1996:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1997:                 my @pairs=split(/\&/,$hashitems);
                   1998:                 foreach my $item (@pairs) {
                   1999:                     my ($key,$value)=split(/=/,$item,2);
                   2000:                     $key = &unescape($key);
                   2001:                     next if ($key =~ /^error: 2 /);
                   2002:                     $ruleshash{$key}=&thaw_unescape($value);
                   2003:                 }
                   2004:                 my @esc_order = split(/\&/,$orderitems);
                   2005:                 foreach my $item (@esc_order) {
                   2006:                     push(@ruleorder,&unescape($item));
                   2007:                 }
                   2008:             }
                   2009:         }
                   2010:     }
                   2011:     return (\%ruleshash,\@ruleorder);
                   2012: }
                   2013: 
1.976     raeburn  2014: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2015: 
                   2016: sub get_domain_defaults {
1.1240    raeburn  2017:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2018:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2019:     my $cachetime = 60*60*24;
1.1240    raeburn  2020:     unless ($ignore_cache) {
                   2021:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2022:         if (defined($cached)) {
                   2023:             if (ref($result) eq 'HASH') {
                   2024:                 return %{$result};
                   2025:             }
1.943     raeburn  2026:         }
                   2027:     }
                   2028:     my %domdefaults;
                   2029:     my %domconfig =
1.989     raeburn  2030:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2031:                                   'requestcourses','inststatus',
1.1183    raeburn  2032:                                   'coursedefaults','usersessions',
1.1258    raeburn  2033:                                   'requestauthor','selfenrollment',
                   2034:                                   'coursecategories'],$domain);
1.1254    raeburn  2035:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2036:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2037:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2038:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2039:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2040:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2041:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2042:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2043:     } else {
                   2044:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2045:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2046:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2047:     }
1.976     raeburn  2048:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2049:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2050:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2051:         } else {
                   2052:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2053:         }
1.1177    raeburn  2054:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2055:         foreach my $item (@usertools) {
                   2056:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2057:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2058:             }
                   2059:         }
1.1229    raeburn  2060:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2061:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2062:         }
1.976     raeburn  2063:     }
1.985     raeburn  2064:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246    raeburn  2065:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2066:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2067:         }
                   2068:     }
1.1183    raeburn  2069:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2070:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2071:     }
1.989     raeburn  2072:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2073:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2074:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2075:         }
                   2076:     }
1.1047    raeburn  2077:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2078:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1254    raeburn  2079:         foreach my $type (@coursetypes) {
                   2080:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2081:                 unless ($type eq 'community') {
                   2082:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2083:                 }
                   2084:             }
                   2085:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2086:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2087:             }
1.1230    raeburn  2088:         }
1.1047    raeburn  2089:     }
1.1073    raeburn  2090:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2091:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2092:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2093:         }
                   2094:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2095:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2096:         }
                   2097:     }
1.1254    raeburn  2098:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2099:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2100:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2101:                             'approval','limit');
                   2102:             foreach my $type (@coursetypes) {
                   2103:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2104:                     my @mgrdc = ();
                   2105:                     foreach my $item (@settings) {
                   2106:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2107:                             push(@mgrdc,$item);
                   2108:                         }
                   2109:                     }
                   2110:                     if (@mgrdc) {
                   2111:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2112:                     }
                   2113:                 }
                   2114:             }
                   2115:         }
                   2116:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2117:             foreach my $type (@coursetypes) {
                   2118:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2119:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2120:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2121:                     }
                   2122:                 }
                   2123:             }
                   2124:         }
                   2125:     }
1.1258    raeburn  2126:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2127:         $domdefaults{'catauth'} = 'std';
                   2128:         $domdefaults{'catunauth'} = 'std';
                   2129:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2130:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2131:         }
                   2132:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2133:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2134:         }
                   2135:     }
1.1219    raeburn  2136:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2137:     return %domdefaults;
                   2138: }
                   2139: 
1.344     www      2140: # --------------------------------------------------- Assign a key to a student
                   2141: 
                   2142: sub assign_access_key {
1.364     www      2143: #
                   2144: # a valid key looks like uname:udom#comments
                   2145: # comments are being appended
                   2146: #
1.498     www      2147:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2148:     $kdom=
1.620     albertel 2149:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2150:     $knum=
1.620     albertel 2151:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2152:     $cdom=
1.620     albertel 2153:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2154:     $cnum=
1.620     albertel 2155:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2156:     $udom=$env{'user.name'} unless (defined($udom));
                   2157:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2158:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2159:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2160:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2161:                                                   # assigned to this person
                   2162:                                                   # - this should not happen,
1.345     www      2163:                                                   # unless something went wrong
                   2164:                                                   # the first time around
                   2165: # ready to assign
1.364     www      2166:         $logentry=$1.'; '.$logentry;
1.496     www      2167:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2168:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2169: # key now belongs to user
1.346     www      2170: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2171:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2172:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2173:                 return 'ok';
                   2174:             } else {
                   2175:                 return 
                   2176:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2177: 	    }
                   2178:         } else {
                   2179:             return 'error: Could not assign key, try again later.';
                   2180:         }
1.364     www      2181:     } elsif (!$existing{$ckey}) {
1.345     www      2182: # the key does not exist
                   2183: 	return 'error: The key does not exist';
                   2184:     } else {
                   2185: # the key is somebody else's
                   2186: 	return 'error: The key is already in use';
                   2187:     }
1.344     www      2188: }
                   2189: 
1.364     www      2190: # ------------------------------------------ put an additional comment on a key
                   2191: 
                   2192: sub comment_access_key {
                   2193: #
                   2194: # a valid key looks like uname:udom#comments
                   2195: # comments are being appended
                   2196: #
                   2197:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2198:     $cdom=
1.620     albertel 2199:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2200:     $cnum=
1.620     albertel 2201:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2202:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2203:     if ($existing{$ckey}) {
                   2204:         $existing{$ckey}.='; '.$logentry;
                   2205: # ready to assign
1.367     www      2206:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2207:                                                  $cdom,$cnum) eq 'ok') {
                   2208: 	    return 'ok';
                   2209:         } else {
                   2210: 	    return 'error: Count not store comment.';
                   2211:         }
                   2212:     } else {
                   2213: # the key does not exist
                   2214: 	return 'error: The key does not exist';
                   2215:     }
                   2216: }
                   2217: 
1.344     www      2218: # ------------------------------------------------------ Generate a set of keys
                   2219: 
                   2220: sub generate_access_keys {
1.364     www      2221:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2222:     $cdom=
1.620     albertel 2223:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2224:     $cnum=
1.620     albertel 2225:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2226:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2227:     unless (($cdom) && ($cnum)) { return 0; }
                   2228:     if ($number>10000) { return 0; }
                   2229:     sleep(2); # make sure don't get same seed twice
                   2230:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2231:     my $total=0;
                   2232:     for (my $i=1;$i<=$number;$i++) {
                   2233:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2234:                   sprintf("%lx",int(100000*rand)).'-'.
                   2235:                   sprintf("%lx",int(100000*rand));
                   2236:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2237:        $newkey=~s/0/h/g; # and also 0 and O
                   2238:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2239:        if ($existing{$newkey}) {
                   2240:            $i--;
                   2241:        } else {
1.364     www      2242: 	  if (&put('accesskeys',
                   2243:               { $newkey => '# generated '.localtime().
1.620     albertel 2244:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2245:                            '; '.$logentry },
                   2246: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2247:               $total++;
                   2248: 	  }
                   2249:        }
                   2250:     }
1.620     albertel 2251:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2252:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2253:     return $total;
                   2254: }
                   2255: 
                   2256: # ------------------------------------------------------- Validate an accesskey
                   2257: 
                   2258: sub validate_access_key {
                   2259:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2260:     $cdom=
1.620     albertel 2261:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2262:     $cnum=
1.620     albertel 2263:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2264:     $udom=$env{'user.domain'} unless (defined($udom));
                   2265:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2266:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2267:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2268: }
                   2269: 
                   2270: # ------------------------------------- Find the section of student in a course
1.652     albertel 2271: sub devalidate_getsection_cache {
                   2272:     my ($udom,$unam,$courseid)=@_;
                   2273:     my $hashid="$udom:$unam:$courseid";
                   2274:     &devalidate_cache_new('getsection',$hashid);
                   2275: }
1.298     matthew  2276: 
1.815     albertel 2277: sub courseid_to_courseurl {
                   2278:     my ($courseid) = @_;
                   2279:     #already url style courseid
                   2280:     return $courseid if ($courseid =~ m{^/});
                   2281: 
                   2282:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2283: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2284: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2285: 	return "/$cdom/$cnum";
                   2286:     }
                   2287: 
                   2288:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2289:     if (exists($courseinfo{'num'})) {
                   2290: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2291:     }
                   2292: 
                   2293:     return undef;
                   2294: }
                   2295: 
1.298     matthew  2296: sub getsection {
                   2297:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2298:     my $cachetime=1800;
1.551     albertel 2299: 
                   2300:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2301:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2302:     if (defined($cached)) { return $result; }
                   2303: 
1.298     matthew  2304:     my %Pending; 
                   2305:     my %Expired;
                   2306:     #
                   2307:     # Each role can either have not started yet (pending), be active, 
                   2308:     #    or have expired.
                   2309:     #
                   2310:     # If there is an active role, we are done.
                   2311:     #
                   2312:     # If there is more than one role which has not started yet, 
                   2313:     #     choose the one which will start sooner
                   2314:     # If there is one role which has not started yet, return it.
                   2315:     #
                   2316:     # If there is more than one expired role, choose the one which ended last.
                   2317:     # If there is a role which has expired, return it.
                   2318:     #
1.815     albertel 2319:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2320:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2321:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2322:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2323:         my $section=$1;
                   2324:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2325:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2326:         my $now=time;
1.548     albertel 2327:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2328:             $Expired{$end}=$section;
                   2329:             next;
                   2330:         }
1.548     albertel 2331:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2332:             $Pending{$start}=$section;
                   2333:             next;
                   2334:         }
1.599     albertel 2335:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2336:     }
                   2337:     #
                   2338:     # Presumedly there will be few matching roles from the above
                   2339:     # loop and the sorting time will be negligible.
                   2340:     if (scalar(keys(%Pending))) {
                   2341:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2342:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2343:     } 
                   2344:     if (scalar(keys(%Expired))) {
                   2345:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2346:         my $time = pop(@sorted);
1.599     albertel 2347:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2348:     }
1.599     albertel 2349:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2350: }
1.70      www      2351: 
1.599     albertel 2352: sub save_cache {
                   2353:     &purge_remembered();
1.722     albertel 2354:     #&Apache::loncommon::validate_page();
1.620     albertel 2355:     undef(%env);
1.780     albertel 2356:     undef($env_loaded);
1.599     albertel 2357: }
1.452     albertel 2358: 
1.599     albertel 2359: my $to_remember=-1;
                   2360: my %remembered;
                   2361: my %accessed;
                   2362: my $kicks=0;
                   2363: my $hits=0;
1.849     albertel 2364: sub make_key {
                   2365:     my ($name,$id) = @_;
1.872     albertel 2366:     if (length($id) > 65 
                   2367: 	&& length(&escape($id)) > 200) {
                   2368: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2369:     }
1.849     albertel 2370:     return &escape($name.':'.$id);
                   2371: }
                   2372: 
1.599     albertel 2373: sub devalidate_cache_new {
                   2374:     my ($name,$id,$debug) = @_;
                   2375:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2376:     $id=&make_key($name,$id);
1.599     albertel 2377:     $memcache->delete($id);
                   2378:     delete($remembered{$id});
                   2379:     delete($accessed{$id});
                   2380: }
                   2381: 
                   2382: sub is_cached_new {
                   2383:     my ($name,$id,$debug) = @_;
1.849     albertel 2384:     $id=&make_key($name,$id);
1.599     albertel 2385:     if (exists($remembered{$id})) {
1.1133    foxr     2386: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2387: 	$accessed{$id}=[&gettimeofday()];
                   2388: 	$hits++;
                   2389: 	return ($remembered{$id},1);
                   2390:     }
                   2391:     my $value = $memcache->get($id);
                   2392:     if (!(defined($value))) {
                   2393: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2394: 	return (undef,undef);
1.416     albertel 2395:     }
1.599     albertel 2396:     if ($value eq '__undef__') {
                   2397: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2398: 	$value=undef;
                   2399:     }
                   2400:     &make_room($id,$value,$debug);
                   2401:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2402:     return ($value,1);
                   2403: }
                   2404: 
                   2405: sub do_cache_new {
                   2406:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2407:     $id=&make_key($name,$id);
1.599     albertel 2408:     my $setvalue=$value;
                   2409:     if (!defined($setvalue)) {
                   2410: 	$setvalue='__undef__';
                   2411:     }
1.623     albertel 2412:     if (!defined($time) ) {
                   2413: 	$time=600;
                   2414:     }
1.599     albertel 2415:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2416:     my $result = $memcache->set($id,$setvalue,$time);
                   2417:     if (! $result) {
1.872     albertel 2418: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2419: 	$memcache->disconnect_all();
1.872     albertel 2420:     }
1.600     albertel 2421:     # need to make a copy of $value
1.919     albertel 2422:     &make_room($id,$value,$debug);
1.599     albertel 2423:     return $value;
                   2424: }
                   2425: 
                   2426: sub make_room {
                   2427:     my ($id,$value,$debug)=@_;
1.919     albertel 2428: 
                   2429:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2430:                                     : $value;
1.599     albertel 2431:     if ($to_remember<0) { return; }
                   2432:     $accessed{$id}=[&gettimeofday()];
                   2433:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2434:     my $to_kick;
                   2435:     my $max_time=0;
                   2436:     foreach my $other (keys(%accessed)) {
                   2437: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2438: 	    $to_kick=$other;
                   2439: 	    $max_time=&tv_interval($accessed{$other});
                   2440: 	}
                   2441:     }
                   2442:     delete($remembered{$to_kick});
                   2443:     delete($accessed{$to_kick});
                   2444:     $kicks++;
                   2445:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2446:     return;
                   2447: }
                   2448: 
1.599     albertel 2449: sub purge_remembered {
1.604     albertel 2450:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2451:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2452:     undef(%remembered);
                   2453:     undef(%accessed);
1.428     albertel 2454: }
1.70      www      2455: # ------------------------------------- Read an entry from a user's environment
                   2456: 
                   2457: sub userenvironment {
                   2458:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2459:     my $items;
                   2460:     foreach my $item (@what) {
                   2461:         $items.=&escape($item).'&';
                   2462:     }
                   2463:     $items=~s/\&$//;
1.70      www      2464:     my %returnhash=();
1.1009    raeburn  2465:     my $uhome = &homeserver($unam,$udom);
                   2466:     unless ($uhome eq 'no_host') {
                   2467:         my @answer=split(/\&/, 
                   2468:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2469:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2470:             return %returnhash;
                   2471:         }
1.1009    raeburn  2472:         my $i;
                   2473:         for ($i=0;$i<=$#what;$i++) {
                   2474: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2475:         }
1.70      www      2476:     }
                   2477:     return %returnhash;
1.1       albertel 2478: }
                   2479: 
1.617     albertel 2480: # ---------------------------------------------------------- Get a studentphoto
                   2481: sub studentphoto {
                   2482:     my ($udom,$unam,$ext) = @_;
                   2483:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2484:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2485:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2486:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2487:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2488:             } else {
                   2489:                 my ($result,$perm_reqd)=
1.707     albertel 2490: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2491:                 if ($result eq 'ok') {
                   2492:                     if (!($perm_reqd eq 'yes')) {
                   2493:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2494:                     }
                   2495:                 }
                   2496:             }
                   2497:         }
                   2498:     } else {
                   2499:         my ($result,$perm_reqd) = 
1.707     albertel 2500: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2501:         if ($result eq 'ok') {
                   2502:             if (!($perm_reqd eq 'yes')) {
                   2503:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2504:             }
                   2505:         }
                   2506:     }
                   2507:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2508: }
                   2509: 
                   2510: sub retrievestudentphoto {
                   2511:     my ($udom,$unam,$ext,$type) = @_;
                   2512:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2513:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2514:     if ($ret eq 'ok') {
                   2515:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2516:         if ($type eq 'thumbnail') {
                   2517:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2518:         }
                   2519:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2520:         return $tokenurl;
                   2521:     } else {
                   2522:         if ($type eq 'thumbnail') {
                   2523:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2524:         } else { 
                   2525:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2526:         }
1.617     albertel 2527:     }
                   2528: }
                   2529: 
1.263     www      2530: # -------------------------------------------------------------------- New chat
                   2531: 
                   2532: sub chatsend {
1.724     raeburn  2533:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2534:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2535:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2536:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2537:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2538: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2539: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2540: }
                   2541: 
                   2542: # ------------------------------------------ Find current version of a resource
                   2543: 
                   2544: sub getversion {
                   2545:     my $fname=&clutter(shift);
1.1189    raeburn  2546:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2547:     return &currentversion(&filelocation('',$fname));
                   2548: }
                   2549: 
                   2550: sub currentversion {
                   2551:     my $fname=shift;
                   2552:     my $author=$fname;
                   2553:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2554:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2555:     my $home=&homeserver($uname,$udom);
1.292     www      2556:     if ($home eq 'no_host') { 
                   2557:         return -1; 
                   2558:     }
1.1112    www      2559:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2560:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2561: 	return -1;
                   2562:     }
1.1112    www      2563:     return $answer;
1.263     www      2564: }
                   2565: 
1.1111    www      2566: #
                   2567: # Return special version number of resource if set by override, empty otherwise
                   2568: #
                   2569: sub usedversion {
                   2570:     my $fname=shift;
                   2571:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2572:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2573:     if ($urlversion) { return $urlversion; }
                   2574:     return '';
                   2575: }
                   2576: 
1.1       albertel 2577: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2578: 
1.1       albertel 2579: sub subscribe {
                   2580:     my $fname=shift;
1.761     raeburn  2581:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2582:     $fname=~s/[\n\r]//g;
1.1       albertel 2583:     my $author=$fname;
                   2584:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2585:     my ($udom,$uname)=split(/\//,$author);
                   2586:     my $home=homeserver($uname,$udom);
1.335     albertel 2587:     if ($home eq 'no_host') {
                   2588:         return 'not_found';
1.1       albertel 2589:     }
                   2590:     my $answer=reply("sub:$fname",$home);
1.64      www      2591:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2592: 	$answer.=' by '.$home;
                   2593:     }
1.1       albertel 2594:     return $answer;
                   2595: }
                   2596:     
1.8       www      2597: # -------------------------------------------------------------- Replicate file
                   2598: 
                   2599: sub repcopy {
                   2600:     my $filename=shift;
1.23      www      2601:     $filename=~s/\/+/\//g;
1.1142    raeburn  2602:     my $londocroot = $perlvar{'lonDocRoot'};
                   2603:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2604:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2605:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2606: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2607: 	return &repcopy_userfile($filename);
                   2608:     }
1.532     albertel 2609:     $filename=~s/[\n\r]//g;
1.8       www      2610:     my $transname="$filename.in.transfer";
1.828     www      2611: # FIXME: this should flock
1.607     raeburn  2612:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2613:     my $remoteurl=subscribe($filename);
1.64      www      2614:     if ($remoteurl =~ /^con_lost by/) {
                   2615: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2616:            return 'unavailable';
1.8       www      2617:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2618: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2619: 	   return 'not_found';
1.64      www      2620:     } elsif ($remoteurl =~ /^rejected by/) {
                   2621: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2622:            return 'forbidden';
1.20      www      2623:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2624:            return 'ok';
1.8       www      2625:     } else {
1.290     www      2626:         my $author=$filename;
                   2627:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2628:         my ($udom,$uname)=split(/\//,$author);
                   2629:         my $home=homeserver($uname,$udom);
                   2630:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2631:            my @parts=split(/\//,$filename);
                   2632:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2633:            if ($path ne "$londocroot/res") {
1.8       www      2634:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2635: 	       return 'bad_request';
1.8       www      2636:            }
                   2637:            my $count;
                   2638:            for ($count=5;$count<$#parts;$count++) {
                   2639:                $path.="/$parts[$count]";
                   2640:                if ((-e $path)!=1) {
                   2641: 		   mkdir($path,0777);
                   2642:                }
                   2643:            }
                   2644:            my $ua=new LWP::UserAgent;
                   2645:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2646:            my $response=$ua->request($request,$transname);
                   2647:            if ($response->is_error()) {
                   2648: 	       unlink($transname);
                   2649:                my $message=$response->status_line;
1.672     albertel 2650:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2651:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2652:                return 'unavailable';
1.8       www      2653:            } else {
1.16      www      2654: 	       if ($remoteurl!~/\.meta$/) {
                   2655:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2656:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2657:                   if ($mresponse->is_error()) {
                   2658: 		      unlink($filename.'.meta');
                   2659:                       &logthis(
1.672     albertel 2660:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2661:                   }
                   2662: 	       }
1.8       www      2663:                rename($transname,$filename);
1.607     raeburn  2664:                return 'ok';
1.8       www      2665:            }
1.290     www      2666:        }
1.8       www      2667:     }
1.330     www      2668: }
                   2669: 
                   2670: # ------------------------------------------------ Get server side include body
                   2671: sub ssi_body {
1.381     albertel 2672:     my ($filelink,%form)=@_;
1.606     matthew  2673:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2674:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2675:     }
1.953     www      2676:     my $output='';
                   2677:     my $response;
1.980     raeburn  2678:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2679:        ($output,$response)=&externalssi($filelink);
1.953     www      2680:     } else {
1.1004    droeschl 2681:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2682:        $filelink .= 'inhibitmenu=yes';
1.953     www      2683:        ($output,$response)=&ssi($filelink,%form);
                   2684:     }
1.778     albertel 2685:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2686:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2687:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2688:     if (wantarray) {
                   2689:         return ($output, $response);
                   2690:     } else {
                   2691:         return $output;
                   2692:     }
1.8       www      2693: }
                   2694: 
1.15      www      2695: # --------------------------------------------------------- Server Side Include
                   2696: 
1.782     albertel 2697: sub absolute_url {
                   2698:     my ($host_name) = @_;
                   2699:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2700:     if ($host_name eq '') {
                   2701: 	$host_name = $ENV{'SERVER_NAME'};
                   2702:     }
                   2703:     return $protocol.$host_name;
                   2704: }
                   2705: 
1.942     foxr     2706: #
                   2707: #   Server side include.
                   2708: # Parameters:
                   2709: #  fn     Possibly encrypted resource name/id.
                   2710: #  form   Hash that describes how the rendering should be done
                   2711: #         and other things.
1.944     foxr     2712: # Returns:
1.950     raeburn  2713: #   Scalar context: The content of the response.
                   2714: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2715: #     
1.15      www      2716: sub ssi {
                   2717: 
1.944     foxr     2718:     my ($fn,%form)=@_;
1.15      www      2719:     my $ua=new LWP::UserAgent;
1.23      www      2720:     my $request;
1.711     albertel 2721: 
                   2722:     $form{'no_update_last_known'}=1;
1.895     albertel 2723:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2724:     if (%form) {
1.782     albertel 2725:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2726:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2727:     } else {
1.782     albertel 2728:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2729:     }
                   2730: 
1.15      www      2731:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2732:     my $response= $ua->request($request);
1.1182    foxr     2733:     my $content = $response->content;
                   2734: 
                   2735: 
1.944     foxr     2736:     if (wantarray) {
1.1173    foxr     2737: 	return ($content, $response);
1.944     foxr     2738:     } else {
1.1173    foxr     2739: 	return $content;
1.942     foxr     2740:     }
1.324     www      2741: }
                   2742: 
                   2743: sub externalssi {
                   2744:     my ($url)=@_;
                   2745:     my $ua=new LWP::UserAgent;
                   2746:     my $request=new HTTP::Request('GET',$url);
                   2747:     my $response=$ua->request($request);
1.954     raeburn  2748:     if (wantarray) {
                   2749:         return ($response->content, $response);
                   2750:     } else {
                   2751:         return $response->content;
                   2752:     }
1.15      www      2753: }
1.254     www      2754: 
1.492     albertel 2755: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2756: 
                   2757: sub allowuploaded {
                   2758:     my ($srcurl,$url)=@_;
                   2759:     $url=&clutter(&declutter($url));
                   2760:     my $dir=$url;
                   2761:     $dir=~s/\/[^\/]+$//;
                   2762:     my %httpref=();
                   2763:     my $httpurl=&hreflocation('',$url);
                   2764:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2765:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2766: }
1.477     raeburn  2767: 
1.1193    raeburn  2768: #
                   2769: # Determine if the current user should be able to edit a particular resource,
                   2770: # when viewing in course context.
                   2771: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2772: #     Functions.
                   2773: # (b) When displaying folder contents in course editor, used to determine if
                   2774: #     "Edit" link will be displayed alongside resource.
                   2775: #
1.1196    raeburn  2776: #  input: six args -- filename (decluttered), course number, course domain,
                   2777: #                   url, symb (if registered) and group (if this is a group
                   2778: #                   item -- e.g., bulletin board, group page etc.).
                   2779: #  output: array of five scalars -- 
1.1193    raeburn  2780: #          $cfile -- url for file editing if editable on current server
                   2781: #          $home -- homeserver of resource (i.e., for author if published,
                   2782: #                                           or course if uploaded.).
                   2783: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  2784: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   2785: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  2786: #
                   2787: 
                   2788: sub can_edit_resource {
1.1194    raeburn  2789:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2790:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2791: #
                   2792: # For aboutme pages user can only edit his/her own.
                   2793: #
1.1199    raeburn  2794:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  2795:         my ($sdom,$sname) = ($1,$2);
                   2796:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2797:             $home = $env{'user.home'};
                   2798:             $cfile = $resurl;
                   2799:             if ($env{'form.forceedit'}) {
                   2800:                 $forceview = 1;
                   2801:             } else {
                   2802:                 $forceedit = 1;
                   2803:             }
                   2804:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2805:         } else {
                   2806:             return;
                   2807:         }
                   2808:     }
                   2809: 
                   2810:     if ($env{'request.course.id'}) {
                   2811:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2812:         if ($group ne '') {
                   2813: # if this is a group homepage or group bulletin board, check group privs
                   2814:             my $allowed = 0;
1.1197    raeburn  2815:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2816:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  2817:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  2818:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2819:                     $allowed = 1;
                   2820:                 }
1.1197    raeburn  2821:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2822:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2823:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  2824:                     $allowed = 1;
                   2825:                 }
                   2826:             }
                   2827:             if ($allowed) {
                   2828:                 $home=&homeserver($cnum,$cdom);
                   2829:                 if ($env{'form.forceedit'}) {
                   2830:                     $forceview = 1;
                   2831:                 } else {
                   2832:                     $forceedit = 1;
                   2833:                 }
                   2834:                 $cfile = $resurl;
                   2835:             } else {
                   2836:                 return;
                   2837:             }
                   2838:         } else {
1.1208    raeburn  2839:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2840:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2841:                     return;
                   2842:                 }
                   2843:             } elsif (!$crsedit) {
1.1194    raeburn  2844: #
                   2845: # No edit allowed where CC has switched to student role.
                   2846: #
                   2847:                 return;
                   2848:             }
                   2849:         }
                   2850:     }
                   2851: 
1.1193    raeburn  2852:     if ($file ne '') {
                   2853:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  2854:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2855:                 $uploaded = 1;
                   2856:                 $incourse = 1;
1.1193    raeburn  2857:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2858:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  2859:                     if ($env{'form.forceedit'}) {
                   2860:                         $forceview = 1;
                   2861:                     } else {
                   2862:                         $forceedit = 1;
                   2863:                     }
1.1194    raeburn  2864:                 }
                   2865:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2866:                 $incourse = 1;
                   2867:                 if ($env{'form.forceedit'}) {
                   2868:                     $forceview = 1;
                   2869:                 } else {
                   2870:                     $forceedit = 1;
                   2871:                 }
                   2872:                 $cfile = $resurl;
                   2873:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   2874:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2875:                     $incourse = 1;
                   2876:                     if ($env{'form.forceedit'}) {
                   2877:                         $forceview = 1;
                   2878:                     } else {
                   2879:                         $forceedit = 1;
                   2880:                     }
                   2881:                     $cfile = $resurl;
1.1199    raeburn  2882:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  2883:                     $incourse = 1;
                   2884:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  2885:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  2886:                     $incourse = 1;
1.1199    raeburn  2887:                     if ($env{'form.forceedit'}) {
                   2888:                         $forceview = 1;
                   2889:                     } else {
                   2890:                         $forceedit = 1;
                   2891:                     }
                   2892:                     $cfile = $resurl;
1.1208    raeburn  2893:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2894:                     $incourse = 1;
                   2895:                     if ($env{'form.forceedit'}) {
                   2896:                         $forceview = 1;
                   2897:                     } else {
                   2898:                         $forceedit = 1;
                   2899:                     }
                   2900:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  2901:                 }
                   2902:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2903:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2904:                 if (&is_on_map($template)) { 
                   2905:                     $incourse = 1;
                   2906:                     $forceview = 1;
                   2907:                     $cfile = $template;
1.1193    raeburn  2908:                 }
1.1199    raeburn  2909:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2910:                     $incourse = 1;
                   2911:                     if ($env{'form.forceedit'}) {
                   2912:                         $forceview = 1;
                   2913:                     } else {
                   2914:                         $forceedit = 1;
                   2915:                     }
                   2916:                     $cfile = $resurl;
                   2917:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2918:                 $incourse = 1;
                   2919:                 $forceview = 1;
                   2920:                 if ($symb) {
                   2921:                     my ($map,$id,$res)=&decode_symb($symb);
                   2922:                     $env{'request.symb'} = $symb;
                   2923:                     $cfile = &clutter($res);
                   2924:                 } else {
                   2925:                     $cfile = $env{'form.suppurl'};
                   2926:                     $cfile =~ s{^http://}{};
                   2927:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2928:                 }
1.1234    raeburn  2929:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2930:                 if ($env{'form.forceedit'}) {
                   2931:                     $forceview = 1;
                   2932:                 } else {
                   2933:                     $forceedit = 1;
                   2934:                 }
                   2935:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  2936:             }
                   2937:         }
1.1194    raeburn  2938:         if ($uploaded || $incourse) {
                   2939:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  2940:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  2941:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2942:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2943:             # Check that the user has permission to edit this resource
                   2944:             my $setpriv = 1;
                   2945:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2946:             if (defined($cfudom)) {
                   2947:                 $home=&homeserver($cfuname,$cfudom);
                   2948:                 $cfile=$file;
                   2949:             }
                   2950:         }
1.1194    raeburn  2951:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   2952:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  2953:             my @ids=&current_machine_ids();
                   2954:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2955:                 $switchserver=1;
                   2956:             }
                   2957:         }
                   2958:     }
1.1194    raeburn  2959:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  2960: }
                   2961: 
                   2962: sub is_course_upload {
                   2963:     my ($file,$cnum,$cdom) = @_;
                   2964:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2965:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  2966:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2967:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  2968:         return 1;
                   2969:     }
                   2970:     return;
                   2971: }
                   2972: 
1.1194    raeburn  2973: sub in_course {
1.1195    raeburn  2974:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2975:     if ($hideprivileged) {
                   2976:         my $skipuser;
1.1219    raeburn  2977:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2978:         my @possdoms = ($cdom);  
                   2979:         if ($coursehash{'checkforpriv'}) { 
                   2980:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   2981:         }
                   2982:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  2983:             $skipuser = 1;
                   2984:             if ($coursehash{'nothideprivileged'}) {
                   2985:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2986:                     my $user;
                   2987:                     if ($item =~ /:/) {
                   2988:                         $user = $item;
                   2989:                     } else {
                   2990:                         $user = join(':',split(/[\@]/,$item));
                   2991:                     }
                   2992:                     if ($user eq $uname.':'.$udom) {
                   2993:                         undef($skipuser);
                   2994:                         last;
                   2995:                     }
                   2996:                 }
                   2997:             }
                   2998:             if ($skipuser) {
                   2999:                 return 0;
                   3000:             }
                   3001:         }
                   3002:     }
1.1194    raeburn  3003:     $type ||= 'any';
                   3004:     if (!defined($cdom) || !defined($cnum)) {
                   3005:         my $cid  = $env{'request.course.id'};
                   3006:         $cdom = $env{'course.'.$cid.'.domain'};
                   3007:         $cnum = $env{'course.'.$cid.'.num'};
                   3008:     }
                   3009:     my $typesref;
1.1195    raeburn  3010:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3011:         $typesref = ['active','previous','future'];
                   3012:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3013:         $typesref = [$type];
                   3014:     }
                   3015:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3016:                               $typesref,undef,[$cdom]);
                   3017:     my ($tmp) = keys(%roles);
                   3018:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3019:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3020:     if (@course_roles > 0) {
                   3021:         return 1;
                   3022:     }
                   3023:     return 0;
                   3024: }
                   3025: 
1.478     albertel 3026: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3027: # input: action, courseID, current domain, intended
1.637     raeburn  3028: #        path to file, source of file, instruction to parse file for objects,
                   3029: #        ref to hash for embedded objects,
                   3030: #        ref to hash for codebase of java objects.
1.1095    raeburn  3031: #        reference to scalar to accommodate mime type determined
                   3032: #          from File::MMagic if $parser = parse.
1.637     raeburn  3033: #
1.485     raeburn  3034: # output: url to file (if action was uploaddoc), 
                   3035: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3036: #
1.478     albertel 3037: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3038: # course.
1.477     raeburn  3039: #
1.478     albertel 3040: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3041: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3042: #          course's home server.
1.477     raeburn  3043: #
1.478     albertel 3044: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3045: #          be copied from $source (current location) to 
                   3046: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3047: #         and will then be copied to
                   3048: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3049: #         course's home server.
1.485     raeburn  3050: #
1.481     raeburn  3051: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3052: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3053: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3054: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3055: #         in course's home server.
1.637     raeburn  3056: #
1.477     raeburn  3057: 
                   3058: sub process_coursefile {
1.1095    raeburn  3059:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3060:         $mimetype)=@_;
1.477     raeburn  3061:     my $fetchresult;
1.638     albertel 3062:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3063:     if ($action eq 'propagate') {
1.638     albertel 3064:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3065: 			     $home);
1.481     raeburn  3066:     } else {
1.477     raeburn  3067:         my $fpath = '';
                   3068:         my $fname = $file;
1.478     albertel 3069:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3070:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3071:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3072:         if ($action eq 'copy') {
                   3073:             if ($source eq '') {
                   3074:                 $fetchresult = 'no source file';
                   3075:                 return $fetchresult;
                   3076:             } else {
                   3077:                 my $destination = $filepath.'/'.$fname;
                   3078:                 rename($source,$destination);
                   3079:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3080:                                  $home);
1.481     raeburn  3081:             }
                   3082:         } elsif ($action eq 'uploaddoc') {
                   3083:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3084:             print $fh $env{'form.'.$source};
1.481     raeburn  3085:             close($fh);
1.637     raeburn  3086:             if ($parser eq 'parse') {
1.1024    raeburn  3087:                 my $mm = new File::MMagic;
1.1095    raeburn  3088:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3089:                 if ($type eq 'text/html') {
1.1024    raeburn  3090:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3091:                     unless ($parse_result eq 'ok') {
                   3092:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3093:                     }
1.637     raeburn  3094:                 }
1.1095    raeburn  3095:                 if (ref($mimetype)) {
                   3096:                     $$mimetype = $type;
                   3097:                 } 
1.637     raeburn  3098:             }
1.477     raeburn  3099:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3100:                                  $home);
1.481     raeburn  3101:             if ($fetchresult eq 'ok') {
                   3102:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3103:             } else {
                   3104:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3105:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3106:                 return '/adm/notfound.html';
                   3107:             }
1.477     raeburn  3108:         }
                   3109:     }
1.485     raeburn  3110:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3111:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3112:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3113:     }
                   3114:     return $fetchresult;
                   3115: }
                   3116: 
1.637     raeburn  3117: sub build_filepath {
                   3118:     my ($fpath) = @_;
                   3119:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3120:     unless ($fpath eq '') {
                   3121:         my @parts=split('/',$fpath);
                   3122:         foreach my $part (@parts) {
                   3123:             $filepath.= '/'.$part;
                   3124:             if ((-e $filepath)!=1) {
                   3125:                 mkdir($filepath,0777);
                   3126:             }
                   3127:         }
                   3128:     }
                   3129:     return $filepath;
                   3130: }
                   3131: 
                   3132: sub store_edited_file {
1.638     albertel 3133:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3134:     my $file = $primary_url;
                   3135:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3136:     my $fpath = '';
                   3137:     my $fname = $file;
                   3138:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3139:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3140:     my $filepath = &build_filepath($fpath);
                   3141:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3142:     print $fh $content;
                   3143:     close($fh);
1.638     albertel 3144:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3145:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3146: 			  $home);
1.637     raeburn  3147:     if ($$fetchresult eq 'ok') {
                   3148:         return '/uploaded/'.$fpath.'/'.$fname;
                   3149:     } else {
1.638     albertel 3150:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3151: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3152:         return '/adm/notfound.html';
                   3153:     }
                   3154: }
                   3155: 
1.531     albertel 3156: sub clean_filename {
1.831     albertel 3157:     my ($fname,$args)=@_;
1.315     www      3158: # Replace Windows backslashes by forward slashes
1.257     www      3159:     $fname=~s/\\/\//g;
1.831     albertel 3160:     if (!$args->{'keep_path'}) {
                   3161:         # Get rid of everything but the actual filename
                   3162: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3163:     }
1.315     www      3164: # Replace spaces by underscores
                   3165:     $fname=~s/\s+/\_/g;
                   3166: # Replace all other weird characters by nothing
1.831     albertel 3167:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3168: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3169: # numbers
                   3170:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3171:     return $fname;
                   3172: }
1.1051    raeburn  3173: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3174: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3175: # image with the same aspect ratio as the original, but with dimensions which do 
                   3176: # not exceed $resizewidth and $resizeheight.
                   3177:  
1.984     neumanie 3178: sub resizeImage {
1.1051    raeburn  3179:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3180:     my $ima = Image::Magick->new;
                   3181:     my $resized;
                   3182:     if (-e $img_path) {
                   3183:         $ima->Read($img_path);
                   3184:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3185:             my $width = $ima->Get('width');
                   3186:             my $height = $ima->Get('height');
                   3187:             if ($width > $resizewidth) {
                   3188: 	        my $factor = $width/$resizewidth;
                   3189:                 my $newheight = $height/$factor;
                   3190:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3191:                 $resized = 1;
                   3192:             }
                   3193:         }
                   3194:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3195:             my $width = $ima->Get('width');
                   3196:             my $height = $ima->Get('height');
                   3197:             if ($height > $resizeheight) {
                   3198:                 my $factor = $height/$resizeheight;
                   3199:                 my $newwidth = $width/$factor;
                   3200:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3201:                 $resized = 1;
                   3202:             }
                   3203:         }
                   3204:         if ($resized) {
                   3205:             $ima->Write($img_path);
                   3206:         }
                   3207:     }
                   3208:     return;
1.977     amueller 3209: }
                   3210: 
1.608     albertel 3211: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3212: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3213: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3214: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3215: #                                    canceloverwrite, or ''. 
                   3216: #                   if 'coursedoc': upload to the current course
                   3217: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3218: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3219: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3220: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3221: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3222: #        $allfiles - reference to hash for embedded objects
                   3223: #        $codebase - reference to hash for codebase of java objects
                   3224: #        $desuname - username for permanent storage of uploaded file
                   3225: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3226: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3227: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3228: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3229: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3230: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3231: #                    from File::MMagic.
1.858     raeburn  3232: # 
1.686     albertel 3233: # output: url of file in userspace, or error: <message> 
                   3234: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3235: 
1.531     albertel 3236: sub userfileupload {
1.1090    raeburn  3237:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3238:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3239:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3240:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3241:     $fname=&clean_filename($fname);
1.1090    raeburn  3242:     # See if there is anything left
1.257     www      3243:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3244:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3245:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3246:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3247:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3248:         my $now = time;
1.1090    raeburn  3249:         my $filepath;
1.1095    raeburn  3250:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3251:              $filepath = 'tmp/helprequests/'.$now;
                   3252:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3253:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3254:                          '_'.$env{'user.domain'}.'/pending';
                   3255:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3256:             my ($docuname,$docudom);
                   3257:             if ($destudom) {
                   3258:                 $docudom = $destudom;
                   3259:             } else {
                   3260:                 $docudom = $env{'user.domain'};
                   3261:             }
                   3262:             if ($destuname) {
                   3263:                 $docuname = $destuname;
                   3264:             } else {
                   3265:                 $docuname = $env{'user.name'};
                   3266:             }
                   3267:             if (exists($env{'form.group'})) {
                   3268:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3269:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3270:             }
                   3271:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3272:             if ($context eq 'canceloverwrite') {
                   3273:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3274:                 if (-e  $tempfile) {
                   3275:                     my @info = stat($tempfile);
                   3276:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3277:                         unlink($tempfile);
                   3278:                     }
                   3279:                 }
                   3280:                 return;
1.523     raeburn  3281:             }
                   3282:         }
1.1090    raeburn  3283:         # Create the directory if not present
1.741     raeburn  3284:         my @parts=split(/\//,$filepath);
                   3285:         my $fullpath = $perlvar{'lonDaemons'};
                   3286:         for (my $i=0;$i<@parts;$i++) {
                   3287:             $fullpath .= '/'.$parts[$i];
                   3288:             if ((-e $fullpath)!=1) {
                   3289:                 mkdir($fullpath,0777);
                   3290:             }
                   3291:         }
                   3292:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3293:         print $fh $env{'form.'.$formname};
                   3294:         close($fh);
1.1090    raeburn  3295:         if ($context eq 'existingfile') {
                   3296:             my @info = stat($fullpath.'/'.$fname);
                   3297:             return ($fullpath.'/'.$fname,$info[9]);
                   3298:         } else {
                   3299:             return $fullpath.'/'.$fname;
                   3300:         }
1.523     raeburn  3301:     }
1.995     raeburn  3302:     if ($subdir eq 'scantron') {
                   3303:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3304:     } else {
1.995     raeburn  3305:         $fname="$subdir/$fname";
                   3306:     }
1.1090    raeburn  3307:     if ($context eq 'coursedoc') {
1.638     albertel 3308: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3309: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3310:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3311:             return &finishuserfileupload($docuname,$docudom,
                   3312: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3313: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3314:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3315:         } else {
1.1218    raeburn  3316:             if ($env{'form.folder'}) {
                   3317:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3318:             }
1.638     albertel 3319:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3320: 				       $fname,$formname,$parser,
1.1095    raeburn  3321: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3322:         }
1.719     banghart 3323:     } elsif (defined($destuname)) {
                   3324:         my $docuname=$destuname;
                   3325:         my $docudom=$destudom;
1.860     raeburn  3326: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3327: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3328:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3329:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3330:     } else {
1.638     albertel 3331:         my $docuname=$env{'user.name'};
                   3332:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3333:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3334:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3335:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3336:         }
1.860     raeburn  3337: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3338: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3339:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3340:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3341:     }
1.271     www      3342: }
                   3343: 
                   3344: sub finishuserfileupload {
1.860     raeburn  3345:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3346:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3347:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3348:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3349:   
1.860     raeburn  3350:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3351:     $file=$fname;
                   3352:     if ($fname=~m|/|) {
                   3353:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3354: 	$path.=$fnamepath.'/';
                   3355:     }
1.259     www      3356:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3357:     my $count;
                   3358:     for ($count=4;$count<=$#parts;$count++) {
                   3359:         $filepath.="/$parts[$count]";
                   3360:         if ((-e $filepath)!=1) {
                   3361: 	    mkdir($filepath,0777);
                   3362:         }
                   3363:     }
1.984     neumanie 3364: 
1.258     www      3365: # Save the file
                   3366:     {
1.701     albertel 3367: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3368: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3369: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3370: 	    return '/adm/notfound.html';
                   3371: 	}
1.1090    raeburn  3372:         if ($context eq 'overwrite') {
1.1117    foxr     3373:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3374:             my $target = $filepath.'/'.$file;
                   3375:             if (-e $source) {
                   3376:                 my @info = stat($source);
                   3377:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3378:                     unless (&File::Copy::move($source,$target)) {
                   3379:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3380:                         return "Moving from $source failed";
                   3381:                     }
                   3382:                 } else {
                   3383:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3384:                 }
                   3385:             } else {
                   3386:                 return "Temporary file: $source missing";
                   3387:             }
                   3388:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3389: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3390: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3391: 	    return '/adm/notfound.html';
                   3392: 	}
1.570     albertel 3393: 	close(FH);
1.1051    raeburn  3394:         if ($resizewidth && $resizeheight) {
                   3395:             my $mm = new File::MMagic;
                   3396:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3397:             if ($mime_type =~ m{^image/}) {
                   3398: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3399:             }  
1.977     amueller 3400: 	}
1.258     www      3401:     }
1.1152    raeburn  3402:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3403:         if (ref($mimetype)) {
                   3404:             if ($$mimetype eq '') {
                   3405:                 my $mm = new File::MMagic;
                   3406:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3407:                 $$mimetype = $type;
                   3408:             }
                   3409:         }
                   3410:     }
1.637     raeburn  3411:     if ($parser eq 'parse') {
1.1152    raeburn  3412:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3413:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3414:                                                        $allfiles,$codebase);
                   3415:             unless ($parse_result eq 'ok') {
                   3416:                 &logthis('Failed to parse '.$filepath.$file.
                   3417: 	   	         ' for embedded media: '.$parse_result); 
                   3418:             }
1.637     raeburn  3419:         }
                   3420:     }
1.860     raeburn  3421:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3422:         my $input = $filepath.'/'.$file;
                   3423:         my $output = $filepath.'/'.'tn-'.$file;
                   3424:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3425:         system("convert -sample $thumbsize $input $output");
                   3426:         if (-e $filepath.'/'.'tn-'.$file) {
                   3427:             $fetchthumb  = 1; 
                   3428:         }
                   3429:     }
1.858     raeburn  3430:  
1.259     www      3431: # Notify homeserver to grep it
                   3432: #
1.984     neumanie 3433:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3434:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3435:     if ($fetchresult eq 'ok') {
1.860     raeburn  3436:         if ($fetchthumb) {
                   3437:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3438:             if ($thumbresult ne 'ok') {
                   3439:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3440:                          $docuhome.': '.$thumbresult);
                   3441:             }
                   3442:         }
1.259     www      3443: #
1.258     www      3444: # Return the URL to it
1.494     albertel 3445:         return '/uploaded/'.$path.$file;
1.263     www      3446:     } else {
1.494     albertel 3447:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3448: 		 ': '.$fetchresult);
1.263     www      3449:         return '/adm/notfound.html';
1.858     raeburn  3450:     }
1.493     albertel 3451: }
                   3452: 
1.637     raeburn  3453: sub extract_embedded_items {
1.961     raeburn  3454:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3455:     my @state = ();
1.1164    raeburn  3456:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3457:     my %javafiles = (
                   3458:                       codebase => '',
                   3459:                       code => '',
                   3460:                       archive => ''
                   3461:                     );
                   3462:     my %mediafiles = (
                   3463:                       src => '',
                   3464:                       movie => '',
                   3465:                      );
1.648     raeburn  3466:     my $p;
                   3467:     if ($content) {
                   3468:         $p = HTML::LCParser->new($content);
                   3469:     } else {
1.961     raeburn  3470:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3471:     }
1.641     albertel 3472:     while (my $t=$p->get_token()) {
1.640     albertel 3473: 	if ($t->[0] eq 'S') {
                   3474: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3475: 	    push(@state, $tagname);
1.648     raeburn  3476:             if (lc($tagname) eq 'allow') {
                   3477:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3478:             }
1.640     albertel 3479: 	    if (lc($tagname) eq 'img') {
                   3480: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3481: 	    }
1.886     albertel 3482: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3483:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3484:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3485:                 }
1.886     albertel 3486: 	    }
1.645     raeburn  3487:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3488:                 my $src;
1.645     raeburn  3489:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3490:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3491:                 } else {
1.1164    raeburn  3492:                     if ($attr->{'src'} ne '') {
                   3493:                         $src = $attr->{'src'};
                   3494:                         &add_filetype($allfiles,$src,'src');
                   3495:                     }
                   3496:                 }
                   3497:                 my $text = $p->get_trimmed_text();
                   3498:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3499:                     my @swfargs = split(/,/,$1);
                   3500:                     foreach my $item (@swfargs) {
                   3501:                         $item =~ s/["']//g;
                   3502:                         $item =~ s/^\s+//;
                   3503:                         $item =~ s/\s+$//;
                   3504:                     }
                   3505:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3506:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3507:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3508:                         } else {
                   3509:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3510:                         }
                   3511:                     }
1.645     raeburn  3512:                 }
                   3513:             }
                   3514:             if (lc($tagname) eq 'link') {
                   3515:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3516:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3517:                 }
                   3518:             }
1.640     albertel 3519: 	    if (lc($tagname) eq 'object' ||
                   3520: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3521: 		foreach my $item (keys(%javafiles)) {
                   3522: 		    $javafiles{$item} = '';
                   3523: 		}
1.1164    raeburn  3524:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3525:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3526:                 }
1.640     albertel 3527: 	    }
                   3528: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3529: 		my $name = lc($attr->{'name'});
                   3530: 		foreach my $item (keys(%javafiles)) {
                   3531: 		    if ($name eq $item) {
                   3532: 			$javafiles{$item} = $attr->{'value'};
                   3533: 			last;
                   3534: 		    }
                   3535: 		}
1.1164    raeburn  3536:                 my $pathfrom;
1.640     albertel 3537: 		foreach my $item (keys(%mediafiles)) {
                   3538: 		    if ($name eq $item) {
1.1164    raeburn  3539:                         $pathfrom = $attr->{'value'};
                   3540:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3541: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3542: 			last;
                   3543: 		    }
                   3544: 		}
1.1164    raeburn  3545:                 if ($name eq 'flashvars') {
                   3546:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3547:                 }
                   3548:                 if ($pathfrom ne '') {
                   3549:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3550:                                          $pathfrom);
                   3551:                 }
1.640     albertel 3552: 	    }
                   3553: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3554: 		foreach my $item (keys(%javafiles)) {
                   3555: 		    if ($attr->{$item}) {
                   3556: 			$javafiles{$item} = $attr->{$item};
                   3557: 			last;
                   3558: 		    }
                   3559: 		}
                   3560: 		foreach my $item (keys(%mediafiles)) {
                   3561: 		    if ($attr->{$item}) {
                   3562: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3563: 			last;
                   3564: 		    }
                   3565: 		}
1.1164    raeburn  3566:                 if (lc($tagname) eq 'embed') {
                   3567:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3568:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3569:                                              $attr->{'src'});
                   3570:                     }
                   3571:                 }
1.640     albertel 3572: 	    }
1.1243    raeburn  3573:             if (lc($tagname) eq 'iframe') {
                   3574:                 my $src = $attr->{'src'} ;
                   3575:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3576:                     &add_filetype($allfiles,$src,'src');
                   3577:                 } elsif ($src =~ m{^/}) {
                   3578:                     if ($env{'request.course.id'}) {
                   3579:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3580:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3581:                         my $url = &hreflocation('',$fullpath);
                   3582:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3583:                             my $relpath = $1;
                   3584:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3585:                                 &add_filetype($allfiles,$1,'src');
                   3586:                             }
                   3587:                         }
                   3588:                     }
                   3589:                 }
                   3590:             }
1.1164    raeburn  3591:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3592:                 pop(@state);
1.1164    raeburn  3593:             }
1.640     albertel 3594: 	} elsif ($t->[0] eq 'E') {
                   3595: 	    my ($tagname) = ($t->[1]);
                   3596: 	    if ($javafiles{'codebase'} ne '') {
                   3597: 		$javafiles{'codebase'} .= '/';
                   3598: 	    }  
                   3599: 	    if (lc($tagname) eq 'applet' ||
                   3600: 		lc($tagname) eq 'object' ||
                   3601: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3602: 		) {
                   3603: 		foreach my $item (keys(%javafiles)) {
                   3604: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3605: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3606: 			&add_filetype($allfiles,$file,$item);
                   3607: 		    }
                   3608: 		}
                   3609: 	    } 
                   3610: 	    pop @state;
                   3611: 	}
                   3612:     }
1.1164    raeburn  3613:     foreach my $id (sort(keys(%flashvars))) {
                   3614:         if ($shockwave{$id} ne '') {
                   3615:             my @pairs = split(/\&/,$flashvars{$id});
                   3616:             foreach my $pair (@pairs) {
                   3617:                 my ($key,$value) = split(/\=/,$pair);
                   3618:                 if ($key eq 'thumb') {
                   3619:                     &add_filetype($allfiles,$value,$key);
                   3620:                 } elsif ($key eq 'content') {
                   3621:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3622:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3623:                     if ($ext ne '') {
                   3624:                         &add_filetype($allfiles,$path.$value,$ext);
                   3625:                     }
                   3626:                 }
                   3627:             }
                   3628:         }
                   3629:     }
1.637     raeburn  3630:     return 'ok';
                   3631: }
                   3632: 
1.639     albertel 3633: sub add_filetype {
                   3634:     my ($allfiles,$file,$type)=@_;
                   3635:     if (exists($allfiles->{$file})) {
                   3636: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3637: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3638: 	}
                   3639:     } else {
                   3640: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3641:     }
                   3642: }
                   3643: 
1.1164    raeburn  3644: sub embedded_dependency {
                   3645:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3646:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3647:         if (($identifier ne '') &&
                   3648:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3649:             ($pathfrom ne '')) {
                   3650:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3651:             foreach my $dep (@{$related->{$identifier}}) {
                   3652:                 &add_filetype($allfiles,$path.$dep,'object');
                   3653:             }
                   3654:         }
                   3655:     }
                   3656:     return;
                   3657: }
                   3658: 
1.493     albertel 3659: sub removeuploadedurl {
1.984     neumanie 3660:     my ($url)=@_;	
                   3661:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3662:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3663: }
                   3664: 
                   3665: sub removeuserfile {
                   3666:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3667:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3668:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3669:     if ($result eq 'ok') {	
1.798     raeburn  3670:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3671:             my $metafile = $fname.'.meta';
                   3672:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3673: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3674:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3675:             my $sqlresult = 
1.823     albertel 3676:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3677:                                         'portfolio_metadata',$group,
                   3678:                                         'delete');
1.798     raeburn  3679:         }
                   3680:     }
                   3681:     return $result;
1.257     www      3682: }
1.15      www      3683: 
1.530     albertel 3684: sub mkdiruserfile {
                   3685:     my ($docuname,$docudom,$dir)=@_;
                   3686:     my $home=&homeserver($docuname,$docudom);
                   3687:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3688: }
                   3689: 
1.531     albertel 3690: sub renameuserfile {
                   3691:     my ($docuname,$docudom,$old,$new)=@_;
                   3692:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3693:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3694:                         &escape("$old").':'.&escape("$new"),$home);
                   3695:     if ($result eq 'ok') {
                   3696:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3697:             my $oldmeta = $old.'.meta';
                   3698:             my $newmeta = $new.'.meta';
                   3699:             my $metaresult = 
                   3700:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3701: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3702:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3703:             my $sqlresult = 
1.823     albertel 3704:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3705:                                         'portfolio_metadata',$group,
                   3706:                                         'delete');
1.798     raeburn  3707:         }
                   3708:     }
                   3709:     return $result;
1.531     albertel 3710: }
                   3711: 
1.14      www      3712: # ------------------------------------------------------------------------- Log
                   3713: 
                   3714: sub log {
                   3715:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3716:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3717: }
                   3718: 
                   3719: # ------------------------------------------------------------------ Course Log
1.352     www      3720: #
                   3721: # This routine flushes several buffers of non-mission-critical nature
                   3722: #
1.157     www      3723: 
                   3724: sub flushcourselogs {
1.352     www      3725:     &logthis('Flushing log buffers');
                   3726: #
                   3727: # course logs
                   3728: # This is a log of all transactions in a course, which can be used
                   3729: # for data mining purposes
                   3730: #
                   3731: # It also collects the courseid database, which lists last transaction
                   3732: # times and course titles for all courseids
                   3733: #
                   3734:     my %courseidbuffer=();
1.921     raeburn  3735:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3736:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3737: 		          &escape($courselogs{$crsid}),
                   3738: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3739: 	    delete $courselogs{$crsid};
                   3740:         } else {
                   3741:             &logthis('Failed to flush log buffer for '.$crsid);
                   3742:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3743:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3744:                         " exceeded maximum size, deleting.</font>");
                   3745:                delete $courselogs{$crsid};
                   3746:             }
1.352     www      3747:         }
1.920     raeburn  3748:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3749:             'description' => $coursedescrbuf{$crsid},
                   3750:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3751:             'type'        => $coursetypebuf{$crsid},
                   3752:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3753:         };
1.191     harris41 3754:     }
1.352     www      3755: #
                   3756: # Write course id database (reverse lookup) to homeserver of courses 
                   3757: # Is used in pickcourse
                   3758: #
1.840     albertel 3759:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3760:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3761:                                     $courseidbuffer{$crs_home},
                   3762:                                     $crs_home,'timeonly');
1.352     www      3763:     }
                   3764: #
                   3765: # File accesses
                   3766: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3767: #
1.449     matthew  3768:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3769:         if ($entry =~ /___count$/) {
                   3770:             my ($dom,$name);
1.807     albertel 3771:             ($dom,$name,undef)=
1.811     albertel 3772: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3773:             if (! defined($dom) || $dom eq '' || 
                   3774:                 ! defined($name) || $name eq '') {
1.620     albertel 3775:                 my $cid = $env{'request.course.id'};
                   3776:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3777:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3778:             }
1.450     matthew  3779:             my $value = $accesshash{$entry};
                   3780:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3781:             my %temphash=($url => $value);
1.449     matthew  3782:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3783:             if ($result eq 'ok') {
                   3784:                 delete $accesshash{$entry};
                   3785:             }
                   3786:         } else {
1.811     albertel 3787:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3788:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3789:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3790:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3791:                 delete $accesshash{$entry};
                   3792:             }
1.185     www      3793:         }
1.191     harris41 3794:     }
1.352     www      3795: #
                   3796: # Roles
                   3797: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3798: #
1.800     albertel 3799:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3800:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3801: 	    split(/\:/,$entry);
                   3802:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3803:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3804:                 $rudom,$runame) eq 'ok') {
                   3805: 	    delete $userrolehash{$entry};
                   3806:         }
                   3807:     }
1.662     raeburn  3808: #
                   3809: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3810: #
                   3811:     my %domrolebuffer = ();
1.1000    raeburn  3812:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3813:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3814:         if ($domrolebuffer{$rudom}) {
                   3815:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3816:                       '='.&escape($domainrolehash{$entry});
                   3817:         } else {
                   3818:             $domrolebuffer{$rudom}.=&escape($entry).
                   3819:                       '='.&escape($domainrolehash{$entry});
                   3820:         }
                   3821:         delete $domainrolehash{$entry};
                   3822:     }
                   3823:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3824: 	my %servers = &get_servers($dom,'library');
                   3825: 	foreach my $tryserver (keys(%servers)) {
                   3826: 	    unless (&reply('domroleput:'.$dom.':'.
                   3827: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3828: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3829: 	    }
1.662     raeburn  3830:         }
                   3831:     }
1.186     www      3832:     $dumpcount++;
1.157     www      3833: }
                   3834: 
                   3835: sub courselog {
                   3836:     my $what=shift;
1.158     www      3837:     $what=time.':'.$what;
1.620     albertel 3838:     unless ($env{'request.course.id'}) { return ''; }
                   3839:     $coursedombuf{$env{'request.course.id'}}=
                   3840:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3841:     $coursenumbuf{$env{'request.course.id'}}=
                   3842:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3843:     $coursehombuf{$env{'request.course.id'}}=
                   3844:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3845:     $coursedescrbuf{$env{'request.course.id'}}=
                   3846:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3847:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3848:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3849:     $courseownerbuf{$env{'request.course.id'}}=
                   3850:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3851:     $coursetypebuf{$env{'request.course.id'}}=
                   3852:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3853:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3854: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3855:     } else {
1.620     albertel 3856: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3857:     }
1.620     albertel 3858:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3859: 	&flushcourselogs();
                   3860:     }
1.158     www      3861: }
                   3862: 
                   3863: sub courseacclog {
                   3864:     my $fnsymb=shift;
1.620     albertel 3865:     unless ($env{'request.course.id'}) { return ''; }
                   3866:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3867:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3868:         $what.=':POST';
1.583     matthew  3869:         # FIXME: Probably ought to escape things....
1.800     albertel 3870: 	foreach my $key (keys(%env)) {
                   3871:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3872:                 my $formitem = $1;
                   3873:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3874:                     $what.=':'.$formitem.'='.$env{$key};
                   3875:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3876:                     $what.=':'.$formitem.'='.$env{$key};
                   3877:                 }
1.158     www      3878:             }
1.191     harris41 3879:         }
1.583     matthew  3880:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3881:         # FIXME: We should not be depending on a form parameter that someone
                   3882:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3883:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3884:             $what.= ':POST';
                   3885:             # FIXME: Probably ought to escape things....
                   3886:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3887:                                  'crsdiscuss') {
1.620     albertel 3888:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3889:             }
                   3890:         }
1.158     www      3891:     }
                   3892:     &courselog($what);
1.149     www      3893: }
                   3894: 
1.185     www      3895: sub countacc {
                   3896:     my $url=&declutter(shift);
1.458     matthew  3897:     return if (! defined($url) || $url eq '');
1.620     albertel 3898:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3899: #
                   3900: # Mark that this url was used in this course
                   3901: #
1.620     albertel 3902:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3903: #
                   3904: # Increase the access count for this resource in this child process
                   3905: #
1.281     www      3906:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3907:     $accesshash{$key}++;
1.185     www      3908: }
1.349     www      3909: 
1.361     www      3910: sub linklog {
                   3911:     my ($from,$to)=@_;
                   3912:     $from=&declutter($from);
                   3913:     $to=&declutter($to);
                   3914:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3915:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3916: }
1.1160    www      3917: 
                   3918: sub statslog {
                   3919:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3920:     if ($users<2) { return; }
                   3921:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3922:             'course'       => $env{'request.course.id'},
                   3923:             'sections'     => '"all"',
                   3924:             'num_students' => $users,
                   3925:             'part'         => $part,
                   3926:             'symb'         => $symb,
                   3927:             'mean_tries'   => $av_attempts,
                   3928:             'deg_of_diff'  => $degdiff});
                   3929:     foreach my $key (keys(%dynstore)) {
                   3930:         $accesshash{$key}=$dynstore{$key};
                   3931:     }
                   3932: }
1.361     www      3933:   
1.349     www      3934: sub userrolelog {
                   3935:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3936:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3937:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3938:        $userrolehash
                   3939:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3940:                     =$tend.':'.$tstart;
1.662     raeburn  3941:     }
1.1169    droeschl 3942:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3943:        $userrolehash
                   3944:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3945:                     =$tend.':'.$tstart;
                   3946:     }
1.1169    droeschl 3947:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3948:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3949:        $domainrolehash
                   3950:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3951:                     = $tend.':'.$tstart;
                   3952:     }
1.351     www      3953: }
                   3954: 
1.957     raeburn  3955: sub courserolelog {
                   3956:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  3957:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3958:         my $cdom = $1;
                   3959:         my $cnum = $2;
                   3960:         my $sec = $3;
                   3961:         my $namespace = 'rolelog';
                   3962:         my %storehash = (
                   3963:                            role    => $trole,
                   3964:                            start   => $tstart,
                   3965:                            end     => $tend,
                   3966:                            selfenroll => $selfenroll,
                   3967:                            context    => $context,
                   3968:                         );
                   3969:         if ($trole eq 'gr') {
                   3970:             $namespace = 'groupslog';
                   3971:             $storehash{'group'} = $sec;
                   3972:         } else {
                   3973:             $storehash{'section'} = $sec;
                   3974:         }
1.1188    raeburn  3975:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3976:                    $domain,$cnum,$cdom);
1.1184    raeburn  3977:         if (($trole ne 'st') || ($sec ne '')) {
                   3978:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3979:         }
                   3980:     }
                   3981:     return;
                   3982: }
                   3983: 
1.1184    raeburn  3984: sub domainrolelog {
                   3985:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3986:     if ($area =~ m{^/($match_domain)/$}) {
                   3987:         my $cdom = $1;
                   3988:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3989:         my $namespace = 'rolelog';
                   3990:         my %storehash = (
                   3991:                            role    => $trole,
                   3992:                            start   => $tstart,
                   3993:                            end     => $tend,
                   3994:                            context => $context,
                   3995:                         );
1.1188    raeburn  3996:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3997:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  3998:     }
                   3999:     return;
                   4000: 
                   4001: }
                   4002: 
                   4003: sub coauthorrolelog {
                   4004:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4005:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4006:         my $audom = $1;
                   4007:         my $auname = $2;
                   4008:         my $namespace = 'rolelog';
                   4009:         my %storehash = (
                   4010:                            role    => $trole,
                   4011:                            start   => $tstart,
                   4012:                            end     => $tend,
                   4013:                            context => $context,
                   4014:                         );
1.1188    raeburn  4015:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4016:                    $domain,$auname,$audom);
1.1184    raeburn  4017:     }
                   4018:     return;
                   4019: }
                   4020: 
1.351     www      4021: sub get_course_adv_roles {
1.948     raeburn  4022:     my ($cid,$codes) = @_;
1.620     albertel 4023:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4024:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4025:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4026:     my %nothide=();
1.800     albertel 4027:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4028:         if ($user !~ /:/) {
                   4029: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4030:         } else {
                   4031:             $nothide{$user}=1;
                   4032:         }
1.470     www      4033:     }
1.1219    raeburn  4034:     my @possdoms = ($coursehash{'domain'});
                   4035:     if ($coursehash{'checkforpriv'}) {
                   4036:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4037:     }
1.351     www      4038:     my %returnhash=();
                   4039:     my %dumphash=
                   4040:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4041:     my $now=time;
1.997     raeburn  4042:     my %privileged;
1.1000    raeburn  4043:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4044: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4045:         if (($tstart) && ($tstart<0)) { next; }
                   4046:         if (($tend) && ($tend<$now)) { next; }
                   4047:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4048:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4049: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4050:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4051:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4052: 	if ($role eq 'cr') { next; }
1.948     raeburn  4053:         if ($codes) {
                   4054:             if ($section) { $role .= ':'.$section; }
                   4055:             if ($returnhash{$role}) {
                   4056:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4057:             } else {
                   4058:                 $returnhash{$role}=$username.':'.$domain;
                   4059:             }
1.351     www      4060:         } else {
1.988     raeburn  4061:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4062:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4063:             if ($returnhash{$key}) {
                   4064: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4065:             } else {
                   4066:                 $returnhash{$key}=$username.':'.$domain;
                   4067:             }
1.351     www      4068:         }
1.948     raeburn  4069:     }
1.400     www      4070:     return %returnhash;
                   4071: }
                   4072: 
                   4073: sub get_my_roles {
1.937     raeburn  4074:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4075:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4076:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4077:     my (%dumphash,%nothide);
1.1086    raeburn  4078:     if ($context eq 'userroles') {
1.1166    raeburn  4079:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4080:     } else {
1.1219    raeburn  4081:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4082:         if ($hidepriv) {
                   4083:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4084:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4085:                 if ($user !~ /:/) {
                   4086:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4087:                 } else {
                   4088:                     $nothide{$user} = 1;
                   4089:                 }
                   4090:             }
                   4091:         }
1.858     raeburn  4092:     }
1.400     www      4093:     my %returnhash=();
                   4094:     my $now=time;
1.999     raeburn  4095:     my %privileged;
1.800     albertel 4096:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4097:         my ($role,$tend,$tstart);
                   4098:         if ($context eq 'userroles') {
1.1149    raeburn  4099:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4100: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4101:         } else {
                   4102:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4103:         }
1.400     www      4104:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4105:         my $status = 'active';
1.939     raeburn  4106:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4107:             $status = 'previous';
                   4108:         } 
                   4109:         if (($tstart) && ($now<$tstart)) {
                   4110:             $status = 'future';
                   4111:         }
                   4112:         if (ref($types) eq 'ARRAY') {
                   4113:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4114:                 next;
                   4115:             } 
                   4116:         } else {
                   4117:             if ($status ne 'active') {
                   4118:                 next;
                   4119:             }
                   4120:         }
1.867     raeburn  4121:         my ($rolecode,$username,$domain,$section,$area);
                   4122:         if ($context eq 'userroles') {
1.1186    raeburn  4123:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4124:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4125:         } else {
                   4126:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4127:         }
1.832     raeburn  4128:         if (ref($roledoms) eq 'ARRAY') {
                   4129:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4130:                 next;
                   4131:             }
                   4132:         }
                   4133:         if (ref($roles) eq 'ARRAY') {
                   4134:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4135:                 if ($role =~ /^cr\//) {
                   4136:                     if (!grep(/^cr$/,@{$roles})) {
                   4137:                         next;
                   4138:                     }
1.1104    raeburn  4139:                 } elsif ($role =~ /^gr\//) {
                   4140:                     if (!grep(/^gr$/,@{$roles})) {
                   4141:                         next;
                   4142:                     }
1.922     raeburn  4143:                 } else {
                   4144:                     next;
                   4145:                 }
1.832     raeburn  4146:             }
1.867     raeburn  4147:         }
1.937     raeburn  4148:         if ($hidepriv) {
1.1219    raeburn  4149:             my @privroles = ('dc','su');
1.999     raeburn  4150:             if ($context eq 'userroles') {
1.1219    raeburn  4151:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4152:             } else {
1.1219    raeburn  4153:                 my $possdoms = [$domain];
                   4154:                 if (ref($roledoms) eq 'ARRAY') {
                   4155:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4156:                 }
1.1219    raeburn  4157:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4158:                     if (!$nothide{$username.':'.$domain}) {
                   4159:                         next;
                   4160:                     }
                   4161:                 }
1.937     raeburn  4162:             }
                   4163:         }
1.933     raeburn  4164:         if ($withsec) {
                   4165:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4166:                 $tstart.':'.$tend;
                   4167:         } else {
                   4168:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4169:         }
1.832     raeburn  4170:     }
1.373     www      4171:     return %returnhash;
1.399     www      4172: }
                   4173: 
                   4174: # ----------------------------------------------------- Frontpage Announcements
                   4175: #
                   4176: #
                   4177: 
                   4178: sub postannounce {
                   4179:     my ($server,$text)=@_;
1.844     albertel 4180:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4181:     unless ($text=~/\w/) { $text=''; }
                   4182:     return &reply('setannounce:'.&escape($text),$server);
                   4183: }
                   4184: 
                   4185: sub getannounce {
1.448     albertel 4186: 
                   4187:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4188: 	my $announcement='';
1.800     albertel 4189: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4190: 	close($fh);
1.399     www      4191: 	if ($announcement=~/\w/) { 
                   4192: 	    return 
                   4193:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4194:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4195: 	} else {
                   4196: 	    return '';
                   4197: 	}
                   4198:     } else {
                   4199: 	return '';
                   4200:     }
1.351     www      4201: }
1.353     www      4202: 
                   4203: # ---------------------------------------------------------- Course ID routines
                   4204: # Deal with domain's nohist_courseid.db files
                   4205: #
                   4206: 
                   4207: sub courseidput {
1.921     raeburn  4208:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4209:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4210:     my $outcome;
                   4211:     if ($caller eq 'timeonly') {
                   4212:         my $cids = '';
                   4213:         foreach my $item (keys(%$storehash)) {
                   4214:             $cids.=&escape($item).'&';
                   4215:         }
                   4216:         $cids=~s/\&$//;
                   4217:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4218:                           $coursehome);       
                   4219:     } else {
                   4220:         my $items = '';
                   4221:         foreach my $item (keys(%$storehash)) {
                   4222:             $items.= &escape($item).'='.
                   4223:                      &freeze_escape($$storehash{$item}).'&';
                   4224:         }
                   4225:         $items=~s/\&$//;
                   4226:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4227:                           $coursehome);
1.918     raeburn  4228:     }
                   4229:     if ($outcome eq 'unknown_cmd') {
                   4230:         my $what;
                   4231:         foreach my $cid (keys(%$storehash)) {
                   4232:             $what .= &escape($cid).'=';
1.921     raeburn  4233:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4234:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4235:             }
                   4236:             $what =~ s/\:$/&/;
                   4237:         }
                   4238:         $what =~ s/\&$//;  
                   4239:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4240:     } else {
                   4241:         return $outcome;
                   4242:     }
1.353     www      4243: }
                   4244: 
                   4245: sub courseiddump {
1.921     raeburn  4246:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4247:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4248:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4249:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
                   4250:         $hasuniquecode)=@_;
1.918     raeburn  4251:     my $as_hash = 1;
                   4252:     my %returnhash;
                   4253:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4254:     my %libserv = &all_library();
                   4255:     foreach my $tryserver (keys(%libserv)) {
                   4256:         if ( (  $hostidflag == 1 
                   4257: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4258: 	     || (!defined($hostidflag)) ) {
                   4259: 
1.918     raeburn  4260: 	    if (($domfilter eq '') ||
                   4261: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4262:                 my $rep;
                   4263:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4264:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4265:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4266:                                 &escape($descfilter), &escape($instcodefilter), 
                   4267:                                 &escape($ownerfilter), &escape($coursefilter),
                   4268:                                 &escape($typefilter), &escape($regexp_ok), 
                   4269:                                 $as_hash, &escape($selfenrollonly), 
                   4270:                                 &escape($catfilter), $showhidden, $caller, 
                   4271:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4272:                                 &escape($createdbefore), &escape($createdafter), 
1.1247    raeburn  4273:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1180    droeschl 4274:                 } else {
                   4275:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4276:                              $sincefilter.':'.&escape($descfilter).':'.
                   4277:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4278:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4279:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4280:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4281:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4282:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4283:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1247    raeburn  4284:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1180    droeschl 4285:                              $tryserver);
                   4286:                 }
                   4287:                      
1.918     raeburn  4288:                 my @pairs=split(/\&/,$rep);
                   4289:                 foreach my $item (@pairs) {
                   4290:                     my ($key,$value)=split(/\=/,$item,2);
                   4291:                     $key = &unescape($key);
                   4292:                     next if ($key =~ /^error: 2 /);
                   4293:                     my $result = &thaw_unescape($value);
                   4294:                     if (ref($result) eq 'HASH') {
                   4295:                         $returnhash{$key}=$result;
                   4296:                     } else {
1.921     raeburn  4297:                         my @responses = split(/:/,$value);
                   4298:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4299:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4300:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4301:                         }
1.1008    raeburn  4302:                     }
1.353     www      4303:                 }
                   4304:             }
                   4305:         }
                   4306:     }
                   4307:     return %returnhash;
                   4308: }
                   4309: 
1.1055    raeburn  4310: sub courselastaccess {
                   4311:     my ($cdom,$cnum,$hostidref) = @_;
                   4312:     my %returnhash;
                   4313:     if ($cdom && $cnum) {
                   4314:         my $chome = &homeserver($cnum,$cdom);
                   4315:         if ($chome ne 'no_host') {
                   4316:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4317:             &extract_lastaccess(\%returnhash,$rep);
                   4318:         }
                   4319:     } else {
                   4320:         if (!$cdom) { $cdom=''; }
                   4321:         my %libserv = &all_library();
                   4322:         foreach my $tryserver (keys(%libserv)) {
                   4323:             if (ref($hostidref) eq 'ARRAY') {
                   4324:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4325:             } 
                   4326:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4327:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4328:                 &extract_lastaccess(\%returnhash,$rep);
                   4329:             }
                   4330:         }
                   4331:     }
                   4332:     return %returnhash;
                   4333: }
                   4334: 
                   4335: sub extract_lastaccess {
                   4336:     my ($returnhash,$rep) = @_;
                   4337:     if (ref($returnhash) eq 'HASH') {
                   4338:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4339:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4340:                  $rep eq '') {
                   4341:             my @pairs=split(/\&/,$rep);
                   4342:             foreach my $item (@pairs) {
                   4343:                 my ($key,$value)=split(/\=/,$item,2);
                   4344:                 $key = &unescape($key);
                   4345:                 next if ($key =~ /^error: 2 /);
                   4346:                 $returnhash->{$key} = &thaw_unescape($value);
                   4347:             }
                   4348:         }
                   4349:     }
                   4350:     return;
                   4351: }
                   4352: 
1.658     raeburn  4353: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4354: 
                   4355: sub dcmailput {
1.685     raeburn  4356:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4357:     my $status = &Apache::lonnet::critical(
1.740     www      4358:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4359:        &escape($message),$server);
1.662     raeburn  4360:     return $status;
                   4361: }
                   4362: 
1.658     raeburn  4363: sub dcmaildump {
                   4364:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4365:     my %returnhash=();
1.846     albertel 4366: 
                   4367:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4368:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4369:                                                          &escape($enddate).':';
                   4370: 	my @esc_senders=map { &escape($_)} @$senders;
                   4371: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4372: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4373:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4374:             if (($key) && ($value)) {
                   4375:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4376:             }
                   4377:         }
                   4378:     }
                   4379:     return %returnhash;
                   4380: }
1.662     raeburn  4381: # ---------------------------------------------------------- Domain roles
                   4382: 
                   4383: sub get_domain_roles {
                   4384:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4385:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4386:         $startdate = '.';
                   4387:     }
1.1018    raeburn  4388:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4389:         $enddate = '.';
                   4390:     }
1.922     raeburn  4391:     my $rolelist;
                   4392:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4393:         $rolelist = join('&',@{$roles});
1.922     raeburn  4394:     }
1.662     raeburn  4395:     my %personnel = ();
1.841     albertel 4396: 
                   4397:     my %servers = &get_servers($dom,'library');
                   4398:     foreach my $tryserver (keys(%servers)) {
                   4399: 	%{$personnel{$tryserver}}=();
                   4400: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4401: 					    &escape($startdate).':'.
                   4402: 					    &escape($enddate).':'.
                   4403: 					    &escape($rolelist), $tryserver))) {
                   4404: 	    my ($key,$value) = split(/\=/,$line,2);
                   4405: 	    if (($key) && ($value)) {
                   4406: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4407: 	    }
                   4408: 	}
1.662     raeburn  4409:     }
                   4410:     return %personnel;
                   4411: }
1.658     raeburn  4412: 
1.1057    www      4413: # ----------------------------------------------------------- Interval timing 
1.149     www      4414: 
1.1153    www      4415: {
                   4416: # Caches needed for speedup of navmaps
                   4417: # We don't want to cache this for very long at all (5 seconds at most)
                   4418: # 
                   4419: # The user for whom we cache
                   4420: my $cachedkey='';
                   4421: # The cached times for this user
                   4422: my %cachedtimes=();
                   4423: # When this was last done
                   4424: my $cachedtime=();
                   4425: 
                   4426: sub load_all_first_access {
1.1154    raeburn  4427:     my ($uname,$udom)=@_;
1.1156    www      4428:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4429:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4430:         return;
                   4431:     }
                   4432:     $cachedtime=time;
                   4433:     $cachedkey=$uname.':'.$udom;
                   4434:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4435: }
                   4436: 
1.504     albertel 4437: sub get_first_access {
1.1162    raeburn  4438:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4439:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4440:     if ($argsymb) { $symb=$argsymb; }
                   4441:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4442:     if ($argmap) { $map = $argmap; }
1.926     albertel 4443:     if ($type eq 'course') {
                   4444: 	$res='course';
                   4445:     } elsif ($type eq 'map') {
1.588     albertel 4446: 	$res=&symbread($map);
                   4447:     } else {
                   4448: 	$res=$symb;
                   4449:     }
1.1153    www      4450:     &load_all_first_access($uname,$udom);
                   4451:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4452: }
                   4453: 
                   4454: sub set_first_access {
1.1162    raeburn  4455:     my ($type,$interval)=@_;
1.790     albertel 4456:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4457:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4458:     if ($type eq 'course') {
                   4459: 	$res='course';
                   4460:     } elsif ($type eq 'map') {
1.588     albertel 4461: 	$res=&symbread($map);
                   4462:     } else {
                   4463: 	$res=$symb;
                   4464:     }
1.1153    www      4465:     $cachedkey='';
1.1162    raeburn  4466:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4467:     if (!$firstaccess) {
1.1162    raeburn  4468:         my $start = time;
                   4469: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4470:                           $udom,$uname);
                   4471:         if ($putres eq 'ok') {
                   4472:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4473:                  $udom,$uname); 
                   4474:             &appenv(
                   4475:                      {
                   4476:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4477:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4478:                      }
                   4479:                   );
                   4480:         }
                   4481:         return $putres;
1.505     albertel 4482:     }
                   4483:     return 'already_set';
1.504     albertel 4484: }
1.1153    www      4485: }
1.110     www      4486: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4487: 
                   4488: sub expirespread {
                   4489:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4490:     my $cid=$env{'request.course.id'}; 
1.110     www      4491:     if ($cid) {
                   4492:        my $now=time;
                   4493:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4494:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4495:                             $env{'course.'.$cid.'.num'}.
1.110     www      4496: 	        	    ':nohist_expirationdates:'.
                   4497:                             &escape($key).'='.$now,
1.620     albertel 4498:                             $env{'course.'.$cid.'.home'})
1.110     www      4499:     }
                   4500:     return 'ok';
1.14      www      4501: }
                   4502: 
1.109     www      4503: # ----------------------------------------------------- Devalidate Spreadsheets
                   4504: 
                   4505: sub devalidate {
1.325     www      4506:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4507:     my $cid=$env{'request.course.id'}; 
1.109     www      4508:     if ($cid) {
1.391     matthew  4509:         # delete the stored spreadsheets for
                   4510:         # - the student level sheet of this user in course's homespace
                   4511:         # - the assessment level sheet for this resource 
                   4512:         #   for this user in user's homespace
1.553     albertel 4513: 	# - current conditional state info
1.325     www      4514: 	my $key=$uname.':'.$udom.':';
1.109     www      4515:         my $status=
1.299     matthew  4516: 	    &del('nohist_calculatedsheets',
1.391     matthew  4517: 		 [$key.'studentcalc:'],
1.620     albertel 4518: 		 $env{'course.'.$cid.'.domain'},
                   4519: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4520: 		.' '.
                   4521: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4522: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4523:         unless ($status eq 'ok ok') {
                   4524:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4525:                     $uname.' at '.$udom.' for '.
1.109     www      4526: 		    $symb.': '.$status);
1.133     albertel 4527:         }
1.553     albertel 4528: 	&delenv('user.state.'.$cid);
1.109     www      4529:     }
                   4530: }
                   4531: 
1.265     albertel 4532: sub get_scalar {
                   4533:     my ($string,$end) = @_;
                   4534:     my $value;
                   4535:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4536: 	$value = $1;
                   4537:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4538: 	$value = $1;
                   4539:     }
                   4540:     return &unescape($value);
                   4541: }
                   4542: 
                   4543: sub array2str {
                   4544:   my (@array) = @_;
                   4545:   my $result=&arrayref2str(\@array);
                   4546:   $result=~s/^__ARRAY_REF__//;
                   4547:   $result=~s/__END_ARRAY_REF__$//;
                   4548:   return $result;
                   4549: }
                   4550: 
1.204     albertel 4551: sub arrayref2str {
                   4552:   my ($arrayref) = @_;
1.265     albertel 4553:   my $result='__ARRAY_REF__';
1.204     albertel 4554:   foreach my $elem (@$arrayref) {
1.265     albertel 4555:     if(ref($elem) eq 'ARRAY') {
                   4556:       $result.=&arrayref2str($elem).'&';
                   4557:     } elsif(ref($elem) eq 'HASH') {
                   4558:       $result.=&hashref2str($elem).'&';
                   4559:     } elsif(ref($elem)) {
                   4560:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4561:     } else {
                   4562:       $result.=&escape($elem).'&';
                   4563:     }
                   4564:   }
                   4565:   $result=~s/\&$//;
1.265     albertel 4566:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4567:   return $result;
                   4568: }
                   4569: 
1.168     albertel 4570: sub hash2str {
1.204     albertel 4571:   my (%hash) = @_;
                   4572:   my $result=&hashref2str(\%hash);
1.265     albertel 4573:   $result=~s/^__HASH_REF__//;
                   4574:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4575:   return $result;
                   4576: }
                   4577: 
                   4578: sub hashref2str {
                   4579:   my ($hashref)=@_;
1.265     albertel 4580:   my $result='__HASH_REF__';
1.800     albertel 4581:   foreach my $key (sort(keys(%$hashref))) {
                   4582:     if (ref($key) eq 'ARRAY') {
                   4583:       $result.=&arrayref2str($key).'=';
                   4584:     } elsif (ref($key) eq 'HASH') {
                   4585:       $result.=&hashref2str($key).'=';
                   4586:     } elsif (ref($key)) {
1.265     albertel 4587:       $result.='=';
1.800     albertel 4588:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4589:     } else {
1.1132    raeburn  4590: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4591:     }
                   4592: 
1.800     albertel 4593:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4594:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4595:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4596:       $result.=&hashref2str($hashref->{$key}).'&';
                   4597:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4598:        $result.='&';
1.800     albertel 4599:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4600:     } else {
1.800     albertel 4601:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4602:     }
                   4603:   }
1.168     albertel 4604:   $result=~s/\&$//;
1.265     albertel 4605:   $result .= '__END_HASH_REF__';
1.168     albertel 4606:   return $result;
                   4607: }
                   4608: 
                   4609: sub str2hash {
1.265     albertel 4610:     my ($string)=@_;
                   4611:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4612:     return %$hash;
                   4613: }
                   4614: 
                   4615: sub str2hashref {
1.168     albertel 4616:   my ($string) = @_;
1.265     albertel 4617: 
                   4618:   my %hash;
                   4619: 
                   4620:   if($string !~ /^__HASH_REF__/) {
                   4621:       if (! ($string eq '' || !defined($string))) {
                   4622: 	  $hash{'error'}='Not hash reference';
                   4623:       }
                   4624:       return (\%hash, $string);
                   4625:   }
                   4626: 
                   4627:   $string =~ s/^__HASH_REF__//;
                   4628: 
                   4629:   while($string !~ /^__END_HASH_REF__/) {
                   4630:       #key
                   4631:       my $key='';
                   4632:       if($string =~ /^__HASH_REF__/) {
                   4633:           ($key, $string)=&str2hashref($string);
                   4634:           if(defined($key->{'error'})) {
                   4635:               $hash{'error'}='Bad data';
                   4636:               return (\%hash, $string);
                   4637:           }
                   4638:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4639:           ($key, $string)=&str2arrayref($string);
                   4640:           if($key->[0] eq 'Array reference error') {
                   4641:               $hash{'error'}='Bad data';
                   4642:               return (\%hash, $string);
                   4643:           }
                   4644:       } else {
                   4645:           $string =~ s/^(.*?)=//;
1.267     albertel 4646: 	  $key=&unescape($1);
1.265     albertel 4647:       }
                   4648:       $string =~ s/^=//;
                   4649: 
                   4650:       #value
                   4651:       my $value='';
                   4652:       if($string =~ /^__HASH_REF__/) {
                   4653:           ($value, $string)=&str2hashref($string);
                   4654:           if(defined($value->{'error'})) {
                   4655:               $hash{'error'}='Bad data';
                   4656:               return (\%hash, $string);
                   4657:           }
                   4658:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4659:           ($value, $string)=&str2arrayref($string);
                   4660:           if($value->[0] eq 'Array reference error') {
                   4661:               $hash{'error'}='Bad data';
                   4662:               return (\%hash, $string);
                   4663:           }
                   4664:       } else {
                   4665: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4666:       }
                   4667:       $string =~ s/^&//;
                   4668: 
                   4669:       $hash{$key}=$value;
1.204     albertel 4670:   }
1.265     albertel 4671: 
                   4672:   $string =~ s/^__END_HASH_REF__//;
                   4673: 
                   4674:   return (\%hash, $string);
1.204     albertel 4675: }
                   4676: 
                   4677: sub str2array {
1.265     albertel 4678:     my ($string)=@_;
                   4679:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4680:     return @$array;
                   4681: }
                   4682: 
                   4683: sub str2arrayref {
1.204     albertel 4684:   my ($string) = @_;
1.265     albertel 4685:   my @array;
                   4686: 
                   4687:   if($string !~ /^__ARRAY_REF__/) {
                   4688:       if (! ($string eq '' || !defined($string))) {
                   4689: 	  $array[0]='Array reference error';
                   4690:       }
                   4691:       return (\@array, $string);
                   4692:   }
                   4693: 
                   4694:   $string =~ s/^__ARRAY_REF__//;
                   4695: 
                   4696:   while($string !~ /^__END_ARRAY_REF__/) {
                   4697:       my $value='';
                   4698:       if($string =~ /^__HASH_REF__/) {
                   4699:           ($value, $string)=&str2hashref($string);
                   4700:           if(defined($value->{'error'})) {
                   4701:               $array[0] ='Array reference error';
                   4702:               return (\@array, $string);
                   4703:           }
                   4704:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4705:           ($value, $string)=&str2arrayref($string);
                   4706:           if($value->[0] eq 'Array reference error') {
                   4707:               $array[0] ='Array reference error';
                   4708:               return (\@array, $string);
                   4709:           }
                   4710:       } else {
                   4711: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4712:       }
                   4713:       $string =~ s/^&//;
                   4714: 
                   4715:       push(@array, $value);
1.191     harris41 4716:   }
1.265     albertel 4717: 
                   4718:   $string =~ s/^__END_ARRAY_REF__//;
                   4719: 
                   4720:   return (\@array, $string);
1.168     albertel 4721: }
                   4722: 
1.167     albertel 4723: # -------------------------------------------------------------------Temp Store
                   4724: 
1.168     albertel 4725: sub tmpreset {
                   4726:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4727:   if (!$symb) {
                   4728:     $symb=&symbread();
1.620     albertel 4729:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4730:   }
                   4731:   $symb=escape($symb);
                   4732: 
1.620     albertel 4733:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4734:   $namespace=~s/\//\_/g;
                   4735:   $namespace=~s/\W//g;
                   4736: 
1.620     albertel 4737:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4738:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4739:   if ($domain eq 'public' && $stuname eq 'public') {
                   4740:       $stuname=$ENV{'REMOTE_ADDR'};
                   4741:   }
1.1117    foxr     4742:   my $path=LONCAPA::tempdir();
1.168     albertel 4743:   my %hash;
                   4744:   if (tie(%hash,'GDBM_File',
                   4745: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4746: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4747:     foreach my $key (keys(%hash)) {
1.180     albertel 4748:       if ($key=~ /:$symb/) {
1.168     albertel 4749: 	delete($hash{$key});
                   4750:       }
                   4751:     }
                   4752:   }
                   4753: }
                   4754: 
1.167     albertel 4755: sub tmpstore {
1.168     albertel 4756:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4757: 
                   4758:   if (!$symb) {
                   4759:     $symb=&symbread();
1.620     albertel 4760:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4761:   }
                   4762:   $symb=escape($symb);
                   4763: 
                   4764:   if (!$namespace) {
                   4765:     # I don't think we would ever want to store this for a course.
                   4766:     # it seems this will only be used if we don't have a course.
1.620     albertel 4767:     #$namespace=$env{'request.course.id'};
1.168     albertel 4768:     #if (!$namespace) {
1.620     albertel 4769:       $namespace=$env{'request.state'};
1.168     albertel 4770:     #}
                   4771:   }
                   4772:   $namespace=~s/\//\_/g;
                   4773:   $namespace=~s/\W//g;
1.620     albertel 4774:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4775:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4776:   if ($domain eq 'public' && $stuname eq 'public') {
                   4777:       $stuname=$ENV{'REMOTE_ADDR'};
                   4778:   }
1.168     albertel 4779:   my $now=time;
                   4780:   my %hash;
1.1117    foxr     4781:   my $path=LONCAPA::tempdir();
1.168     albertel 4782:   if (tie(%hash,'GDBM_File',
                   4783: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4784: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4785:     $hash{"version:$symb"}++;
                   4786:     my $version=$hash{"version:$symb"};
                   4787:     my $allkeys=''; 
                   4788:     foreach my $key (keys(%$storehash)) {
                   4789:       $allkeys.=$key.':';
1.591     albertel 4790:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4791:     }
                   4792:     $hash{"$version:$symb:timestamp"}=$now;
                   4793:     $allkeys.='timestamp';
                   4794:     $hash{"$version:keys:$symb"}=$allkeys;
                   4795:     if (untie(%hash)) {
                   4796:       return 'ok';
                   4797:     } else {
                   4798:       return "error:$!";
                   4799:     }
                   4800:   } else {
                   4801:     return "error:$!";
                   4802:   }
                   4803: }
1.167     albertel 4804: 
1.168     albertel 4805: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4806: 
1.168     albertel 4807: sub tmprestore {
                   4808:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4809: 
1.168     albertel 4810:   if (!$symb) {
                   4811:     $symb=&symbread();
1.620     albertel 4812:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4813:   }
                   4814:   $symb=escape($symb);
                   4815: 
1.620     albertel 4816:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4817: 
1.620     albertel 4818:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4819:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4820:   if ($domain eq 'public' && $stuname eq 'public') {
                   4821:       $stuname=$ENV{'REMOTE_ADDR'};
                   4822:   }
1.168     albertel 4823:   my %returnhash;
                   4824:   $namespace=~s/\//\_/g;
                   4825:   $namespace=~s/\W//g;
                   4826:   my %hash;
1.1117    foxr     4827:   my $path=LONCAPA::tempdir();
1.168     albertel 4828:   if (tie(%hash,'GDBM_File',
                   4829: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4830: 	  &GDBM_READER(),0640)) {
1.168     albertel 4831:     my $version=$hash{"version:$symb"};
                   4832:     $returnhash{'version'}=$version;
                   4833:     my $scope;
                   4834:     for ($scope=1;$scope<=$version;$scope++) {
                   4835:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4836:       my @keys=split(/:/,$vkeys);
                   4837:       my $key;
                   4838:       $returnhash{"$scope:keys"}=$vkeys;
                   4839:       foreach $key (@keys) {
1.591     albertel 4840: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4841: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4842:       }
                   4843:     }
1.168     albertel 4844:     if (!(untie(%hash))) {
                   4845:       return "error:$!";
                   4846:     }
                   4847:   } else {
                   4848:     return "error:$!";
                   4849:   }
                   4850:   return %returnhash;
1.167     albertel 4851: }
                   4852: 
1.9       www      4853: # ----------------------------------------------------------------------- Store
                   4854: 
                   4855: sub store {
1.1269    raeburn  4856:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      4857:     my $home='';
                   4858: 
1.168     albertel 4859:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4860: 
1.213     www      4861:     $symb=&symbclean($symb);
1.122     albertel 4862:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4863: 
1.620     albertel 4864:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4865:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4866: 
                   4867:     &devalidate($symb,$stuname,$domain);
1.109     www      4868: 
                   4869:     $symb=escape($symb);
1.187     www      4870:     if (!$namespace) { 
1.620     albertel 4871:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4872:           return ''; 
                   4873:        } 
                   4874:     }
1.620     albertel 4875:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4876: 
                   4877:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4878:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4879: 
1.12      www      4880:     my $namevalue='';
1.800     albertel 4881:     foreach my $key (keys(%$storehash)) {
                   4882:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4883:     }
1.12      www      4884:     $namevalue=~s/\&$//;
1.187     www      4885:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  4886:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      4887: }
                   4888: 
1.47      www      4889: # -------------------------------------------------------------- Critical Store
                   4890: 
                   4891: sub cstore {
1.1269    raeburn  4892:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      4893:     my $home='';
                   4894: 
1.168     albertel 4895:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4896: 
1.213     www      4897:     $symb=&symbclean($symb);
1.122     albertel 4898:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4899: 
1.620     albertel 4900:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4901:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4902: 
                   4903:     &devalidate($symb,$stuname,$domain);
1.109     www      4904: 
                   4905:     $symb=escape($symb);
1.187     www      4906:     if (!$namespace) { 
1.620     albertel 4907:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4908:           return ''; 
                   4909:        } 
                   4910:     }
1.620     albertel 4911:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4912: 
                   4913:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4914:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4915: 
1.47      www      4916:     my $namevalue='';
1.800     albertel 4917:     foreach my $key (keys(%$storehash)) {
                   4918:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4919:     }
1.47      www      4920:     $namevalue=~s/\&$//;
1.187     www      4921:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4922:     return critical
1.1269    raeburn  4923:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      4924: }
                   4925: 
1.9       www      4926: # --------------------------------------------------------------------- Restore
                   4927: 
                   4928: sub restore {
1.124     www      4929:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4930:     my $home='';
                   4931: 
1.168     albertel 4932:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4933: 
1.122     albertel 4934:     if (!$symb) {
1.1224    raeburn  4935:         return if ($namespace eq 'courserequests');
                   4936:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 4937:     } else {
1.1224    raeburn  4938:         unless ($namespace eq 'courserequests') {
                   4939:             $symb=&escape(&symbclean($symb));
                   4940:         }
1.122     albertel 4941:     }
1.188     www      4942:     if (!$namespace) { 
1.620     albertel 4943:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4944:           return ''; 
                   4945:        } 
                   4946:     }
1.620     albertel 4947:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4948:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4949:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4950:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4951: 
1.12      www      4952:     my %returnhash=();
1.800     albertel 4953:     foreach my $line (split(/\&/,$answer)) {
                   4954: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4955:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4956:     }
1.75      www      4957:     my $version;
                   4958:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4959:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4960:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4961:        }
1.75      www      4962:     }
1.13      www      4963:     return %returnhash;
1.34      www      4964: }
                   4965: 
                   4966: # ---------------------------------------------------------- Course Description
1.1118    foxr     4967: #
                   4968: #  
1.34      www      4969: 
                   4970: sub coursedescription {
1.731     albertel 4971:     my ($courseid,$args)=@_;
1.34      www      4972:     $courseid=~s/^\///;
1.49      www      4973:     $courseid=~s/\_/\//g;
1.34      www      4974:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4975:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4976:     my $normalid=$cdomain.'_'.$cnum;
                   4977:     # need to always cache even if we get errors otherwise we keep 
                   4978:     # trying and trying and trying to get the course description.
                   4979:     my %envhash=();
                   4980:     my %returnhash=();
1.731     albertel 4981:     
                   4982:     my $expiretime=600;
                   4983:     if ($env{'request.course.id'} eq $normalid) {
                   4984: 	$expiretime=120;
                   4985:     }
                   4986: 
                   4987:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4988:     if (!$args->{'freshen_cache'}
                   4989: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4990: 	foreach my $key (keys(%env)) {
                   4991: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4992: 	    my ($setting) = $1;
                   4993: 	    $returnhash{$setting} = $env{$key};
                   4994: 	}
                   4995: 	return %returnhash;
                   4996:     }
                   4997: 
1.1118    foxr     4998:     # get the data again
                   4999: 
1.731     albertel 5000:     if (!$args->{'one_time'}) {
                   5001: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5002:     }
1.811     albertel 5003: 
1.34      www      5004:     if ($chome ne 'no_host') {
1.302     albertel 5005:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5006:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5007: 	   my $username = $env{'user.name'}; # Defult username
                   5008: 	   if(defined $args->{'user'}) {
                   5009: 	       $username = $args->{'user'};
                   5010: 	   }
1.129     albertel 5011:            $returnhash{'home'}= $chome;
                   5012: 	   $returnhash{'domain'} = $cdomain;
                   5013: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5014:            if (!defined($returnhash{'type'})) {
                   5015:                $returnhash{'type'} = 'Course';
                   5016:            }
1.130     albertel 5017:            while (my ($name,$value) = each %returnhash) {
1.53      www      5018:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5019:            }
1.270     www      5020:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5021:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5022: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5023:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5024:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5025:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5026:        }
                   5027:     }
1.731     albertel 5028:     if (!$args->{'one_time'}) {
1.949     raeburn  5029: 	&appenv(\%envhash);
1.731     albertel 5030:     }
1.302     albertel 5031:     return %returnhash;
1.461     www      5032: }
                   5033: 
1.1080    raeburn  5034: sub update_released_required {
                   5035:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5036:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5037:         $cid = $env{'request.course.id'};
                   5038:         $cdom = $env{'course.'.$cid.'.domain'};
                   5039:         $cnum = $env{'course.'.$cid.'.num'};
                   5040:         $chome = $env{'course.'.$cid.'.home'};
                   5041:     }
                   5042:     if ($needsrelease) {
                   5043:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5044:         my $needsupdate;
                   5045:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5046:             $needsupdate = 1;
                   5047:         } else {
                   5048:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5049:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5050:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5051:                 $needsupdate = 1;
                   5052:             }
                   5053:         }
                   5054:         if ($needsupdate) {
                   5055:             my %needshash = (
                   5056:                              'internal.releaserequired' => $needsrelease,
                   5057:                             );
                   5058:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5059:             if ($putresult eq 'ok') {
                   5060:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5061:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5062:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5063:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5064:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5065:                 }
                   5066:             }
                   5067:         }
                   5068:     }
                   5069:     return;
                   5070: }
                   5071: 
1.461     www      5072: # -------------------------------------------------See if a user is privileged
                   5073: 
                   5074: sub privileged {
1.1219    raeburn  5075:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5076:     my $now = time;
1.1219    raeburn  5077:     my $roles;
                   5078:     if (ref($possroles) eq 'ARRAY') {
                   5079:         $roles = $possroles; 
                   5080:     } else {
                   5081:         $roles = ['dc','su'];
                   5082:     }
                   5083:     if (ref($possdomains) eq 'ARRAY') {
                   5084:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5085:         foreach my $dom (@{$possdomains}) {
                   5086:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5087:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5088:                 foreach my $role (@{$roles}) {
                   5089:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5090:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5091:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5092:                             return 1 unless (($end && $end < $now) ||
                   5093:                                              ($start && $start > $now));
                   5094:                         }
                   5095:                     }
                   5096:                 }
                   5097:             }
                   5098:         }
                   5099:     } else {
                   5100:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5101:         my $now = time;
1.1170    droeschl 5102: 
1.1219    raeburn  5103:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170    droeschl 5104:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5105:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5106:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5107:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5108:             }
1.1219    raeburn  5109:         }
                   5110:     }
                   5111:     return 0;
                   5112: }
1.1170    droeschl 5113: 
1.1219    raeburn  5114: sub privileged_by_domain {
                   5115:     my ($domains,$roles) = @_;
                   5116:     my %privileged = ();
                   5117:     my $cachetime = 60*60*24;
                   5118:     my $now = time;
                   5119:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5120:         return %privileged;
                   5121:     }
                   5122:     foreach my $dom (@{$domains}) {
                   5123:         next if (ref($privileged{$dom}) eq 'HASH');
                   5124:         my $needroles;
                   5125:         foreach my $role (@{$roles}) {
                   5126:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5127:             if (defined($cached)) {
                   5128:                 if (ref($result) eq 'HASH') {
                   5129:                     $privileged{$dom}{$role} = $result;
                   5130:                 }
                   5131:             } else {
                   5132:                 $needroles = 1;
                   5133:             }
                   5134:         }
                   5135:         if ($needroles) {
                   5136:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5137:             $privileged{$dom} = {};
                   5138:             foreach my $server (keys(%dompersonnel)) {
                   5139:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5140:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5141:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5142:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5143:                         next if ($end && $end < $now);
                   5144:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5145:                             $dompersonnel{$server}{$item};
                   5146:                     }
                   5147:                 }
                   5148:             }
                   5149:             if (ref($privileged{$dom}) eq 'HASH') {
                   5150:                 foreach my $role (@{$roles}) {
                   5151:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5152:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5153:                     } else {
                   5154:                         my %hash = ();
                   5155:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5156:                     }
                   5157:                 }
                   5158:             }
                   5159:         }
                   5160:     }
                   5161:     return %privileged;
1.9       www      5162: }
1.1       albertel 5163: 
1.103     harris41 5164: # -------------------------------------------------------- Get user privileges
1.11      www      5165: 
                   5166: sub rolesinit {
1.1169    droeschl 5167:     my ($domain, $username) = @_;
                   5168:     my %userroles = ('user.login.time' => time);
                   5169:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5170: 
                   5171:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5172:     # also, blocking can be triggered by an activating timer
                   5173:     # it's saved in the user's %env.
                   5174:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5175:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5176:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5177:         %timerintchk, %timerintenv);
                   5178: 
1.1162    raeburn  5179:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5180:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5181:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5182:     }
1.1169    droeschl 5183: 
1.1162    raeburn  5184:     foreach my $key (keys(%timerinterval)) {
                   5185:         my ($cid,$rest) = split(/\0/,$key);
                   5186:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5187:     }
1.1169    droeschl 5188: 
1.11      www      5189:     my %allroles=();
1.1162    raeburn  5190:     my %allgroups=();
1.11      www      5191: 
1.1169    droeschl 5192:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   5193:         my $role = $rolesdump{$area};
                   5194:         $area =~ s/\_\w\w$//;
                   5195: 
                   5196:         my ($trole, $tend, $tstart, $group_privs);
                   5197: 
                   5198:         if ($role =~ /^cr/) {
                   5199:         # Custom role, defined by a user 
                   5200:         # e.g., user.role.cr/msu/smith/mynewrole
                   5201:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5202:                 $trole = $1;
                   5203:                 ($tend, $tstart) = split('_', $2);
                   5204:             } else {
                   5205:                 $trole = $role;
                   5206:             }
                   5207:         } elsif ($role =~ m|^gr/|) {
                   5208:         # Role of member in a group, defined within a course/community
                   5209:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5210:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5211:             next if $tstart eq '-1';
                   5212:             ($trole, $group_privs) = split(/\//, $trole);
                   5213:             $group_privs = &unescape($group_privs);
                   5214:         } else {
                   5215:         # Just a normal role, defined in roles.tab
                   5216:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5217:         }
                   5218: 
                   5219:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5220:                  $username);
                   5221:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5222: 
                   5223:         # role expired or not available yet?
                   5224:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5225:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5226: 
                   5227:         next if $area eq '' or $trole eq '';
                   5228: 
                   5229:         my $spec = "$trole.$area";
                   5230:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5231: 
                   5232:         if ($trole =~ /^cr\//) {
                   5233:         # Custom role, defined by a user
                   5234:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5235:         } elsif ($trole eq 'gr') {
                   5236:         # Role of a member in a group, defined within a course/community
                   5237:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5238:             next;
                   5239:         } else {
                   5240:         # Normal role, defined in roles.tab
                   5241:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5242:         }
                   5243: 
                   5244:         my $cid = $tdomain.'_'.$trest;
                   5245:         unless ($firstaccchk{$cid}) {
                   5246:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5247:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5248:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5249:                         $coursetimerstarts{$cid}{$item}; 
                   5250:                 }
                   5251:             }
                   5252:             $firstaccchk{$cid} = 1;
                   5253:         }
                   5254:         unless ($timerintchk{$cid}) {
                   5255:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5256:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5257:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5258:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5259:                 }
1.12      www      5260:             }
1.1169    droeschl 5261:             $timerintchk{$cid} = 1;
1.191     harris41 5262:         }
1.11      www      5263:     }
1.1169    droeschl 5264: 
                   5265:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5266:         \%allroles, \%allgroups);
                   5267:     $env{'user.adv'} = $userroles{'user.adv'};
                   5268: 
1.1162    raeburn  5269:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5270: }
                   5271: 
1.567     raeburn  5272: sub set_arearole {
1.1215    raeburn  5273:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5274:     unless ($nolog) {
1.567     raeburn  5275: # log the associated role with the area
1.1215    raeburn  5276:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5277:     }
1.743     albertel 5278:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5279: }
                   5280: 
                   5281: sub custom_roleprivs {
                   5282:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5283:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5284:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5285:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5286:         my ($rdummy,$roledef)=
                   5287:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5288:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5289:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5290:             if (defined($syspriv)) {
1.1043    raeburn  5291:                 if ($trest =~ /^$match_community$/) {
                   5292:                     $syspriv =~ s/bre\&S//; 
                   5293:                 }
1.567     raeburn  5294:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5295:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5296:             }
                   5297:             if ($tdomain ne '') {
                   5298:                 if (defined($dompriv)) {
                   5299:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5300:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5301:                 }
                   5302:                 if (($trest ne '') && (defined($coursepriv))) {
                   5303:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5304:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5305:                 }
                   5306:             }
                   5307:         }
                   5308:     }
                   5309: }
                   5310: 
1.678     raeburn  5311: sub group_roleprivs {
                   5312:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5313:     my $access = 1;
                   5314:     my $now = time;
                   5315:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5316:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5317:     if ($access) {
1.811     albertel 5318:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5319:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5320:     }
                   5321: }
1.567     raeburn  5322: 
                   5323: sub standard_roleprivs {
                   5324:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5325:     if (defined($pr{$trole.':s'})) {
                   5326:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5327:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5328:     }
                   5329:     if ($tdomain ne '') {
                   5330:         if (defined($pr{$trole.':d'})) {
                   5331:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5332:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5333:         }
                   5334:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5335:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5336:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5337:         }
                   5338:     }
                   5339: }
                   5340: 
                   5341: sub set_userprivs {
1.1064    raeburn  5342:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5343:     my $author=0;
                   5344:     my $adv=0;
1.678     raeburn  5345:     my %grouproles = ();
                   5346:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5347:         my @groupkeys; 
1.1000    raeburn  5348:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5349:             push(@groupkeys,$role);
                   5350:         }
                   5351:         if (ref($groups_roles) eq 'HASH') {
                   5352:             foreach my $key (keys(%{$groups_roles})) {
                   5353:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5354:                     push(@groupkeys,$key);
                   5355:                 }
                   5356:             }
                   5357:         }
                   5358:         if (@groupkeys > 0) {
                   5359:             foreach my $role (@groupkeys) {
                   5360:                 my ($trole,$area,$sec,$extendedarea);
                   5361:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5362:                     $trole = $1;
                   5363:                     $area = $2;
                   5364:                     $sec = $3;
                   5365:                     $extendedarea = $area.$sec;
                   5366:                     if (exists($$allgroups{$area})) {
                   5367:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5368:                             my $spec = $trole.'.'.$extendedarea;
                   5369:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5370:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5371:                         }
1.678     raeburn  5372:                     }
                   5373:                 }
                   5374:             }
                   5375:         }
                   5376:     }
1.800     albertel 5377:     foreach my $group (keys(%grouproles)) {
                   5378:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5379:     }
1.800     albertel 5380:     foreach my $role (keys(%{$allroles})) {
                   5381:         my %thesepriv;
1.941     raeburn  5382:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5383:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5384:             if ($item ne '') {
                   5385:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5386:                 if ($restrictions eq '') {
                   5387:                     $thesepriv{$privilege}='F';
                   5388:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5389:                     $thesepriv{$privilege}.=$restrictions;
                   5390:                 }
                   5391:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5392:             }
                   5393:         }
                   5394:         my $thesestr='';
1.1104    raeburn  5395:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5396: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5397: 	}
                   5398:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5399:     }
                   5400:     return ($author,$adv);
                   5401: }
                   5402: 
1.994     raeburn  5403: sub role_status {
1.1104    raeburn  5404:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5405:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5406:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5407:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5408:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5409:             $$where = '/'.$two;
1.994     raeburn  5410:             $$trolecode=$$role.'.'.$$where;
                   5411:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5412:             $$tstatus='is';
1.1104    raeburn  5413:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5414:                 $$tstatus='future';
1.1034    raeburn  5415:                 if ($$tstart<$now) {
                   5416:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5417:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5418:                             my (%allroles,%allgroups,$group_privs,
                   5419:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5420:                             my %userroles = (
                   5421:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5422:                             );
1.1064    raeburn  5423:                             @rolecodes = ('cm'); 
1.1002    raeburn  5424:                             my $spec=$$role.'.'.$$where;
                   5425:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5426:                             if ($$role =~ /^cr\//) {
                   5427:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5428:                                 push(@rolecodes,'cr');
1.1002    raeburn  5429:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5430:                                 push(@rolecodes,$$role);
1.1002    raeburn  5431:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5432:                                                     $env{'user.name'});
1.1064    raeburn  5433:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5434:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5435:                                 $group_privs = &unescape($group_privs);
                   5436:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5437:                                 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  5438:                                 &get_groups_roles($tdomain,$trest,
                   5439:                                                   \%course_roles,\@rolecodes,
                   5440:                                                   \%groups_roles);
1.1002    raeburn  5441:                             } else {
1.1064    raeburn  5442:                                 push(@rolecodes,$$role);
1.1002    raeburn  5443:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5444:                             }
1.1064    raeburn  5445:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5446:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5447:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5448:                         }
                   5449:                     }
1.1034    raeburn  5450:                     $$tstatus = 'is';
1.1002    raeburn  5451:                 }
1.994     raeburn  5452:             }
                   5453:             if ($$tend) {
1.1104    raeburn  5454:                 if ($$tend<$update) {
1.994     raeburn  5455:                     $$tstatus='expired';
                   5456:                 } elsif ($$tend<$now) {
                   5457:                     $$tstatus='will_not';
                   5458:                 }
                   5459:             }
                   5460:         }
                   5461:     }
                   5462: }
                   5463: 
1.1104    raeburn  5464: sub get_groups_roles {
                   5465:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5466:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5467:                   (ref($rolecodes) eq 'ARRAY') && 
                   5468:                   (ref($groups_roles) eq 'HASH')); 
                   5469:     if (keys(%{$cdom_courseroles}) > 0) {
                   5470:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5471:         if ($cdom ne '' && $cnum ne '') {
                   5472:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5473:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5474:                     my $crsrole = $1;
                   5475:                     my $crssec = $2;
                   5476:                     if ($crsrole =~ /^cr/) {
                   5477:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5478:                             push(@{$rolecodes},'cr');
                   5479:                         }
                   5480:                     } else {
                   5481:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5482:                             push(@{$rolecodes},$crsrole);
                   5483:                         }
                   5484:                     }
                   5485:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5486:                     if ($crssec ne '') {
                   5487:                         $rolekey .= "/$crssec";
                   5488:                     }
                   5489:                     $rolekey .= './';
                   5490:                     $groups_roles->{$rolekey} = $rolecodes;
                   5491:                 }
                   5492:             }
                   5493:         }
                   5494:     }
                   5495:     return;
                   5496: }
                   5497: 
                   5498: sub delete_env_groupprivs {
                   5499:     my ($where,$courseroles,$possroles) = @_;
                   5500:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5501:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5502:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5503:         %{$courseroles->{$udom}} =
                   5504:             &get_my_roles('','','userroles',['active'],
                   5505:                           $possroles,[$udom],1);
                   5506:     }
                   5507:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5508:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5509:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5510:             my $area = '/'.$cdom.'/'.$cnum;
                   5511:             my $privkey = "user.priv.$crsrole.$area";
                   5512:             if ($crssec ne '') {
                   5513:                 $privkey .= '/'.$crssec;
                   5514:             }
                   5515:             $privkey .= ".$area/$group";
                   5516:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5517:         }
                   5518:     }
                   5519:     return;
                   5520: }
                   5521: 
1.994     raeburn  5522: sub check_adhoc_privs {
1.1104    raeburn  5523:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5524:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5525:     my $setprivs;
1.994     raeburn  5526:     if ($env{$cckey}) {
                   5527:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5528:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5529:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5530:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5531:             $setprivs = 1;
1.994     raeburn  5532:         }
                   5533:     } else {
1.1088    raeburn  5534:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5535:         $setprivs = 1;
1.994     raeburn  5536:     }
1.1185    raeburn  5537:     return $setprivs;
1.994     raeburn  5538: }
                   5539: 
                   5540: sub set_adhoc_privileges {
                   5541: # role can be cc or ca
1.1088    raeburn  5542:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5543:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5544:     my $spec = $role.'.'.$area;
                   5545:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5546:                                   $env{'user.name'},1);
1.994     raeburn  5547:     my %ccrole = ();
                   5548:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5549:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5550:     &appenv(\%userroles,[$role,'cm']);
                   5551:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5552:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5553:         &appenv( {'request.role'        => $spec,
                   5554:                   'request.role.domain' => $dcdom,
                   5555:                   'request.course.sec'  => ''
                   5556:                  }
                   5557:                );
                   5558:         my $tadv=0;
                   5559:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5560:         &appenv({'request.role.adv'    => $tadv});
                   5561:     }
1.994     raeburn  5562: }
                   5563: 
1.12      www      5564: # --------------------------------------------------------------- get interface
                   5565: 
                   5566: sub get {
1.131     albertel 5567:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5568:    my $items='';
1.800     albertel 5569:    foreach my $item (@$storearr) {
                   5570:        $items.=&escape($item).'&';
1.191     harris41 5571:    }
1.12      www      5572:    $items=~s/\&$//;
1.620     albertel 5573:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5574:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5575:    my $uhome=&homeserver($uname,$udomain);
                   5576: 
1.133     albertel 5577:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5578:    my @pairs=split(/\&/,$rep);
1.273     albertel 5579:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5580:      return @pairs;
                   5581:    }
1.15      www      5582:    my %returnhash=();
1.42      www      5583:    my $i=0;
1.800     albertel 5584:    foreach my $item (@$storearr) {
                   5585:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5586:       $i++;
1.191     harris41 5587:    }
1.15      www      5588:    return %returnhash;
1.27      www      5589: }
                   5590: 
                   5591: # --------------------------------------------------------------- del interface
                   5592: 
                   5593: sub del {
1.133     albertel 5594:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5595:    my $items='';
1.800     albertel 5596:    foreach my $item (@$storearr) {
                   5597:        $items.=&escape($item).'&';
1.191     harris41 5598:    }
1.984     neumanie 5599: 
1.27      www      5600:    $items=~s/\&$//;
1.620     albertel 5601:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5602:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5603:    my $uhome=&homeserver($uname,$udomain);
                   5604:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5605: }
                   5606: 
                   5607: # -------------------------------------------------------------- dump interface
                   5608: 
1.1180    droeschl 5609: sub unserialize {
                   5610:     my ($rep, $escapedkeys) = @_;
                   5611: 
                   5612:     return {} if $rep =~ /^error/;
                   5613: 
                   5614:     my %returnhash=();
1.1252    raeburn  5615: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 5616: 	    my ($key, $value) = split(/=/, $item, 2);
                   5617: 	    $key = unescape($key) unless $escapedkeys;
                   5618: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  5619: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 5620: 	}
                   5621:     #return %returnhash;
                   5622:     return \%returnhash;
                   5623: }        
                   5624: 
                   5625: # see Lond::dump_with_regexp
                   5626: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5627: sub dump {
1.1180    droeschl 5628:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5629:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5630:     if (!$uname) { $uname=$env{'user.name'}; }
                   5631:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5632: 
1.1266    raeburn  5633:     if ($regexp) {
                   5634:         $regexp=&escape($regexp);
                   5635:     } else {
                   5636:         $regexp='.';
                   5637:     }
1.1180    droeschl 5638:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5639:         # user is hosted on this machine
1.1266    raeburn  5640:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5641:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5642:         return %{unserialize($reply, $escapedkeys)};
                   5643:     }
1.1166    raeburn  5644:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5645:     my @pairs=split(/\&/,$rep);
                   5646:     my %returnhash=();
1.1098    foxr     5647:     if (!($rep =~ /^error/ )) {
                   5648: 	foreach my $item (@pairs) {
                   5649: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5650:         $key = unescape($key) unless $escapedkeys;
                   5651:         #$key = &unescape($key);
1.1098    foxr     5652: 	    next if ($key =~ /^error: 2 /);
                   5653: 	    $returnhash{$key}=&thaw_unescape($value);
                   5654: 	}
1.755     albertel 5655:     }
                   5656:     return %returnhash;
1.407     www      5657: }
                   5658: 
1.1098    foxr     5659: 
1.717     albertel 5660: # --------------------------------------------------------- dumpstore interface
                   5661: 
                   5662: sub dumpstore {
                   5663:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5664:    # same as dump but keys must be escaped. They may contain colon separated
                   5665:    # lists of values that may themself contain colons (e.g. symbs).
                   5666:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5667: }
                   5668: 
1.407     www      5669: # -------------------------------------------------------------- keys interface
                   5670: 
                   5671: sub getkeys {
                   5672:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5673:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5674:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5675:    my $uhome=&homeserver($uname,$udomain);
                   5676:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5677:    my @keyarray=();
1.800     albertel 5678:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5679:       next if ($key =~ /^error: 2 /);
1.800     albertel 5680:       push(@keyarray,&unescape($key));
1.407     www      5681:    }
                   5682:    return @keyarray;
1.318     matthew  5683: }
                   5684: 
1.319     matthew  5685: # --------------------------------------------------------------- currentdump
                   5686: sub currentdump {
1.328     matthew  5687:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5688:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5689:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5690:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5691:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5692:    my $rep;
                   5693: 
                   5694:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5695:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5696:                    $courseid)));
                   5697:    } else {
                   5698:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5699:    }
                   5700: 
1.318     matthew  5701:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5702:    #
1.318     matthew  5703:    my %returnhash=();
1.319     matthew  5704:    #
                   5705:    if ($rep eq "unknown_cmd") { 
                   5706:        # an old lond will not know currentdump
                   5707:        # Do a dump and make it look like a currentdump
1.822     albertel 5708:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5709:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5710:        my %hash = @tmp;
                   5711:        @tmp=();
1.424     matthew  5712:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5713:    } else {
                   5714:        my @pairs=split(/\&/,$rep);
1.800     albertel 5715:        foreach my $pair (@pairs) {
                   5716:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5717:            my ($symb,$param) = split(/:/,$key);
                   5718:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5719:                                                         &thaw_unescape($value);
1.319     matthew  5720:        }
1.191     harris41 5721:    }
1.12      www      5722:    return %returnhash;
1.424     matthew  5723: }
                   5724: 
                   5725: sub convert_dump_to_currentdump{
                   5726:     my %hash = %{shift()};
                   5727:     my %returnhash;
                   5728:     # Code ripped from lond, essentially.  The only difference
                   5729:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5730:     # we might run in to problems with parameter names =~ /^v\./
                   5731:     while (my ($key,$value) = each(%hash)) {
                   5732:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5733: 	$symb  = &unescape($symb);
                   5734: 	$param = &unescape($param);
1.424     matthew  5735:         next if ($v eq 'version' || $symb eq 'keys');
                   5736:         next if (exists($returnhash{$symb}) &&
                   5737:                  exists($returnhash{$symb}->{$param}) &&
                   5738:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5739:         $returnhash{$symb}->{$param}=$value;
                   5740:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5741:     }
                   5742:     #
                   5743:     # Remove all of the keys in the hashes which keep track of
                   5744:     # the version of the parameter.
                   5745:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5746:         # use a foreach because we are going to delete from the hash.
                   5747:         foreach my $key (keys(%$param_hash)) {
                   5748:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5749:         }
                   5750:     }
                   5751:     return \%returnhash;
1.12      www      5752: }
                   5753: 
1.627     albertel 5754: # ------------------------------------------------------ critical inc interface
                   5755: 
                   5756: sub cinc {
                   5757:     return &inc(@_,'critical');
                   5758: }
                   5759: 
1.449     matthew  5760: # --------------------------------------------------------------- inc interface
                   5761: 
                   5762: sub inc {
1.627     albertel 5763:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5764:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5765:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5766:     my $uhome=&homeserver($uname,$udomain);
                   5767:     my $items='';
                   5768:     if (! ref($store)) {
                   5769:         # got a single value, so use that instead
                   5770:         $items = &escape($store).'=&';
                   5771:     } elsif (ref($store) eq 'SCALAR') {
                   5772:         $items = &escape($$store).'=&';        
                   5773:     } elsif (ref($store) eq 'ARRAY') {
                   5774:         $items = join('=&',map {&escape($_);} @{$store});
                   5775:     } elsif (ref($store) eq 'HASH') {
                   5776:         while (my($key,$value) = each(%{$store})) {
                   5777:             $items.= &escape($key).'='.&escape($value).'&';
                   5778:         }
                   5779:     }
                   5780:     $items=~s/\&$//;
1.627     albertel 5781:     if ($critical) {
                   5782: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5783:     } else {
                   5784: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5785:     }
1.449     matthew  5786: }
                   5787: 
1.12      www      5788: # --------------------------------------------------------------- put interface
                   5789: 
                   5790: sub put {
1.134     albertel 5791:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5792:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5793:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5794:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5795:    my $items='';
1.800     albertel 5796:    foreach my $item (keys(%$storehash)) {
                   5797:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5798:    }
1.12      www      5799:    $items=~s/\&$//;
1.134     albertel 5800:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5801: }
                   5802: 
1.631     albertel 5803: # ------------------------------------------------------------ newput interface
                   5804: 
                   5805: sub newput {
                   5806:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5807:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5808:    if (!$uname) { $uname=$env{'user.name'}; }
                   5809:    my $uhome=&homeserver($uname,$udomain);
                   5810:    my $items='';
                   5811:    foreach my $key (keys(%$storehash)) {
                   5812:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5813:    }
                   5814:    $items=~s/\&$//;
                   5815:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5816: }
                   5817: 
                   5818: # ---------------------------------------------------------  putstore interface
                   5819: 
1.524     raeburn  5820: sub putstore {
1.1269    raeburn  5821:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 5822:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5823:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5824:    my $uhome=&homeserver($uname,$udomain);
                   5825:    my $items='';
1.715     albertel 5826:    foreach my $key (keys(%$storehash)) {
                   5827:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5828:    }
1.715     albertel 5829:    $items=~s/\&$//;
1.716     albertel 5830:    my $esc_symb=&escape($symb);
                   5831:    my $esc_v=&escape($version);
1.715     albertel 5832:    my $reply =
1.716     albertel 5833:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5834: 	      $uhome);
1.1269    raeburn  5835:    if (($tolog) && ($reply eq 'ok')) {
                   5836:        my $namevalue='';
                   5837:        foreach my $key (keys(%{$storehash})) {
                   5838:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   5839:        }
                   5840:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   5841:                      '&host='.&escape($perlvar{'lonHostID'}).
                   5842:                      '&version='.$esc_v.
                   5843:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   5844:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   5845:    }
1.715     albertel 5846:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5847:        # gfall back to way things use to be done
1.715     albertel 5848:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5849: 			    $uname);
1.524     raeburn  5850:    }
1.715     albertel 5851:    return $reply;
                   5852: }
                   5853: 
                   5854: sub old_putstore {
1.716     albertel 5855:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5856:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5857:     if (!$uname) { $uname=$env{'user.name'}; }
                   5858:     my $uhome=&homeserver($uname,$udomain);
                   5859:     my %newstorehash;
1.800     albertel 5860:     foreach my $item (keys(%$storehash)) {
                   5861: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5862: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5863:     }
                   5864:     my $items='';
                   5865:     my %allitems = ();
1.800     albertel 5866:     foreach my $item (keys(%newstorehash)) {
                   5867: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5868: 	    my $key = $1.':keys:'.$2;
                   5869: 	    $allitems{$key} .= $3.':';
                   5870: 	}
1.800     albertel 5871: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5872:     }
1.800     albertel 5873:     foreach my $item (keys(%allitems)) {
                   5874: 	$allitems{$item} =~ s/\:$//;
                   5875: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5876:     }
                   5877:     $items=~s/\&$//;
                   5878:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5879: }
                   5880: 
1.47      www      5881: # ------------------------------------------------------ critical put interface
                   5882: 
                   5883: sub cput {
1.134     albertel 5884:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5885:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5886:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5887:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5888:    my $items='';
1.800     albertel 5889:    foreach my $item (keys(%$storehash)) {
                   5890:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5891:    }
1.47      www      5892:    $items=~s/\&$//;
1.134     albertel 5893:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5894: }
                   5895: 
                   5896: # -------------------------------------------------------------- eget interface
                   5897: 
                   5898: sub eget {
1.133     albertel 5899:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5900:    my $items='';
1.800     albertel 5901:    foreach my $item (@$storearr) {
                   5902:        $items.=&escape($item).'&';
1.191     harris41 5903:    }
1.12      www      5904:    $items=~s/\&$//;
1.620     albertel 5905:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5906:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5907:    my $uhome=&homeserver($uname,$udomain);
                   5908:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5909:    my @pairs=split(/\&/,$rep);
                   5910:    my %returnhash=();
1.42      www      5911:    my $i=0;
1.800     albertel 5912:    foreach my $item (@$storearr) {
                   5913:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5914:       $i++;
1.191     harris41 5915:    }
1.12      www      5916:    return %returnhash;
                   5917: }
                   5918: 
1.667     albertel 5919: # ------------------------------------------------------------ tmpput interface
                   5920: sub tmpput {
1.802     raeburn  5921:     my ($storehash,$server,$context)=@_;
1.667     albertel 5922:     my $items='';
1.800     albertel 5923:     foreach my $item (keys(%$storehash)) {
                   5924: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5925:     }
                   5926:     $items=~s/\&$//;
1.802     raeburn  5927:     if (defined($context)) {
                   5928:         $items .= ':'.&escape($context);
                   5929:     }
1.667     albertel 5930:     return &reply("tmpput:$items",$server);
                   5931: }
                   5932: 
                   5933: # ------------------------------------------------------------ tmpget interface
                   5934: sub tmpget {
1.688     albertel 5935:     my ($token,$server)=@_;
                   5936:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5937:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5938:     my %returnhash;
                   5939:     foreach my $item (split(/\&/,$rep)) {
                   5940: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5941:         next if ($key =~ /^error: 2 /);
1.667     albertel 5942: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5943:     }
                   5944:     return %returnhash;
                   5945: }
                   5946: 
1.1113    raeburn  5947: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5948: sub tmpdel {
                   5949:     my ($token,$server)=@_;
                   5950:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5951:     return &reply("tmpdel:$token",$server);
                   5952: }
                   5953: 
1.1198    raeburn  5954: # ------------------------------------------------------------ get_timebased_id 
                   5955: 
                   5956: sub get_timebased_id {
                   5957:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5958:         $maxtries) = @_;
                   5959:     my ($newid,$error,$dellock);
                   5960:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   5961:         return ('','ok','invalid call to get suffix');
                   5962:     }
                   5963: 
                   5964: # set defaults for any optional args for which values were not supplied
                   5965:     if ($who eq '') {
                   5966:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5967:     }
                   5968:     if (!$locktries) {
                   5969:         $locktries = 3;
                   5970:     }
                   5971:     if (!$maxtries) {
                   5972:         $maxtries = 10;
                   5973:     }
                   5974:     
                   5975:     if (($cdom eq '') || ($cnum eq '')) {
                   5976:         if ($env{'request.course.id'}) {
                   5977:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5978:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5979:         }
                   5980:         if (($cdom eq '') || ($cnum eq '')) {
                   5981:             return ('','ok','call to get suffix not in course context');
                   5982:         }
                   5983:     }
                   5984: 
                   5985: # construct locking item
                   5986:     my $lockhash = {
                   5987:                       $prefix."\0".'locked_'.$keyid => $who,
                   5988:                    };
                   5989:     my $tries = 0;
                   5990: 
                   5991: # attempt to get lock on nohist_$namespace file
                   5992:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5993:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5994:         $tries ++;
                   5995:         sleep 1;
                   5996:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5997:     }
                   5998: 
                   5999: # attempt to get unique identifier, based on current timestamp
                   6000:     if ($gotlock eq 'ok') {
                   6001:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6002:         my $id = time;
                   6003:         $newid = $id;
1.1268    raeburn  6004:         if ($idtype eq 'addcode') {
                   6005:             $newid .= &sixnum_code();
                   6006:         }
1.1198    raeburn  6007:         my $idtries = 0;
                   6008:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6009:             if ($idtype eq 'concat') {
                   6010:                 $newid = $id.$idtries;
1.1268    raeburn  6011:             } elsif ($idtype eq 'addcode') {
                   6012:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6013:             } else {
                   6014:                 $newid ++;
                   6015:             }
                   6016:             $idtries ++;
                   6017:         }
                   6018:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6019:             my %new_item =  (
                   6020:                               $prefix."\0".$newid => $who,
                   6021:                             );
                   6022:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6023:                                                  $cdom,$cnum);
                   6024:             if ($putresult ne 'ok') {
                   6025:                 undef($newid);
                   6026:                 $error = 'error saving new item: '.$putresult;
                   6027:             }
                   6028:         } else {
1.1268    raeburn  6029:              undef($newid);
1.1198    raeburn  6030:              $error = ('error: no unique suffix available for the new item ');
                   6031:         }
                   6032: #  remove lock
                   6033:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6034:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6035:     } else {
                   6036:         $error = "error: could not obtain lockfile\n";
                   6037:         $dellock = 'ok';
                   6038:     }
                   6039:     return ($newid,$dellock,$error);
                   6040: }
                   6041: 
1.1268    raeburn  6042: sub sixnum_code {
                   6043:     my $code;
                   6044:     for (0..6) {
                   6045:         $code .= int( rand(9) );
                   6046:     }
                   6047:     return $code;
                   6048: }
                   6049: 
1.765     albertel 6050: # -------------------------------------------------- portfolio access checking
                   6051: 
                   6052: sub portfolio_access {
1.1270    raeburn  6053:     my ($requrl,$clientip) = @_;
1.765     albertel 6054:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6055:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6056:     if ($result) {
                   6057:         my %setters;
                   6058:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6059:             my ($startblock,$endblock) =
                   6060:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6061:             if ($startblock && $endblock) {
                   6062:                 return 'B';
                   6063:             }
                   6064:         } else {
                   6065:             my ($startblock,$endblock) =
                   6066:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6067:             if ($startblock && $endblock) {
                   6068:                 return 'B';
                   6069:             }
                   6070:         }
                   6071:     }
1.765     albertel 6072:     if ($result eq 'ok') {
1.766     albertel 6073:        return 'F';
1.765     albertel 6074:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6075:        return 'A';
1.765     albertel 6076:     }
1.766     albertel 6077:     return '';
1.765     albertel 6078: }
                   6079: 
                   6080: sub get_portfolio_access {
1.1270    raeburn  6081:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6082: 
                   6083:     if (!ref($access_hash)) {
                   6084: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6085: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6086: 						   $file_name);
                   6087: 	$access_hash = $access_controls{$file_name};
                   6088:     }
                   6089: 
1.1270    raeburn  6090:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6091:     my $now = time;
                   6092:     if (ref($access_hash) eq 'HASH') {
                   6093:         foreach my $key (keys(%{$access_hash})) {
                   6094:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6095:             if ($start > $now) {
                   6096:                 next;
                   6097:             }
                   6098:             if ($end && $end<$now) {
                   6099:                 next;
                   6100:             }
                   6101:             if ($scope eq 'public') {
                   6102:                 $public = $key;
                   6103:                 last;
                   6104:             } elsif ($scope eq 'guest') {
                   6105:                 $guest = $key;
                   6106:             } elsif ($scope eq 'domains') {
                   6107:                 push(@domains,$key);
                   6108:             } elsif ($scope eq 'users') {
                   6109:                 push(@users,$key);
                   6110:             } elsif ($scope eq 'course') {
                   6111:                 push(@courses,$key);
                   6112:             } elsif ($scope eq 'group') {
                   6113:                 push(@groups,$key);
1.1270    raeburn  6114:             } elsif ($scope eq 'ip') {
                   6115:                 push(@ips,$key);
1.765     albertel 6116:             }
                   6117:         }
                   6118:         if ($public) {
                   6119:             return 'ok';
1.1270    raeburn  6120:         } elsif (@ips > 0) {
                   6121:             my $allowed;
                   6122:             foreach my $ipkey (@ips) {
                   6123:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6124:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6125:                         $allowed = 1;
                   6126:                         last; 
                   6127:                     }
                   6128:                 }
                   6129:             }
                   6130:             if ($allowed) {
                   6131:                 return 'ok';
                   6132:             }
1.765     albertel 6133:         }
                   6134:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6135:             if ($guest) {
                   6136:                 return $guest;
                   6137:             }
                   6138:         } else {
                   6139:             if (@domains > 0) {
                   6140:                 foreach my $domkey (@domains) {
                   6141:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6142:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6143:                             return 'ok';
                   6144:                         }
                   6145:                     }
                   6146:                 }
                   6147:             }
                   6148:             if (@users > 0) {
                   6149:                 foreach my $userkey (@users) {
1.865     raeburn  6150:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6151:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6152:                             if (ref($item) eq 'HASH') {
                   6153:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6154:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6155:                                     return 'ok';
                   6156:                                 }
                   6157:                             }
                   6158:                         }
                   6159:                     } 
1.765     albertel 6160:                 }
                   6161:             }
                   6162:             my %roleshash;
                   6163:             my @courses_and_groups = @courses;
                   6164:             push(@courses_and_groups,@groups); 
                   6165:             if (@courses_and_groups > 0) {
                   6166:                 my (%allgroups,%allroles); 
                   6167:                 my ($start,$end,$role,$sec,$group);
                   6168:                 foreach my $envkey (%env) {
1.1060    raeburn  6169:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6170:                         my $cid = $2.'_'.$3; 
                   6171:                         if ($1 eq 'gr') {
                   6172:                             $group = $4;
                   6173:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6174:                         } else {
                   6175:                             if ($4 eq '') {
                   6176:                                 $sec = 'none';
                   6177:                             } else {
                   6178:                                 $sec = $4;
                   6179:                             }
                   6180:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6181:                         }
1.811     albertel 6182:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6183:                         my $cid = $2.'_'.$3;
                   6184:                         if ($4 eq '') {
                   6185:                             $sec = 'none';
                   6186:                         } else {
                   6187:                             $sec = $4;
                   6188:                         }
                   6189:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6190:                     }
                   6191:                 }
                   6192:                 if (keys(%allroles) == 0) {
                   6193:                     return;
                   6194:                 }
                   6195:                 foreach my $key (@courses_and_groups) {
                   6196:                     my %content = %{$$access_hash{$key}};
                   6197:                     my $cnum = $content{'number'};
                   6198:                     my $cdom = $content{'domain'};
                   6199:                     my $cid = $cdom.'_'.$cnum;
                   6200:                     if (!exists($allroles{$cid})) {
                   6201:                         next;
                   6202:                     }    
                   6203:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6204:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6205:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6206:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6207:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6208:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6209:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6210:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6211:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6212:                                         if (grep/^all$/,@sections) {
                   6213:                                             return 'ok';
                   6214:                                         } else {
                   6215:                                             if (grep/^$sec$/,@sections) {
                   6216:                                                 return 'ok';
                   6217:                                             }
                   6218:                                         }
                   6219:                                     }
                   6220:                                 }
                   6221:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6222:                                     if (grep/^none$/,@groups) {
                   6223:                                         return 'ok';
                   6224:                                     }
                   6225:                                 } else {
                   6226:                                     if (grep/^all$/,@groups) {
                   6227:                                         return 'ok';
                   6228:                                     } 
                   6229:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6230:                                         if (grep/^$group$/,@groups) {
                   6231:                                             return 'ok';
                   6232:                                         }
                   6233:                                     }
                   6234:                                 } 
                   6235:                             }
                   6236:                         }
                   6237:                     }
                   6238:                 }
                   6239:             }
                   6240:             if ($guest) {
                   6241:                 return $guest;
                   6242:             }
                   6243:         }
                   6244:     }
                   6245:     return;
                   6246: }
                   6247: 
                   6248: sub course_group_datechecker {
                   6249:     my ($dates,$now,$status) = @_;
                   6250:     my ($start,$end) = split(/\./,$dates);
                   6251:     if (!$start && !$end) {
                   6252:         return 'ok';
                   6253:     }
                   6254:     if (grep/^active$/,@{$status}) {
                   6255:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6256:             return 'ok';
                   6257:         }
                   6258:     }
                   6259:     if (grep/^previous$/,@{$status}) {
                   6260:         if ($end > $now ) {
                   6261:             return 'ok';
                   6262:         }
                   6263:     }
                   6264:     if (grep/^future$/,@{$status}) {
                   6265:         if ($start > $now) {
                   6266:             return 'ok';
                   6267:         }
                   6268:     }
                   6269:     return; 
                   6270: }
                   6271: 
                   6272: sub parse_portfolio_url {
                   6273:     my ($url) = @_;
                   6274: 
                   6275:     my ($type,$udom,$unum,$group,$file_name);
                   6276:     
1.823     albertel 6277:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6278: 	$type = 1;
                   6279:         $udom = $1;
                   6280:         $unum = $2;
                   6281:         $file_name = $3;
1.823     albertel 6282:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6283: 	$type = 2;
                   6284:         $udom = $1;
                   6285:         $unum = $2;
                   6286:         $group = $3;
                   6287:         $file_name = $3.'/'.$4;
                   6288:     }
                   6289:     if (wantarray) {
                   6290: 	return ($type,$udom,$unum,$file_name,$group);
                   6291:     }
                   6292:     return $type;
                   6293: }
                   6294: 
                   6295: sub is_portfolio_url {
                   6296:     my ($url) = @_;
                   6297:     return scalar(&parse_portfolio_url($url));
                   6298: }
                   6299: 
1.798     raeburn  6300: sub is_portfolio_file {
                   6301:     my ($file) = @_;
1.820     raeburn  6302:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6303:         return 1;
                   6304:     }
                   6305:     return;
                   6306: }
                   6307: 
1.976     raeburn  6308: sub usertools_access {
1.1084    raeburn  6309:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6310:     my ($access,%tools);
                   6311:     if ($context eq '') {
                   6312:         $context = 'tools';
                   6313:     }
                   6314:     if ($context eq 'requestcourses') {
                   6315:         %tools = (
                   6316:                       official   => 1,
                   6317:                       unofficial => 1,
1.1006    raeburn  6318:                       community  => 1,
1.1246    raeburn  6319:                       textbook   => 1,
1.985     raeburn  6320:                  );
1.1183    raeburn  6321:     } elsif ($context eq 'requestauthor') {
                   6322:         %tools = (
                   6323:                       requestauthor => 1,
                   6324:                  );
1.985     raeburn  6325:     } else {
                   6326:         %tools = (
                   6327:                       aboutme   => 1,
                   6328:                       blog      => 1,
1.1177    raeburn  6329:                       webdav    => 1,
1.985     raeburn  6330:                       portfolio => 1,
                   6331:                  );
                   6332:     }
1.976     raeburn  6333:     return if (!defined($tools{$tool}));
                   6334: 
1.1242    raeburn  6335:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6336:         $udom = $env{'user.domain'};
                   6337:         $uname = $env{'user.name'};
                   6338:     }
                   6339: 
1.978     raeburn  6340:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6341:         if ($action ne 'reload') {
1.985     raeburn  6342:             if ($context eq 'requestcourses') {
                   6343:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6344:             } elsif ($context eq 'requestauthor') {
                   6345:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6346:             } else {
                   6347:                 return $env{'environment.availabletools.'.$tool};
                   6348:             }
                   6349:         }
1.976     raeburn  6350:     }
                   6351: 
1.1183    raeburn  6352:     my ($toolstatus,$inststatus,$envkey);
                   6353:     if ($context eq 'requestauthor') {
                   6354:         $envkey = $context; 
                   6355:     } else {
                   6356:         $envkey = $context.'.'.$tool;
                   6357:     }
1.976     raeburn  6358: 
1.985     raeburn  6359:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6360:          ($action ne 'reload')) {
1.1183    raeburn  6361:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6362:         $inststatus = $env{'environment.inststatus'};
                   6363:     } else {
1.1084    raeburn  6364:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6365:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6366:             $inststatus = $userenvref->{'inststatus'};
                   6367:         } else {
1.1183    raeburn  6368:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6369:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6370:             $inststatus = $userenv{'inststatus'};
                   6371:         }
1.976     raeburn  6372:     }
                   6373: 
                   6374:     if ($toolstatus ne '') {
                   6375:         if ($toolstatus) {
                   6376:             $access = 1;
                   6377:         } else {
                   6378:             $access = 0;
                   6379:         }
                   6380:         return $access;
                   6381:     }
                   6382: 
1.1084    raeburn  6383:     my ($is_adv,%domdef);
                   6384:     if (ref($is_advref) eq 'HASH') {
                   6385:         $is_adv = $is_advref->{'is_adv'};
                   6386:     } else {
                   6387:         $is_adv = &is_advanced_user($udom,$uname);
                   6388:     }
                   6389:     if (ref($domdefref) eq 'HASH') {
                   6390:         %domdef = %{$domdefref};
                   6391:     } else {
                   6392:         %domdef = &get_domain_defaults($udom);
                   6393:     }
1.976     raeburn  6394:     if (ref($domdef{$tool}) eq 'HASH') {
                   6395:         if ($is_adv) {
                   6396:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6397:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6398:                     $access = 1;
                   6399:                 } else {
                   6400:                     $access = 0;
                   6401:                 }
                   6402:                 return $access;
                   6403:             }
                   6404:         }
                   6405:         if ($inststatus ne '') {
                   6406:             my ($hasaccess,$hasnoaccess);
                   6407:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6408:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6409:                     if ($domdef{$tool}{$affiliation}) {
                   6410:                         $hasaccess = 1;
                   6411:                     } else {
                   6412:                         $hasnoaccess = 1;
                   6413:                     }
                   6414:                 }
                   6415:             }
                   6416:             if ($hasaccess || $hasnoaccess) {
                   6417:                 if ($hasaccess) {
                   6418:                     $access = 1;
                   6419:                 } elsif ($hasnoaccess) {
                   6420:                     $access = 0; 
                   6421:                 }
                   6422:                 return $access;
                   6423:             }
                   6424:         } else {
                   6425:             if ($domdef{$tool}{'default'} ne '') {
                   6426:                 if ($domdef{$tool}{'default'}) {
                   6427:                     $access = 1;
                   6428:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6429:                     $access = 0;
                   6430:                 }
                   6431:                 return $access;
                   6432:             }
                   6433:         }
                   6434:     } else {
1.1177    raeburn  6435:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6436:             $access = 1;
                   6437:         } else {
                   6438:             $access = 0;
                   6439:         }
1.976     raeburn  6440:         return $access;
                   6441:     }
                   6442: }
                   6443: 
1.1050    raeburn  6444: sub is_course_owner {
                   6445:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6446:     if (($udom eq '') || ($uname eq '')) {
                   6447:         $udom = $env{'user.domain'};
                   6448:         $uname = $env{'user.name'};
                   6449:     }
                   6450:     unless (($udom eq '') || ($uname eq '')) {
                   6451:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6452:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6453:                 return 1;
                   6454:             } else {
                   6455:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6456:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6457:                     return 1;
                   6458:                 }
                   6459:             }
                   6460:         }
                   6461:     }
                   6462:     return;
                   6463: }
                   6464: 
1.976     raeburn  6465: sub is_advanced_user {
                   6466:     my ($udom,$uname) = @_;
1.1085    raeburn  6467:     if ($udom ne '' && $uname ne '') {
                   6468:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6469:             if (wantarray) {
                   6470:                 return ($env{'user.adv'},$env{'user.author'});
                   6471:             } else {
                   6472:                 return $env{'user.adv'};
                   6473:             }
1.1085    raeburn  6474:         }
                   6475:     }
1.976     raeburn  6476:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6477:     my %allroles;
1.1128    raeburn  6478:     my ($is_adv,$is_author);
1.976     raeburn  6479:     foreach my $role (keys(%roleshash)) {
                   6480:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6481:         my $area = '/'.$tdomain.'/'.$trest;
                   6482:         if ($sec ne '') {
                   6483:             $area .= '/'.$sec;
                   6484:         }
                   6485:         if (($area ne '') && ($trole ne '')) {
                   6486:             my $spec=$trole.'.'.$area;
                   6487:             if ($trole =~ /^cr\//) {
                   6488:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6489:             } elsif ($trole ne 'gr') {
                   6490:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6491:             }
1.1128    raeburn  6492:             if ($trole eq 'au') {
                   6493:                 $is_author = 1;
                   6494:             }
1.976     raeburn  6495:         }
                   6496:     }
                   6497:     foreach my $role (keys(%allroles)) {
                   6498:         last if ($is_adv);
                   6499:         foreach my $item (split(/:/,$allroles{$role})) {
                   6500:             if ($item ne '') {
                   6501:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6502:                 if ($privilege eq 'adv') {
                   6503:                     $is_adv = 1;
                   6504:                     last;
                   6505:                 }
                   6506:             }
                   6507:         }
                   6508:     }
1.1128    raeburn  6509:     if (wantarray) {
                   6510:         return ($is_adv,$is_author);
                   6511:     }
1.976     raeburn  6512:     return $is_adv;
                   6513: }
1.798     raeburn  6514: 
1.1035    raeburn  6515: sub check_can_request {
1.1036    raeburn  6516:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6517:     my $canreq = 0;
                   6518:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6519:     my @options = ('approval','validate','autolimit');
                   6520:     my $optregex = join('|',@options);
                   6521:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6522:         foreach my $type (@{$types}) {
                   6523:             if (&usertools_access($env{'user.name'},
                   6524:                                   $env{'user.domain'},
                   6525:                                   $type,undef,'requestcourses')) {
                   6526:                 $canreq ++;
1.1036    raeburn  6527:                 if (ref($request_domains) eq 'HASH') {
                   6528:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6529:                 }
1.1035    raeburn  6530:                 if ($dom eq $env{'user.domain'}) {
                   6531:                     $can_request->{$type} = 1;
                   6532:                 }
                   6533:             }
                   6534:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6535:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6536:                 if (@curr > 0) {
1.1036    raeburn  6537:                     foreach my $item (@curr) {
                   6538:                         if (ref($request_domains) eq 'HASH') {
                   6539:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6540:                             if ($otherdom ne '') {
                   6541:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6542:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6543:                                         push(@{$request_domains->{$type}},$otherdom);
                   6544:                                     }
                   6545:                                 } else {
                   6546:                                     push(@{$request_domains->{$type}},$otherdom);
                   6547:                                 }
                   6548:                             }
                   6549:                         }
                   6550:                     }
                   6551:                     unless($dom eq $env{'user.domain'}) {
                   6552:                         $canreq ++;
1.1035    raeburn  6553:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6554:                             $can_request->{$type} = 1;
                   6555:                         }
                   6556:                     }
                   6557:                 }
                   6558:             }
                   6559:         }
                   6560:     }
                   6561:     return $canreq;
                   6562: }
                   6563: 
1.341     www      6564: # ---------------------------------------------- Custom access rule evaluation
                   6565: 
                   6566: sub customaccess {
                   6567:     my ($priv,$uri)=@_;
1.807     albertel 6568:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6569:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6570:     $udom = &LONCAPA::clean_domain($udom);
                   6571:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6572:     my $access=0;
1.800     albertel 6573:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6574: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6575: 	if ($type eq 'user') {
                   6576: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6577: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6578: 		if ($tdom) {
                   6579: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6580: 		}
1.896     albertel 6581: 		if ($tuname) {
                   6582: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6583: 		}
                   6584: 		$access=($effect eq 'allow');
                   6585: 		last;
                   6586: 	    }
                   6587: 	} else {
                   6588: 	    if ($role) {
                   6589: 		if ($role ne $urole) { next; }
                   6590: 	    }
                   6591: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6592: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6593: 		if ($tdom) {
                   6594: 		    if ($tdom ne $udom) { next; }
                   6595: 		}
                   6596: 		if ($tcrs) {
                   6597: 		    if ($tcrs ne $ucrs) { next; }
                   6598: 		}
                   6599: 		if ($tsec) {
                   6600: 		    if ($tsec ne $usec) { next; }
                   6601: 		}
                   6602: 		$access=($effect eq 'allow');
                   6603: 		last;
                   6604: 	    }
                   6605: 	    if ($realm eq '' && $role eq '') {
                   6606: 		$access=($effect eq 'allow');
                   6607: 	    }
1.402     bowersj2 6608: 	}
1.341     www      6609:     }
                   6610:     return $access;
                   6611: }
                   6612: 
1.103     harris41 6613: # ------------------------------------------------- Check for a user privilege
1.12      www      6614: 
                   6615: sub allowed {
1.1270    raeburn  6616:     my ($priv,$uri,$symb,$role,$clientip)=@_;
1.705     albertel 6617:     my $ver_orguri=$uri;
1.439     www      6618:     $uri=&deversion($uri);
1.152     www      6619:     my $orguri=$uri;
1.52      www      6620:     $uri=&declutter($uri);
1.809     raeburn  6621: 
1.810     raeburn  6622:     if ($priv eq 'evb') {
                   6623: # Evade communication block restrictions for specified role in a course
                   6624:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6625:             return $1;
                   6626:         } else {
                   6627:             return;
                   6628:         }
                   6629:     }
                   6630: 
1.620     albertel 6631:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6632: # Free bre access to adm and meta resources
1.775     albertel 6633:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6634: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6635: 	&& ($priv eq 'bre')) {
1.14      www      6636: 	return 'F';
1.159     www      6637:     }
                   6638: 
1.545     banghart 6639: # Free bre access to user's own portfolio contents
1.714     raeburn  6640:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6641:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6642: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6643:         my %setters;
                   6644:         my ($startblock,$endblock) = 
                   6645:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6646:         if ($startblock && $endblock) {
                   6647:             return 'B';
                   6648:         } else {
                   6649:             return 'F';
                   6650:         }
1.545     banghart 6651:     }
                   6652: 
1.762     raeburn  6653: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6654:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6655:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6656:         if (exists($env{'request.course.id'})) {
                   6657:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6658:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6659:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6660:                 my $courseprivid=$env{'request.course.id'};
                   6661:                 $courseprivid=~s/\_/\//;
                   6662:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6663:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6664:                     return $1; 
1.762     raeburn  6665:                 } else {
                   6666:                     if ($env{'request.course.sec'}) {
                   6667:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6668:                     }
                   6669:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6670:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6671:                         return $2;
                   6672:                     }
1.714     raeburn  6673:                 }
                   6674:             }
                   6675:         }
                   6676:     }
                   6677: 
1.159     www      6678: # Free bre to public access
                   6679: 
                   6680:     if ($priv eq 'bre') {
1.238     www      6681:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6682: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6683:            return 'F'; 
                   6684:         }
1.238     www      6685:         if ($copyright eq 'priv') {
                   6686:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6687: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6688: 		return '';
                   6689:             }
                   6690:         }
                   6691:         if ($copyright eq 'domain') {
                   6692:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6693: 	    unless (($env{'user.domain'} eq $1) ||
                   6694:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6695: 		return '';
                   6696:             }
1.262     matthew  6697:         }
1.620     albertel 6698:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6699:             # Library role, so allow browsing of resources in this domain.
                   6700:             return 'F';
1.238     www      6701:         }
1.341     www      6702:         if ($copyright eq 'custom') {
                   6703: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6704:         }
1.14      www      6705:     }
1.264     matthew  6706:     # Domain coordinator is trying to create a course
1.620     albertel 6707:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6708:         # uri is the requested domain in this case.
                   6709:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6710:         # a role of dc for the domain in question.
1.620     albertel 6711:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6712:     }
1.29      www      6713: 
1.52      www      6714:     my $thisallowed='';
                   6715:     my $statecond=0;
                   6716:     my $courseprivid='';
                   6717: 
1.1039    raeburn  6718:     my $ownaccess;
1.1043    raeburn  6719:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6720:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6721:         if ($uri eq '') {
                   6722:             $ownaccess = 1;
                   6723:         } else {
                   6724:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6725:                 my $udom = $env{'user.domain'};
                   6726:                 my $uname = $env{'user.name'};
                   6727:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6728:                     $ownaccess = 1;
1.1040    raeburn  6729:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6730:                     unless ($uri =~ m{\.\./}) {
                   6731:                         $ownaccess = 1;
                   6732:                     }
                   6733:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6734:                     my $now = time;
                   6735:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6736:                         my $adom = $1;
                   6737:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6738:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6739:                                 my ($start,$end) = split('.',$env{$key});
                   6740:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6741:                                     $ownaccess = 1;
                   6742:                                     last;
                   6743:                                 }
                   6744:                             }
                   6745:                         }
                   6746:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6747:                         my $adom = $1;
                   6748:                         my $aname = $2;
1.1042    raeburn  6749:                         foreach my $role ('ca','aa') { 
                   6750:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6751:                                 my ($start,$end) =
                   6752:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6753:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6754:                                     $ownaccess = 1;
                   6755:                                     last;
                   6756:                                 }
1.1039    raeburn  6757:                             }
                   6758:                         }
                   6759:                     }
                   6760:                 }
                   6761:             }
                   6762:         }
                   6763:     }
                   6764: 
1.52      www      6765: # Course
                   6766: 
1.620     albertel 6767:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6768:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6769:             $thisallowed.=$1;
                   6770:         }
1.52      www      6771:     }
1.29      www      6772: 
1.52      www      6773: # Domain
                   6774: 
1.620     albertel 6775:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6776:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6777:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6778:             $thisallowed.=$1;
                   6779:         }
1.12      www      6780:     }
1.52      www      6781: 
1.1141    raeburn  6782: # User who is not author or co-author might still be able to edit
                   6783: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6784:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6785:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6786:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6787:             $thisallowed.=$1;
                   6788:         }
                   6789:     }
                   6790: 
1.52      www      6791: # Course: uri itself is a course
1.66      www      6792:     my $courseuri=$uri;
                   6793:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6794:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6795: 
1.620     albertel 6796:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6797:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6798:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6799:             $thisallowed.=$1;
                   6800:         }
1.12      www      6801:     }
1.29      www      6802: 
1.665     albertel 6803: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6804: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6805:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6806: 	$thisallowed='';
1.671     raeburn  6807:         my ($match)=&is_on_map($uri);
                   6808:         if ($match) {
                   6809:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6810:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6811:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6812:                 if (@blockers > 0) {
                   6813:                     $thisallowed = 'B';
                   6814:                 } else {
                   6815:                     $thisallowed.=$1;
                   6816:                 }
1.671     raeburn  6817:             }
                   6818:         } else {
1.705     albertel 6819:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6820:             if ($refuri) {
                   6821:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6822:                     $thisallowed='F';
1.671     raeburn  6823:                 } else {
                   6824:                     $refuri=&declutter($refuri);
                   6825:                     my ($match) = &is_on_map($refuri);
                   6826:                     if ($match) {
1.1162    raeburn  6827:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6828:                         if (@blockers > 0) {
                   6829:                             $thisallowed = 'B';
                   6830:                         } else {
                   6831:                             $thisallowed='F';
                   6832:                         }
1.671     raeburn  6833:                     }
1.669     raeburn  6834:                 }
1.671     raeburn  6835:             }
                   6836:         }
1.314     www      6837:     }
1.492     albertel 6838: 
1.766     albertel 6839:     if ($priv eq 'bre'
                   6840: 	&& $thisallowed ne 'F' 
                   6841: 	&& $thisallowed ne '2'
                   6842: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  6843: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 6844:     }
1.1250    raeburn  6845: 
1.52      www      6846: # Full access at system, domain or course-wide level? Exit.
1.29      www      6847:     if ($thisallowed=~/F/) {
                   6848: 	return 'F';
                   6849:     }
                   6850: 
1.52      www      6851: # If this is generating or modifying users, exit with special codes
1.29      www      6852: 
1.643     www      6853:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6854: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6855: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6856: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6857: 	    unless ($auname) { return $thisallowed; }
                   6858: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6859: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6860: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6861: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6862: 	}
1.52      www      6863: 	return $thisallowed;
                   6864:     }
                   6865: #
1.103     harris41 6866: # Gathered so far: system, domain and course wide privileges
1.52      www      6867: #
                   6868: # Course: See if uri or referer is an individual resource that is part of 
                   6869: # the course
                   6870: 
1.620     albertel 6871:     if ($env{'request.course.id'}) {
1.232     www      6872: 
1.620     albertel 6873:        $courseprivid=$env{'request.course.id'};
                   6874:        if ($env{'request.course.sec'}) {
                   6875:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6876:        }
                   6877:        $courseprivid=~s/\_/\//;
                   6878:        my $checkreferer=1;
1.232     www      6879:        my ($match,$cond)=&is_on_map($uri);
                   6880:        if ($match) {
                   6881:            $statecond=$cond;
1.620     albertel 6882:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6883:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6884:                my $value = $1;
                   6885:                if ($priv eq 'bre') {
                   6886:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6887:                    if (@blockers > 0) {
                   6888:                        $thisallowed = 'B';
                   6889:                    } else {
                   6890:                        $thisallowed.=$value;
                   6891:                    }
                   6892:                } else {
                   6893:                    $thisallowed.=$value;
                   6894:                }
1.52      www      6895:                $checkreferer=0;
                   6896:            }
1.29      www      6897:        }
1.83      www      6898:        
1.148     www      6899:        if ($checkreferer) {
1.620     albertel 6900: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6901:             unless ($refuri) {
1.800     albertel 6902:                 foreach my $key (keys(%env)) {
                   6903: 		    if ($key=~/^httpref\..*\*/) {
                   6904: 			my $pattern=$key;
1.156     www      6905:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6906:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6907:                         $pattern=~s/\//\\\//g;
1.152     www      6908:                         if ($orguri=~/$pattern/) {
1.800     albertel 6909: 			    $refuri=$env{$key};
1.148     www      6910:                         }
                   6911:                     }
1.191     harris41 6912:                 }
1.148     www      6913:             }
1.232     www      6914: 
1.148     www      6915:          if ($refuri) { 
1.152     www      6916: 	  $refuri=&declutter($refuri);
1.232     www      6917:           my ($match,$cond)=&is_on_map($refuri);
                   6918:             if ($match) {
                   6919:               my $refstatecond=$cond;
1.620     albertel 6920:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6921:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6922:                   my $value = $1;
                   6923:                   if ($priv eq 'bre') {
                   6924:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6925:                       if (@blockers > 0) {
                   6926:                           $thisallowed = 'B';
                   6927:                       } else {
                   6928:                           $thisallowed.=$value;
                   6929:                       }
                   6930:                   } else {
                   6931:                       $thisallowed.=$value;
                   6932:                   }
1.53      www      6933:                   $uri=$refuri;
                   6934:                   $statecond=$refstatecond;
1.52      www      6935:               }
                   6936:           }
1.148     www      6937:         }
1.29      www      6938:        }
1.52      www      6939:    }
1.29      www      6940: 
1.52      www      6941: #
1.103     harris41 6942: # Gathered now: all privileges that could apply, and condition number
1.52      www      6943: # 
                   6944: #
                   6945: # Full or no access?
                   6946: #
1.29      www      6947: 
1.52      www      6948:     if ($thisallowed=~/F/) {
                   6949: 	return 'F';
                   6950:     }
1.29      www      6951: 
1.52      www      6952:     unless ($thisallowed) {
                   6953:         return '';
                   6954:     }
1.29      www      6955: 
1.52      www      6956: # Restrictions exist, deal with them
                   6957: #
                   6958: #   C:according to course preferences
                   6959: #   R:according to resource settings
                   6960: #   L:unless locked
                   6961: #   X:according to user session state
                   6962: #
                   6963: 
                   6964: # Possibly locked functionality, check all courses
1.54      www      6965: # Locks might take effect only after 10 minutes cache expiration for other
                   6966: # courses, and 2 minutes for current course
1.52      www      6967: 
                   6968:     my $envkey;
                   6969:     if ($thisallowed=~/L/) {
1.1000    raeburn  6970:         foreach $envkey (keys(%env)) {
1.54      www      6971:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6972:                my $courseid=$2;
                   6973:                my $roleid=$1.'.'.$2;
1.92      www      6974:                $courseid=~s/^\///;
1.54      www      6975:                my $expiretime=600;
1.620     albertel 6976:                if ($env{'request.role'} eq $roleid) {
1.54      www      6977: 		  $expiretime=120;
                   6978:                }
                   6979: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6980:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6981:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6982: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6983:                }
1.620     albertel 6984:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6985:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6986: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6987:                        &log($env{'user.domain'},$env{'user.name'},
                   6988:                             $env{'user.home'},
1.57      www      6989:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6990:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6991:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6992: 		       return '';
                   6993:                    }
                   6994:                }
1.620     albertel 6995:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6996:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6997: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6998:                        &log($env{'user.domain'},$env{'user.name'},
                   6999:                             $env{'user.home'},
1.57      www      7000:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7001:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7002:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7003: 		       return '';
                   7004:                    }
                   7005:                }
                   7006: 	   }
1.29      www      7007:        }
1.52      www      7008:     }
                   7009:    
                   7010: #
                   7011: # Rest of the restrictions depend on selected course
                   7012: #
                   7013: 
1.620     albertel 7014:     unless ($env{'request.course.id'}) {
1.766     albertel 7015: 	if ($thisallowed eq 'A') {
                   7016: 	    return 'A';
1.814     raeburn  7017:         } elsif ($thisallowed eq 'B') {
                   7018:             return 'B';
1.766     albertel 7019: 	} else {
                   7020: 	    return '1';
                   7021: 	}
1.52      www      7022:     }
1.29      www      7023: 
1.52      www      7024: #
                   7025: # Now user is definitely in a course
                   7026: #
1.53      www      7027: 
                   7028: 
                   7029: # Course preferences
                   7030: 
                   7031:    if ($thisallowed=~/C/) {
1.620     albertel 7032:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7033:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7034:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7035: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7036: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7037: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7038: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7039: 			$env{'request.course.id'});
                   7040: 	   }
1.237     www      7041:            return '';
                   7042:        }
                   7043: 
1.620     albertel 7044:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7045: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7046: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7047: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7048: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7049: 			$env{'request.course.id'});
                   7050: 	   }
1.54      www      7051:            return '';
                   7052:        }
1.53      www      7053:    }
                   7054: 
                   7055: # Resource preferences
                   7056: 
                   7057:    if ($thisallowed=~/R/) {
1.620     albertel 7058:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7059:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7060: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7061: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7062: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7063: 	   }
                   7064: 	   return '';
1.54      www      7065:        }
1.53      www      7066:    }
1.30      www      7067: 
1.246     www      7068: # Restricted by state or randomout?
1.30      www      7069: 
1.52      www      7070:    if ($thisallowed=~/X/) {
1.620     albertel 7071:       if ($env{'acc.randomout'}) {
1.579     albertel 7072: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7073:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7074:             return ''; 
                   7075:          }
1.247     www      7076:       }
                   7077:       if (&condval($statecond)) {
1.52      www      7078: 	 return '2';
                   7079:       } else {
                   7080:          return '';
                   7081:       }
                   7082:    }
1.30      www      7083: 
1.766     albertel 7084:     if ($thisallowed eq 'A') {
                   7085: 	return 'A';
1.814     raeburn  7086:     } elsif ($thisallowed eq 'B') {
                   7087:         return 'B';
1.766     albertel 7088:     }
1.52      www      7089:    return 'F';
1.232     www      7090: }
1.1162    raeburn  7091: 
1.1192    raeburn  7092: # ------------------------------------------- Check construction space access
                   7093: 
                   7094: sub constructaccess {
                   7095:     my ($url,$setpriv)=@_;
                   7096: 
                   7097: # We do not allow editing of previous versions of files
                   7098:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7099: 
                   7100: # Get username and domain from URL
                   7101:     my ($ownername,$ownerdomain,$ownerhome);
                   7102: 
                   7103:     ($ownerdomain,$ownername) =
                   7104:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   7105: 
                   7106: # The URL does not really point to any authorspace, forget it
                   7107:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7108: 
                   7109: # Now we need to see if the user has access to the authorspace of
                   7110: # $ownername at $ownerdomain
                   7111: 
                   7112:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7113: # Real author for this?
                   7114:        $ownerhome = $env{'user.home'};
                   7115:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7116:           return ($ownername,$ownerdomain,$ownerhome);
                   7117:        }
                   7118:     } else {
                   7119: # Co-author for this?
                   7120:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7121:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7122:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7123:             return ($ownername,$ownerdomain,$ownerhome);
                   7124:         }
                   7125:     }
                   7126: 
                   7127: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7128: # we might as well leave
                   7129:    unless ($setpriv) { return ''; }
                   7130: 
                   7131: # Backdoor access?
                   7132:     my $allowed=&allowed('eco',$ownerdomain);
                   7133: # Nope
                   7134:     unless ($allowed) { return ''; }
                   7135: # Looks like we may have access, but could be locked by the owner of the construction space
                   7136:     if ($allowed eq 'U') {
                   7137:         my %blocked=&get('environment',['domcoord.author'],
                   7138:                          $ownerdomain,$ownername);
                   7139: # Is blocked by owner
                   7140:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7141:     }
                   7142:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7143: # Grant temporary access
                   7144:         my $then=$env{'user.login.time'};
1.1209    raeburn  7145:         my $update=$env{'user.update.time'};
1.1192    raeburn  7146:         if (!$update) { $update = $then; }
                   7147:         my $refresh=$env{'user.refresh.time'};
                   7148:         if (!$refresh) { $refresh = $update; }
                   7149:         my $now = time;
                   7150:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7151:                            $now,'ca','constructaccess');
                   7152:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7153:         return($ownername,$ownerdomain,$ownerhome);
                   7154:     }
                   7155: # No business here
                   7156:     return '';
                   7157: }
                   7158: 
1.1162    raeburn  7159: sub get_comm_blocks {
                   7160:     my ($cdom,$cnum) = @_;
                   7161:     if ($cdom eq '' || $cnum eq '') {
                   7162:         return unless ($env{'request.course.id'});
                   7163:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7164:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7165:     }
                   7166:     my %commblocks;
                   7167:     my $hashid=$cdom.'_'.$cnum;
                   7168:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7169:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7170:         %commblocks = %{$blocksref};
                   7171:     } else {
                   7172:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7173:         my $cachetime = 600;
                   7174:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7175:     }
                   7176:     return %commblocks;
                   7177: }
                   7178: 
                   7179: sub has_comm_blocking {
                   7180:     my ($priv,$symb,$uri,$blocks) = @_;
                   7181:     return unless ($env{'request.course.id'});
                   7182:     return unless ($priv eq 'bre');
                   7183:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7184:     my %commblocks;
                   7185:     if (ref($blocks) eq 'HASH') {
                   7186:         %commblocks = %{$blocks};
                   7187:     } else {
                   7188:         %commblocks = &get_comm_blocks();
                   7189:     }
                   7190:     return unless (keys(%commblocks) > 0);
                   7191:     if (!$symb) { $symb=&symbread($uri,1); }
                   7192:     my ($map,$resid,undef)=&decode_symb($symb);
                   7193:     my %tocheck = (
                   7194:                     maps      => $map,
                   7195:                     resources => $symb,
                   7196:                   );
                   7197:     my @blockers;
                   7198:     my $now = time;
1.1163    raeburn  7199:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7200:     foreach my $block (keys(%commblocks)) {
                   7201:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7202:             my ($start,$end) = ($1,$2);
                   7203:             if ($start <= $now && $end >= $now) {
                   7204:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7205:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7206:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7207:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7208:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7209:                                     push(@blockers,$block);
                   7210:                                 }
                   7211:                             }
                   7212:                         }
                   7213:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7214:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7215:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7216:                                     push(@blockers,$block);
                   7217:                                 }
                   7218:                             }
                   7219:                         }
                   7220:                     }
                   7221:                 }
                   7222:             }
                   7223:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7224:             my $item = $1;
1.1163    raeburn  7225:             my @to_test;
1.1162    raeburn  7226:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7227:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7228:                     my $check_interval;
                   7229:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7230:                         my @interval;
                   7231:                         my $type = 'map';
                   7232:                         if ($item eq 'course') {
                   7233:                             $type = 'course';
                   7234:                             @interval=&EXT("resource.0.interval");
                   7235:                         } else {
                   7236:                             if ($item =~ /___\d+___/) {
                   7237:                                 $type = 'resource';
                   7238:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7239:                                 if (ref($navmap)) {                        
                   7240:                                     my $res = $navmap->getBySymb($item); 
                   7241:                                     push(@to_test,$res);
                   7242:                                 }
1.1162    raeburn  7243:                             } else {
                   7244:                                 my $mapsymb = &symbread($item,1);
                   7245:                                 if ($mapsymb) {
                   7246:                                     if (ref($navmap)) {
                   7247:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7248:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7249:                                         foreach my $res (@to_test) {
1.1162    raeburn  7250:                                             my $symb = $res->symb();
                   7251:                                             next if ($symb eq $mapsymb);
                   7252:                                             if ($symb ne '') {
                   7253:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7254:                                                 last;
                   7255:                                             }
                   7256:                                         }
                   7257:                                     }
                   7258:                                 }
                   7259:                             }
                   7260:                         }
                   7261:                         if ($interval[0] =~ /\d+/) {
                   7262:                             my $first_access;
                   7263:                             if ($type eq 'resource') {
                   7264:                                 $first_access=&get_first_access($interval[1],$item);
                   7265:                             } elsif ($type eq 'map') {
                   7266:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7267:                             } else {
                   7268:                                 $first_access=&get_first_access($interval[1]);
                   7269:                             }
                   7270:                             if ($first_access) {
                   7271:                                 my $timesup = $first_access+$interval[0];
                   7272:                                 if ($timesup > $now) {
1.1163    raeburn  7273:                                     foreach my $res (@to_test) {
                   7274:                                         if ($res->is_problem()) {
                   7275:                                             if ($res->completable()) {
                   7276:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7277:                                                     push(@blockers,$block);
                   7278:                                                 }
                   7279:                                                 last;
                   7280:                                             }
                   7281:                                         }
1.1162    raeburn  7282:                                     }
                   7283:                                 }
                   7284:                             }
                   7285:                         }
                   7286:                     }
                   7287:                 }
                   7288:             }
                   7289:         }
                   7290:     }
                   7291:     return @blockers;
                   7292: }
                   7293: 
                   7294: sub check_docs_block {
                   7295:     my ($docsblock,$tocheck) =@_;
                   7296:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7297:         return;
                   7298:     }
                   7299:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7300:         if ($tocheck->{'maps'}) {
                   7301:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7302:                 return 1;
                   7303:             }
                   7304:         }
                   7305:     }
                   7306:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7307:         if ($tocheck->{'resources'}) {
                   7308:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7309:                 return 1;
                   7310:             }
                   7311:         }
                   7312:     }
                   7313:     return;
                   7314: }
                   7315: 
1.1133    foxr     7316: #
                   7317: #   Removes the versino from a URI and
                   7318: #   splits it in to its filename and path to the filename.
                   7319: #   Seems like File::Basename could have done this more clearly.
                   7320: #   Parameters:
                   7321: #      $uri   - input URI
                   7322: #   Returns:
                   7323: #     Two element list consisting of 
                   7324: #     $pathname  - the URI up to and excluding the trailing /
                   7325: #     $filename  - The part of the URI following the last /
                   7326: #  NOTE:
                   7327: #    Another realization of this is simply:
                   7328: #    use File::Basename;
                   7329: #    ...
                   7330: #    $uri = shift;
                   7331: #    $filename = basename($uri);
                   7332: #    $path     = dirname($uri);
                   7333: #    return ($filename, $path);
                   7334: #
                   7335: #     The implementation below is probably faster however.
                   7336: #
1.710     albertel 7337: sub split_uri_for_cond {
                   7338:     my $uri=&deversion(&declutter(shift));
                   7339:     my @uriparts=split(/\//,$uri);
                   7340:     my $filename=pop(@uriparts);
                   7341:     my $pathname=join('/',@uriparts);
                   7342:     return ($pathname,$filename);
                   7343: }
1.232     www      7344: # --------------------------------------------------- Is a resource on the map?
                   7345: 
                   7346: sub is_on_map {
1.710     albertel 7347:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7348:     #Trying to find the conditional for the file
1.620     albertel 7349:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7350: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7351:     if ($match) {
1.289     bowersj2 7352: 	return (1,$1);
                   7353:     } else {
1.434     www      7354: 	return (0,0);
1.289     bowersj2 7355:     }
1.12      www      7356: }
                   7357: 
1.427     www      7358: # --------------------------------------------------------- Get symb from alias
                   7359: 
                   7360: sub get_symb_from_alias {
                   7361:     my $symb=shift;
                   7362:     my ($map,$resid,$url)=&decode_symb($symb);
                   7363: # Already is a symb
                   7364:     if ($url) { return $symb; }
                   7365: # Must be an alias
                   7366:     my $aliassymb='';
                   7367:     my %bighash;
1.620     albertel 7368:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7369:                             &GDBM_READER(),0640)) {
                   7370:         my $rid=$bighash{'mapalias_'.$symb};
                   7371: 	if ($rid) {
                   7372: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7373: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7374: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7375: 	}
                   7376:         untie %bighash;
                   7377:     }
                   7378:     return $aliassymb;
                   7379: }
                   7380: 
1.12      www      7381: # ----------------------------------------------------------------- Define Role
                   7382: 
                   7383: sub definerole {
                   7384:   if (allowed('mcr','/')) {
                   7385:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7386:     foreach my $role (split(':',$sysrole)) {
                   7387: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7388:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7389:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7390: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7391:                return "refused:s:$crole&$cqual"; 
                   7392:             }
                   7393:         }
1.191     harris41 7394:     }
1.800     albertel 7395:     foreach my $role (split(':',$domrole)) {
                   7396: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7397:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7398:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7399: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7400:                return "refused:d:$crole&$cqual"; 
                   7401:             }
                   7402:         }
1.191     harris41 7403:     }
1.800     albertel 7404:     foreach my $role (split(':',$courole)) {
                   7405: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7406:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7407:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7408: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7409:                return "refused:c:$crole&$cqual"; 
                   7410:             }
                   7411:         }
1.191     harris41 7412:     }
1.620     albertel 7413:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7414:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7415: 	        "rolesdef_$rolename=".
                   7416:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7417:     return reply($command,$env{'user.home'});
1.12      www      7418:   } else {
                   7419:     return 'refused';
                   7420:   }
1.105     harris41 7421: }
                   7422: 
                   7423: # ---------------- Make a metadata query against the network of library servers
                   7424: 
                   7425: sub metadata_query {
1.1237    raeburn  7426:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7427:     my %rhash;
1.845     albertel 7428:     my %libserv = &all_library();
1.244     matthew  7429:     my @server_list = (defined($server_array) ? @$server_array
                   7430:                                               : keys(%libserv) );
                   7431:     for my $server (@server_list) {
1.1237    raeburn  7432:         my $domains = ''; 
                   7433:         if (ref($domains_hash) eq 'HASH') {
                   7434:             $domains = $domains_hash->{$server}; 
                   7435:         }
1.118     harris41 7436: 	unless ($custom or $customshow) {
1.1237    raeburn  7437: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7438: 	    $rhash{$server}=$reply;
                   7439: 	}
                   7440: 	else {
                   7441: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7442: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7443: 			     $server);
                   7444: 	    $rhash{$server}=$reply;
                   7445: 	}
1.112     harris41 7446:     }
1.118     harris41 7447:     return \%rhash;
1.240     www      7448: }
                   7449: 
                   7450: # ----------------------------------------- Send log queries and wait for reply
                   7451: 
                   7452: sub log_query {
                   7453:     my ($uname,$udom,$query,%filters)=@_;
                   7454:     my $uhome=&homeserver($uname,$udom);
                   7455:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7456:     my $uhost=&hostname($uhome);
1.800     albertel 7457:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7458:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7459:                        $uhome);
1.479     albertel 7460:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7461:     return get_query_reply($queryid);
                   7462: }
                   7463: 
1.818     raeburn  7464: # -------------------------- Update MySQL table for portfolio file
                   7465: 
                   7466: sub update_portfolio_table {
1.821     raeburn  7467:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7468:     if ($group ne '') {
                   7469:         $file_name =~s /^\Q$group\E//;
                   7470:     }
1.818     raeburn  7471:     my $homeserver = &homeserver($uname,$udom);
                   7472:     my $queryid=
1.821     raeburn  7473:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7474:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7475:     my $reply = &get_query_reply($queryid);
                   7476:     return $reply;
                   7477: }
                   7478: 
1.899     raeburn  7479: # -------------------------- Update MySQL allusers table
                   7480: 
                   7481: sub update_allusers_table {
                   7482:     my ($uname,$udom,$names) = @_;
                   7483:     my $homeserver = &homeserver($uname,$udom);
                   7484:     my $queryid=
                   7485:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7486:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7487:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7488:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7489:                'generation='.&escape($names->{'generation'}).'%%'.
                   7490:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7491:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7492:     return;
1.899     raeburn  7493: }
                   7494: 
1.508     raeburn  7495: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7496: 
                   7497: sub fetch_enrollment_query {
1.511     raeburn  7498:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7499:     my $homeserver;
1.547     raeburn  7500:     my $maxtries = 1;
1.508     raeburn  7501:     if ($context eq 'automated') {
                   7502:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7503:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7504:     } else {
                   7505:         $homeserver = &homeserver($cnum,$dom);
                   7506:     }
1.838     albertel 7507:     my $host=&hostname($homeserver);
1.506     raeburn  7508:     my $cmd = '';
1.1000    raeburn  7509:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7510:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7511:     }
                   7512:     $cmd =~ s/%%$//;
                   7513:     $cmd = &escape($cmd);
                   7514:     my $query = 'fetchenrollment';
1.620     albertel 7515:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7516:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7517:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7518:         return 'error: '.$queryid;
                   7519:     }
1.506     raeburn  7520:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7521:     my $tries = 1;
                   7522:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7523:         $reply = &get_query_reply($queryid);
                   7524:         $tries ++;
                   7525:     }
1.526     raeburn  7526:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7527:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7528:     } else {
1.901     albertel 7529:         my @responses = split(/:/,$reply);
1.515     raeburn  7530:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7531:             foreach my $line (@responses) {
                   7532:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7533:                 $$replyref{$key} = $value;
                   7534:             }
                   7535:         } else {
1.1117    foxr     7536:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7537:             foreach my $line (@responses) {
                   7538:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7539:                 $$replyref{$key} = $value;
                   7540:                 if ($value > 0) {
1.800     albertel 7541:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7542:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7543:                         my $destname = $pathname.'/'.$filename;
                   7544:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7545:                         if ($xml_classlist =~ /^error/) {
                   7546:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7547:                         } else {
1.506     raeburn  7548:                             if ( open(FILE,">$destname") ) {
                   7549:                                 print FILE &unescape($xml_classlist);
                   7550:                                 close(FILE);
1.526     raeburn  7551:                             } else {
                   7552:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7553:                             }
                   7554:                         }
                   7555:                     }
                   7556:                 }
                   7557:             }
                   7558:         }
                   7559:         return 'ok';
                   7560:     }
                   7561:     return 'error';
                   7562: }
                   7563: 
1.242     www      7564: sub get_query_reply {
                   7565:     my $queryid=shift;
1.1117    foxr     7566:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7567:     my $reply='';
                   7568:     for (1..100) {
                   7569: 	sleep 2;
                   7570:         if (-e $replyfile.'.end') {
1.448     albertel 7571: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7572: 		$reply = join('',<$fh>);
                   7573: 		close($fh);
1.240     www      7574: 	   } else { return 'error: reply_file_error'; }
1.242     www      7575:            return &unescape($reply);
                   7576: 	}
1.240     www      7577:     }
1.242     www      7578:     return 'timeout:'.$queryid;
1.240     www      7579: }
                   7580: 
                   7581: sub courselog_query {
1.241     www      7582: #
                   7583: # possible filters:
                   7584: # url: url or symb
                   7585: # username
                   7586: # domain
                   7587: # action: view, submit, grade
                   7588: # start: timestamp
                   7589: # end: timestamp
                   7590: #
1.240     www      7591:     my (%filters)=@_;
1.620     albertel 7592:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7593:     if ($filters{'url'}) {
                   7594: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7595:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7596:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7597:     }
1.620     albertel 7598:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7599:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7600:     return &log_query($cname,$cdom,'courselog',%filters);
                   7601: }
                   7602: 
                   7603: sub userlog_query {
1.858     raeburn  7604: #
                   7605: # possible filters:
                   7606: # action: log check role
                   7607: # start: timestamp
                   7608: # end: timestamp
                   7609: #
1.240     www      7610:     my ($uname,$udom,%filters)=@_;
                   7611:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7612: }
                   7613: 
1.506     raeburn  7614: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7615: 
                   7616: sub auto_run {
1.508     raeburn  7617:     my ($cnum,$cdom) = @_;
1.876     raeburn  7618:     my $response = 0;
                   7619:     my $settings;
                   7620:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7621:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7622:         $settings = $domconfig{'autoenroll'};
                   7623:         if ($settings->{'run'} eq '1') {
                   7624:             $response = 1;
                   7625:         }
                   7626:     } else {
1.934     raeburn  7627:         my $homeserver;
                   7628:         if (&is_course($cdom,$cnum)) {
                   7629:             $homeserver = &homeserver($cnum,$cdom);
                   7630:         } else {
                   7631:             $homeserver = &domain($cdom,'primary');
                   7632:         }
                   7633:         if ($homeserver ne 'no_host') {
                   7634:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7635:         }
1.876     raeburn  7636:     }
1.506     raeburn  7637:     return $response;
                   7638: }
1.776     albertel 7639: 
1.506     raeburn  7640: sub auto_get_sections {
1.508     raeburn  7641:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7642:     my $homeserver;
                   7643:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7644:         $homeserver = &homeserver($cnum,$cdom);
                   7645:     }
                   7646:     if (!defined($homeserver)) { 
                   7647:         if ($cdom =~ /^$match_domain$/) {
                   7648:             $homeserver = &domain($cdom,'primary');
                   7649:         }
                   7650:     }
                   7651:     my @secs;
                   7652:     if (defined($homeserver)) {
                   7653:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7654:         unless ($response eq 'refused') {
                   7655:             @secs = split(/:/,$response);
                   7656:         }
1.506     raeburn  7657:     }
                   7658:     return @secs;
                   7659: }
1.776     albertel 7660: 
1.506     raeburn  7661: sub auto_new_course {
1.1099    raeburn  7662:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7663:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7664:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7665:     return $response;
                   7666: }
1.776     albertel 7667: 
1.506     raeburn  7668: sub auto_validate_courseID {
1.508     raeburn  7669:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7670:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7671:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7672:     return $response;
                   7673: }
1.776     albertel 7674: 
1.1007    raeburn  7675: sub auto_validate_instcode {
1.1020    raeburn  7676:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7677:     my ($homeserver,$response);
                   7678:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7679:         $homeserver = &homeserver($cnum,$cdom);
                   7680:     }
                   7681:     if (!defined($homeserver)) {
                   7682:         if ($cdom =~ /^$match_domain$/) {
                   7683:             $homeserver = &domain($cdom,'primary');
                   7684:         }
                   7685:     }
1.1065    raeburn  7686:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7687:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  7688:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7689:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7690: }
                   7691: 
1.506     raeburn  7692: sub auto_create_password {
1.873     raeburn  7693:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7694:     my ($homeserver,$response);
1.506     raeburn  7695:     my $create_passwd = 0;
                   7696:     my $authchk = '';
1.873     raeburn  7697:     if ($udom =~ /^$match_domain$/) {
                   7698:         $homeserver = &domain($udom,'primary');
                   7699:     }
                   7700:     if ($homeserver eq '') {
                   7701:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7702:             $homeserver = &homeserver($cnum,$cdom);
                   7703:         }
                   7704:     }
                   7705:     if ($homeserver eq '') {
                   7706:         $authchk = 'nodomain';
1.506     raeburn  7707:     } else {
1.873     raeburn  7708:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7709:         if ($response eq 'refused') {
                   7710:             $authchk = 'refused';
                   7711:         } else {
1.901     albertel 7712:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7713:         }
1.506     raeburn  7714:     }
                   7715:     return ($authparam,$create_passwd,$authchk);
                   7716: }
                   7717: 
1.706     raeburn  7718: sub auto_photo_permission {
                   7719:     my ($cnum,$cdom,$students) = @_;
                   7720:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7721:     my ($outcome,$perm_reqd,$conditions) = 
                   7722: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7723:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7724: 	return (undef,undef);
                   7725:     }
1.706     raeburn  7726:     return ($outcome,$perm_reqd,$conditions);
                   7727: }
                   7728: 
                   7729: sub auto_checkphotos {
                   7730:     my ($uname,$udom,$pid) = @_;
                   7731:     my $homeserver = &homeserver($uname,$udom);
                   7732:     my ($result,$resulttype);
                   7733:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7734: 				   &escape($uname).':'.&escape($pid),
                   7735: 				   $homeserver));
1.709     albertel 7736:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7737: 	return (undef,undef);
                   7738:     }
1.706     raeburn  7739:     if ($outcome) {
                   7740:         ($result,$resulttype) = split(/:/,$outcome);
                   7741:     } 
                   7742:     return ($result,$resulttype);
                   7743: }
                   7744: 
                   7745: sub auto_photochoice {
                   7746:     my ($cnum,$cdom) = @_;
                   7747:     my $homeserver = &homeserver($cnum,$cdom);
                   7748:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7749: 						       &escape($cdom),
                   7750: 						       $homeserver)));
1.709     albertel 7751:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7752: 	return (undef,undef);
                   7753:     }
1.706     raeburn  7754:     return ($update,$comment);
                   7755: }
                   7756: 
                   7757: sub auto_photoupdate {
                   7758:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7759:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7760:     my $host=&hostname($homeserver);
1.706     raeburn  7761:     my $cmd = '';
                   7762:     my $maxtries = 1;
1.800     albertel 7763:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7764:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7765:     }
                   7766:     $cmd =~ s/%%$//;
                   7767:     $cmd = &escape($cmd);
                   7768:     my $query = 'institutionalphotos';
                   7769:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7770:     unless ($queryid=~/^\Q$host\E\_/) {
                   7771:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7772:         return 'error: '.$queryid;
                   7773:     }
                   7774:     my $reply = &get_query_reply($queryid);
                   7775:     my $tries = 1;
                   7776:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7777:         $reply = &get_query_reply($queryid);
                   7778:         $tries ++;
                   7779:     }
                   7780:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7781:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7782:     } else {
                   7783:         my @responses = split(/:/,$reply);
                   7784:         my $outcome = shift(@responses); 
                   7785:         foreach my $item (@responses) {
                   7786:             my ($key,$value) = split(/=/,$item);
                   7787:             $$photo{$key} = $value;
                   7788:         }
                   7789:         return $outcome;
                   7790:     }
                   7791:     return 'error';
                   7792: }
                   7793: 
1.521     raeburn  7794: sub auto_instcode_format {
1.793     albertel 7795:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7796: 	$cat_order) = @_;
1.521     raeburn  7797:     my $courses = '';
1.772     raeburn  7798:     my @homeservers;
1.521     raeburn  7799:     if ($caller eq 'global') {
1.841     albertel 7800: 	my %servers = &get_servers($codedom,'library');
                   7801: 	foreach my $tryserver (keys(%servers)) {
                   7802: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7803: 		push(@homeservers,$tryserver);
                   7804: 	    }
1.584     raeburn  7805:         }
1.1022    raeburn  7806:     } elsif ($caller eq 'requests') {
                   7807:         if ($codedom =~ /^$match_domain$/) {
                   7808:             my $chome = &domain($codedom,'primary');
                   7809:             unless ($chome eq 'no_host') {
                   7810:                 push(@homeservers,$chome);
                   7811:             }
                   7812:         }
1.521     raeburn  7813:     } else {
1.772     raeburn  7814:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7815:     }
1.793     albertel 7816:     foreach my $code (keys(%{$instcodes})) {
                   7817:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7818:     }
                   7819:     chop($courses);
1.772     raeburn  7820:     my $ok_response = 0;
                   7821:     my $response;
                   7822:     while (@homeservers > 0 && $ok_response == 0) {
                   7823:         my $server = shift(@homeservers); 
                   7824:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7825:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7826:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7827: 		split(/:/,$response);
1.772     raeburn  7828:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7829:             push(@{$codetitles},&str2array($codetitles_str));
                   7830:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7831:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7832:             $ok_response = 1;
                   7833:         }
                   7834:     }
                   7835:     if ($ok_response) {
1.521     raeburn  7836:         return 'ok';
1.772     raeburn  7837:     } else {
                   7838:         return $response;
1.521     raeburn  7839:     }
                   7840: }
                   7841: 
1.792     raeburn  7842: sub auto_instcode_defaults {
                   7843:     my ($domain,$returnhash,$code_order) = @_;
                   7844:     my @homeservers;
1.841     albertel 7845: 
                   7846:     my %servers = &get_servers($domain,'library');
                   7847:     foreach my $tryserver (keys(%servers)) {
                   7848: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7849: 	    push(@homeservers,$tryserver);
                   7850: 	}
1.792     raeburn  7851:     }
1.841     albertel 7852: 
1.792     raeburn  7853:     my $response;
1.841     albertel 7854:     foreach my $server (@homeservers) {
1.792     raeburn  7855:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7856:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7857: 	
                   7858: 	foreach my $pair (split(/\&/,$response)) {
                   7859: 	    my ($name,$value)=split(/\=/,$pair);
                   7860: 	    if ($name eq 'code_order') {
                   7861: 		@{$code_order} = split(/\&/,&unescape($value));
                   7862: 	    } else {
                   7863: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7864: 	    }
                   7865: 	}
                   7866: 	return 'ok';
1.792     raeburn  7867:     }
1.841     albertel 7868: 
                   7869:     return $response;
1.1003    raeburn  7870: }
                   7871: 
                   7872: sub auto_possible_instcodes {
1.1007    raeburn  7873:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7874:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7875:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7876:         return;
                   7877:     }
1.1003    raeburn  7878:     my (@homeservers,$uhome);
                   7879:     if (defined(&domain($domain,'primary'))) {
                   7880:         $uhome=&domain($domain,'primary');
                   7881:         push(@homeservers,&domain($domain,'primary'));
                   7882:     } else {
                   7883:         my %servers = &get_servers($domain,'library');
                   7884:         foreach my $tryserver (keys(%servers)) {
                   7885:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7886:                 push(@homeservers,$tryserver);
                   7887:             }
                   7888:         }
                   7889:     }
                   7890:     my $response;
                   7891:     foreach my $server (@homeservers) {
                   7892:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7893:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7894:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7895:             split(':',$response);
                   7896:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7897:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7898:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7899:             my ($name,$value)=split('=',$item);
                   7900:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7901:         }
                   7902:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7903:             my ($name,$value)=split('=',$item);
                   7904:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7905:         }
                   7906:         return 'ok';
                   7907:     }
                   7908:     return $response;
                   7909: }
1.792     raeburn  7910: 
1.1010    raeburn  7911: sub auto_courserequest_checks {
                   7912:     my ($dom) = @_;
1.1020    raeburn  7913:     my ($homeserver,%validations);
                   7914:     if ($dom =~ /^$match_domain$/) {
                   7915:         $homeserver = &domain($dom,'primary');
                   7916:     }
                   7917:     unless ($homeserver eq 'no_host') {
                   7918:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7919:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7920:             my @items = split(/&/,$response);
                   7921:             foreach my $item (@items) {
                   7922:                 my ($key,$value) = split('=',$item);
                   7923:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7924:             }
                   7925:         }
                   7926:     }
1.1010    raeburn  7927:     return %validations; 
                   7928: }
                   7929: 
1.1020    raeburn  7930: sub auto_courserequest_validation {
1.1255    raeburn  7931:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  7932:     my ($homeserver,$response);
                   7933:     if ($dom =~ /^$match_domain$/) {
                   7934:         $homeserver = &domain($dom,'primary');
                   7935:     }
1.1255    raeburn  7936:     unless ($homeserver eq 'no_host') {
                   7937:         my $customdata;
                   7938:         if (ref($custominfo) eq 'HASH') {
                   7939:             $customdata = &freeze_escape($custominfo);
                   7940:         }
1.1020    raeburn  7941:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7942:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  7943:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   7944:                                     $customdata,$homeserver));
1.1020    raeburn  7945:     }
                   7946:     return $response;
                   7947: }
                   7948: 
1.777     albertel 7949: sub auto_validate_class_sec {
1.918     raeburn  7950:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7951:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7952:     my $ownerlist;
                   7953:     if (ref($owners) eq 'ARRAY') {
                   7954:         $ownerlist = join(',',@{$owners});
                   7955:     } else {
                   7956:         $ownerlist = $owners;
                   7957:     }
1.773     raeburn  7958:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7959:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7960:     return $response;
                   7961: }
                   7962: 
1.1248    raeburn  7963: sub auto_crsreq_update {
                   7964:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  7965:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  7966:     my ($homeserver,%crsreqresponse);
                   7967:     if ($cdom =~ /^$match_domain$/) {
                   7968:         $homeserver = &domain($cdom,'primary');
                   7969:     }
                   7970:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   7971:         my $info;
                   7972:         if (ref($inbound) eq 'HASH') {
                   7973:             $info = &freeze_escape($inbound);
                   7974:         }
                   7975:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   7976:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   7977:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  7978:                             &escape($title).':'.&escape($code).':'.
                   7979:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   7980:                             $homeserver);
1.1248    raeburn  7981:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7982:             my @items = split(/&/,$response);
                   7983:             foreach my $item (@items) {
                   7984:                 my ($key,$value) = split('=',$item);
                   7985:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   7986:             }
                   7987:         }
                   7988:     }
                   7989:     return \%crsreqresponse;
                   7990: }
                   7991: 
1.679     raeburn  7992: # ------------------------------------------------------- Course Group routines
                   7993: 
                   7994: sub get_coursegroups {
1.809     raeburn  7995:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7996:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7997: }
                   7998: 
1.679     raeburn  7999: sub modify_coursegroup {
                   8000:     my ($cdom,$cnum,$groupsettings) = @_;
                   8001:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8002: }
                   8003: 
1.809     raeburn  8004: sub toggle_coursegroup_status {
                   8005:     my ($cdom,$cnum,$group,$action) = @_;
                   8006:     my ($from_namespace,$to_namespace);
                   8007:     if ($action eq 'delete') {
                   8008:         $from_namespace = 'coursegroups';
                   8009:         $to_namespace = 'deleted_groups';
                   8010:     } else {
                   8011:         $from_namespace = 'deleted_groups';
                   8012:         $to_namespace = 'coursegroups';
                   8013:     }
                   8014:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8015:     if (my $tmp = &error(%curr_group)) {
                   8016:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8017:         return ('read error',$tmp);
                   8018:     } else {
                   8019:         my %savedsettings = %curr_group; 
1.809     raeburn  8020:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8021:         my $deloutcome;
                   8022:         if ($result eq 'ok') {
1.809     raeburn  8023:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8024:         } else {
                   8025:             return ('write error',$result);
                   8026:         }
                   8027:         if ($deloutcome eq 'ok') {
                   8028:             return 'ok';
                   8029:         } else {
                   8030:             return ('delete error',$deloutcome);
                   8031:         }
                   8032:     }
                   8033: }
                   8034: 
1.679     raeburn  8035: sub modify_group_roles {
1.957     raeburn  8036:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8037:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8038:     my $role = 'gr/'.&escape($userprivs);
                   8039:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8040:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8041:     if ($result eq 'ok') {
                   8042:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8043:     }
1.679     raeburn  8044:     return $result;
                   8045: }
                   8046: 
                   8047: sub modify_coursegroup_membership {
                   8048:     my ($cdom,$cnum,$membership) = @_;
                   8049:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8050:     return $result;
                   8051: }
                   8052: 
1.682     raeburn  8053: sub get_active_groups {
                   8054:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8055:     my $now = time;
                   8056:     my %groups = ();
                   8057:     foreach my $key (keys(%env)) {
1.811     albertel 8058:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8059:             my ($start,$end) = split(/\./,$env{$key});
                   8060:             if (($end!=0) && ($end<$now)) { next; }
                   8061:             if (($start!=0) && ($start>$now)) { next; }
                   8062:             if ($1 eq $cdom && $2 eq $cnum) {
                   8063:                 $groups{$3} = $env{$key} ;
                   8064:             }
                   8065:         }
                   8066:     }
                   8067:     return %groups;
                   8068: }
                   8069: 
1.683     raeburn  8070: sub get_group_membership {
                   8071:     my ($cdom,$cnum,$group) = @_;
                   8072:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8073: }
                   8074: 
                   8075: sub get_users_groups {
                   8076:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8077:     my @usersgroups;
1.683     raeburn  8078:     my $cachetime=1800;
                   8079: 
                   8080:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8081:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8082:     if (defined($cached)) {
1.734     albertel 8083:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8084:     } else {  
                   8085:         $grouplist = '';
1.816     raeburn  8086:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8087:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8088:         my $access_end = $env{'course.'.$courseid.
                   8089:                               '.default_enrollment_end_date'};
                   8090:         my $now = time;
                   8091:         foreach my $key (keys(%roleshash)) {
                   8092:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8093:                 my $group = $1;
                   8094:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8095:                     my $start = $2;
                   8096:                     my $end = $1;
                   8097:                     if ($start == -1) { next; } # deleted from group
                   8098:                     if (($start!=0) && ($start>$now)) { next; }
                   8099:                     if (($end!=0) && ($end<$now)) {
                   8100:                         if ($access_end && $access_end < $now) {
                   8101:                             if ($access_end - $end < 86400) {
                   8102:                                 push(@usersgroups,$group);
1.733     raeburn  8103:                             }
                   8104:                         }
1.817     raeburn  8105:                         next;
1.733     raeburn  8106:                     }
1.817     raeburn  8107:                     push(@usersgroups,$group);
1.683     raeburn  8108:                 }
                   8109:             }
                   8110:         }
1.817     raeburn  8111:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8112:         $grouplist = join(':',@usersgroups);
                   8113:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8114:     }
1.733     raeburn  8115:     return @usersgroups;
1.683     raeburn  8116: }
                   8117: 
                   8118: sub devalidate_getgroups_cache {
                   8119:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8120:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8121: 
1.683     raeburn  8122:     my $hashid="$udom:$uname:$courseid";
                   8123:     &devalidate_cache_new('getgroups',$hashid);
                   8124: }
                   8125: 
1.12      www      8126: # ------------------------------------------------------------------ Plain Text
                   8127: 
                   8128: sub plaintext {
1.988     raeburn  8129:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8130:     if ($short =~ m{^cr/}) {
1.758     albertel 8131: 	return (split('/',$short))[-1];
                   8132:     }
1.742     raeburn  8133:     if (!defined($cid)) {
                   8134:         $cid = $env{'request.course.id'};
                   8135:     }
                   8136:     my %rolenames = (
1.1008    raeburn  8137:                       Course    => 'std',
                   8138:                       Community => 'alt1',
1.742     raeburn  8139:                     );
1.1037    raeburn  8140:     if ($cid ne '') {
                   8141:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8142:             unless ($forcedefault) {
                   8143:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8144:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8145:                 return &Apache::lonlocal::mt($roletext);
                   8146:             }
                   8147:         }
                   8148:     }
                   8149:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8150:         (defined($rolenames{$type})) && 
                   8151:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8152:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8153:     } elsif ($cid ne '') {
                   8154:         my $crstype = $env{'course.'.$cid.'.type'};
                   8155:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8156:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8157:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8158:         }
1.742     raeburn  8159:     }
1.1037    raeburn  8160:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8161: }
                   8162: 
                   8163: # ----------------------------------------------------------------- Assign Role
                   8164: 
                   8165: sub assignrole {
1.957     raeburn  8166:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8167:         $context)=@_;
1.21      www      8168:     my $mrole;
                   8169:     if ($role =~ /^cr\//) {
1.393     www      8170:         my $cwosec=$url;
1.811     albertel 8171:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8172: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8173:            my $refused = 1;
                   8174:            if ($context eq 'requestcourses') {
                   8175:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8176:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8177:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8178:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8179:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8180:                            if ($crsenv{'internal.courseowner'} eq
                   8181:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8182:                                $refused = '';
                   8183:                            }
                   8184:                        }
                   8185:                    }
                   8186:                }
                   8187:            }
                   8188:            if ($refused) {
                   8189:                &logthis('Refused custom assignrole: '.
                   8190:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8191:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8192:                return 'refused';
                   8193:            }
1.104     www      8194:         }
1.21      www      8195:         $mrole='cr';
1.678     raeburn  8196:     } elsif ($role =~ /^gr\//) {
                   8197:         my $cwogrp=$url;
1.811     albertel 8198:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8199:         unless (&allowed('mdg',$cwogrp)) {
                   8200:             &logthis('Refused group assignrole: '.
                   8201:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8202:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8203:             return 'refused';
                   8204:         }
                   8205:         $mrole='gr';
1.21      www      8206:     } else {
1.82      www      8207:         my $cwosec=$url;
1.811     albertel 8208:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8209:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8210:             my $refused;
                   8211:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8212:                 if (!(&allowed('c'.$role,$url))) {
                   8213:                     $refused = 1;
                   8214:                 }
                   8215:             } else {
                   8216:                 $refused = 1;
                   8217:             }
1.947     raeburn  8218:             if ($refused) {
1.1045    raeburn  8219:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8220:                 if (!$selfenroll && $context eq 'course') {
                   8221:                     my %crsenv;
                   8222:                     if ($role eq 'cc' || $role eq 'co') {
                   8223:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8224:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8225:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8226:                                 if ($crsenv{'internal.courseowner'} eq 
                   8227:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8228:                                     $refused = '';
                   8229:                                 }
                   8230:                             }
                   8231:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8232:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8233:                                 if ($crsenv{'internal.courseowner'} eq 
                   8234:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8235:                                     $refused = '';
                   8236:                                 }
                   8237:                             }
                   8238:                         }
                   8239:                     }
                   8240:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8241:                     $refused = '';
1.1017    raeburn  8242:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8243:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8244:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8245:                         my $wrongcc;
                   8246:                         if ($cnum =~ /^$match_community$/) {
                   8247:                             $wrongcc = 1 if ($role eq 'cc');
                   8248:                         } else {
                   8249:                             $wrongcc = 1 if ($role eq 'co');
                   8250:                         }
                   8251:                         unless ($wrongcc) {
                   8252:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8253:                             if ($crsenv{'internal.courseowner'} eq 
                   8254:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8255:                                 $refused = '';
                   8256:                             }
1.1017    raeburn  8257:                         }
                   8258:                     }
1.1183    raeburn  8259:                 } elsif ($context eq 'requestauthor') {
                   8260:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8261:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8262:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8263:                             $refused = '';
                   8264:                         } else {
                   8265:                             my %domdefaults = &get_domain_defaults($udom);
                   8266:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8267:                                 my $checkbystatus;
                   8268:                                 if ($env{'user.adv'}) { 
                   8269:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8270:                                     if ($disposition eq 'automatic') {
                   8271:                                         $refused = '';
                   8272:                                     } elsif ($disposition eq '') {
                   8273:                                         $checkbystatus = 1;
                   8274:                                     } 
                   8275:                                 } else {
                   8276:                                     $checkbystatus = 1;
                   8277:                                 }
                   8278:                                 if ($checkbystatus) {
                   8279:                                     if ($env{'environment.inststatus'}) {
                   8280:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8281:                                         foreach my $type (@inststatuses) {
                   8282:                                             if (($type ne '') &&
                   8283:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8284:                                                 $refused = '';
                   8285:                                             }
                   8286:                                         }
                   8287:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8288:                                         $refused = '';
                   8289:                                     }
                   8290:                                 }
                   8291:                             }
                   8292:                         }
                   8293:                     }
1.1017    raeburn  8294:                 }
                   8295:                 if ($refused) {
1.947     raeburn  8296:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8297:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8298: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8299:                     return 'refused';
                   8300:                 }
1.932     raeburn  8301:             }
1.1131    raeburn  8302:         } elsif ($role eq 'au') {
                   8303:             if ($url ne '/'.$udom.'/') {
                   8304:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8305:                          ' to assign author role for '.$uname.':'.$udom.
                   8306:                          ' in domain: '.$url.' refused (wrong domain).');
                   8307:                 return 'refused';
                   8308:             }
1.104     www      8309:         }
1.21      www      8310:         $mrole=$role;
                   8311:     }
1.620     albertel 8312:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8313:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8314:     if ($end) { $command.='_'.$end; }
1.21      www      8315:     if ($start) {
                   8316: 	if ($end) { 
1.81      www      8317:            $command.='_'.$start; 
1.21      www      8318:         } else {
1.81      www      8319:            $command.='_0_'.$start;
1.21      www      8320:         }
                   8321:     }
1.739     raeburn  8322:     my $origstart = $start;
                   8323:     my $origend = $end;
1.957     raeburn  8324:     my $delflag;
1.357     www      8325: # actually delete
                   8326:     if ($deleteflag) {
1.373     www      8327: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8328: # modify command to delete the role
1.620     albertel 8329:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8330:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8331: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8332: # set start and finish to negative values for userrolelog
                   8333:            $start=-1;
                   8334:            $end=-1;
1.957     raeburn  8335:            $delflag = 1;
1.357     www      8336:         }
                   8337:     }
                   8338: # send command
1.349     www      8339:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8340: # log new user role if status is ok
1.349     www      8341:     if ($answer eq 'ok') {
1.663     raeburn  8342: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8343:         if (($role eq 'cc') || ($role eq 'in') ||
                   8344:             ($role eq 'ep') || ($role eq 'ad') ||
                   8345:             ($role eq 'ta') || ($role eq 'st') ||
                   8346:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8347:             ($role eq 'co')) {
1.1200    raeburn  8348: # for course roles, perform group memberships changes triggered by role change.
                   8349:             unless ($role =~ /^gr/) {
                   8350:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8351:                                                  $origstart,$selfenroll,$context);
                   8352:             }
1.1184    raeburn  8353:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8354:                            $selfenroll,$context);
                   8355:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8356:                  ($role eq 'au') || ($role eq 'dc')) {
                   8357:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8358:                            $context);
                   8359:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8360:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8361:                              $context); 
                   8362:         }
1.1053    raeburn  8363:         if ($role eq 'cc') {
                   8364:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8365:         }
1.349     www      8366:     }
                   8367:     return $answer;
1.169     harris41 8368: }
                   8369: 
1.1053    raeburn  8370: sub autoupdate_coowners {
                   8371:     my ($url,$end,$start,$uname,$udom) = @_;
                   8372:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8373:     if (($cdom ne '') && ($cnum ne '')) {
                   8374:         my $now = time;
                   8375:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8376:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8377:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8378:             my $instcode = $coursehash{'internal.coursecode'};
                   8379:             if ($instcode ne '') {
1.1056    raeburn  8380:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8381:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8382:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8383:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8384:                         if ($result eq 'valid') {
                   8385:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8386:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8387:                                     push(@newcoowners,$coowner);
                   8388:                                 }
                   8389:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8390:                                     push(@newcoowners,$uname.':'.$udom);
                   8391:                                 }
                   8392:                                 @newcoowners = sort(@newcoowners);
                   8393:                             } else {
                   8394:                                 push(@newcoowners,$uname.':'.$udom);
                   8395:                             }
                   8396:                         } else {
                   8397:                             if ($coursehash{'internal.co-owners'}) {
                   8398:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8399:                                     unless ($coowner eq $uname.':'.$udom) {
                   8400:                                         push(@newcoowners,$coowner);
                   8401:                                     }
                   8402:                                 }
                   8403:                                 unless (@newcoowners > 0) {
                   8404:                                     $delcoowners = 1;
                   8405:                                     $coowners = '';
                   8406:                                 }
                   8407:                             }
                   8408:                         }
                   8409:                         if (@newcoowners || $delcoowners) {
                   8410:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8411:                                             $delcoowners,@newcoowners);
                   8412:                         }
                   8413:                     }
                   8414:                 }
                   8415:             }
                   8416:         }
                   8417:     }
                   8418: }
                   8419: 
                   8420: sub store_coowners {
                   8421:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8422:     my $cid = $cdom.'_'.$cnum;
                   8423:     my ($coowners,$delresult,$putresult);
                   8424:     if (@newcoowners) {
                   8425:         $coowners = join(',',@newcoowners);
                   8426:         my %coownershash = (
                   8427:                             'internal.co-owners' => $coowners,
                   8428:                            );
                   8429:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8430:         if ($putresult eq 'ok') {
                   8431:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8432:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8433:             }
                   8434:         }
                   8435:     }
                   8436:     if ($delcoowners) {
                   8437:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8438:         if ($delresult eq 'ok') {
                   8439:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8440:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8441:             }
                   8442:         }
                   8443:     }
                   8444:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8445:         my %crsinfo =
                   8446:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8447:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8448:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8449:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8450:         }
                   8451:     }
                   8452: }
                   8453: 
1.169     harris41 8454: # -------------------------------------------------- Modify user authentication
1.197     www      8455: # Overrides without validation
                   8456: 
1.169     harris41 8457: sub modifyuserauth {
                   8458:     my ($udom,$uname,$umode,$upass)=@_;
                   8459:     my $uhome=&homeserver($uname,$udom);
1.197     www      8460:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8461:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8462:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8463:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8464:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8465: 		     &escape($upass),$uhome);
1.620     albertel 8466:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8467:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8468:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8469:     &log($udom,,$uname,$uhome,
1.620     albertel 8470:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8471:                                      $env{'user.name'}.', '.$umode.
1.197     www      8472:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8473:     unless ($reply eq 'ok') {
1.197     www      8474:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8475: 	return 'error: '.$reply;
                   8476:     }   
1.170     harris41 8477:     return 'ok';
1.80      www      8478: }
                   8479: 
1.81      www      8480: # --------------------------------------------------------------- Modify a user
1.80      www      8481: 
1.81      www      8482: sub modifyuser {
1.206     matthew  8483:     my ($udom,    $uname, $uid,
                   8484:         $umode,   $upass, $first,
                   8485:         $middle,  $last,  $gene,
1.1058    raeburn  8486:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8487:     $udom= &LONCAPA::clean_domain($udom);
                   8488:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8489:     my $showcandelete = 'none';
                   8490:     if (ref($candelete) eq 'ARRAY') {
                   8491:         if (@{$candelete} > 0) {
                   8492:             $showcandelete = join(', ',@{$candelete});
                   8493:         }
                   8494:     }
1.81      www      8495:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8496:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8497: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8498:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8499:                                      ' desiredhome not specified'). 
1.620     albertel 8500:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8501:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8502:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8503:     my $newuser;
                   8504:     if ($uhome eq 'no_host') {
                   8505:         $newuser = 1;
                   8506:     }
1.80      www      8507: # ----------------------------------------------------------------- Create User
1.406     albertel 8508:     if (($uhome eq 'no_host') && 
                   8509: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8510:         my $unhome='';
1.844     albertel 8511:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8512:             $unhome = $desiredhome;
1.620     albertel 8513: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8514: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8515:         } else { # load balancing routine for determining $unhome
1.81      www      8516:             my $loadm=10000000;
1.841     albertel 8517: 	    my %servers = &get_servers($udom,'library');
                   8518: 	    foreach my $tryserver (keys(%servers)) {
                   8519: 		my $answer=reply('load',$tryserver);
                   8520: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8521: 		    $loadm=$answer;
                   8522: 		    $unhome=$tryserver;
                   8523: 		}
1.80      www      8524: 	    }
                   8525:         }
                   8526:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8527: 	    return 'error: unable to find a home server for '.$uname.
                   8528:                    ' in domain '.$udom;
1.80      www      8529:         }
                   8530:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8531:                          &escape($upass),$unhome);
                   8532: 	unless ($reply eq 'ok') {
                   8533:             return 'error: '.$reply;
                   8534:         }   
1.230     stredwic 8535:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8536:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8537: 	    return 'error: unable verify users home machine.';
1.80      www      8538:         }
1.209     matthew  8539:     }   # End of creation of new user
1.80      www      8540: # ---------------------------------------------------------------------- Add ID
                   8541:     if ($uid) {
                   8542:        $uid=~tr/A-Z/a-z/;
                   8543:        my %uidhash=&idrget($udom,$uname);
1.196     www      8544:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8545:          && (!$forceid)) {
1.80      www      8546: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8547: 	      return 'error: user id "'.$uid.'" does not match '.
                   8548:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8549:           }
                   8550:        } else {
                   8551: 	  &idput($udom,($uname => $uid));
                   8552:        }
                   8553:     }
                   8554: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8555:     my @tmp=&get('environment',
1.899     raeburn  8556: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8557:                     'permanentemail','inststatus'],
1.134     albertel 8558: 		   $udom,$uname);
1.1075    raeburn  8559:     my (%names,%oldnames);
1.313     matthew  8560:     if ($tmp[0] =~ m/^error:.*/) { 
                   8561:         %names=(); 
                   8562:     } else {
                   8563:         %names = @tmp;
1.1075    raeburn  8564:         %oldnames = %names;
1.313     matthew  8565:     }
1.388     www      8566: #
1.1058    raeburn  8567: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8568: # of users did not contain them), do not overwrite existing values
                   8569: # unless field is in $candelete array ref.  
                   8570: #
                   8571: 
                   8572:     my @fields = ('firstname','middlename','lastname','generation',
                   8573:                   'permanentemail','id');
                   8574:     my %newvalues;
                   8575:     if (ref($candelete) eq 'ARRAY') {
                   8576:         foreach my $field (@fields) {
                   8577:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8578:                 if ($field eq 'firstname') {
                   8579:                     $names{$field} = $first;
                   8580:                 } elsif ($field eq 'middlename') {
                   8581:                     $names{$field} = $middle;
                   8582:                 } elsif ($field eq 'lastname') {
                   8583:                     $names{$field} = $last;
                   8584:                 } elsif ($field eq 'generation') { 
                   8585:                     $names{$field} = $gene;
                   8586:                 } elsif ($field eq 'permanentemail') {
                   8587:                     $names{$field} = $email;
                   8588:                 } elsif ($field eq 'id') {
                   8589:                     $names{$field}  = $uid;
                   8590:                 }
                   8591:             }
                   8592:         }
                   8593:     }
1.388     www      8594:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8595:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8596:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8597:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8598:     if ($email) {
                   8599:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8600:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8601:     }
1.899     raeburn  8602:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8603:     if (defined($inststatus)) {
                   8604:         $names{'inststatus'} = '';
                   8605:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8606:         if (ref($usertypes) eq 'HASH') {
                   8607:             my @okstatuses; 
                   8608:             foreach my $item (split(/:/,$inststatus)) {
                   8609:                 if (defined($usertypes->{$item})) {
                   8610:                     push(@okstatuses,$item);  
                   8611:                 }
                   8612:             }
                   8613:             if (@okstatuses) {
                   8614:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8615:             }
                   8616:         }
                   8617:     }
1.1075    raeburn  8618:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8619:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8620:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8621:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8622:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8623:     } else {
                   8624:         $logmsg .= ' during self creation';
                   8625:     }
1.1075    raeburn  8626:     my $changed;
                   8627:     if ($newuser) {
                   8628:         $changed = 1;
                   8629:     } else {
                   8630:         foreach my $field (@fields) {
                   8631:             if ($names{$field} ne $oldnames{$field}) {
                   8632:                 $changed = 1;
                   8633:                 last;
                   8634:             }
                   8635:         }
                   8636:     }
                   8637:     unless ($changed) {
                   8638:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8639:         &logthis($logmsg);
                   8640:         return 'ok';
                   8641:     }
                   8642:     my $reply = &put('environment', \%names, $udom,$uname);
                   8643:     if ($reply ne 'ok') { 
                   8644:         return 'error: '.$reply;
                   8645:     }
1.1087    raeburn  8646:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8647:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8648:     }
1.1075    raeburn  8649:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8650:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8651:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8652:     &logthis($logmsg);
1.134     albertel 8653:     return 'ok';
1.80      www      8654: }
                   8655: 
1.81      www      8656: # -------------------------------------------------------------- Modify student
1.80      www      8657: 
1.81      www      8658: sub modifystudent {
                   8659:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8660:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216    raeburn  8661:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8662:     if (!$cid) {
1.620     albertel 8663: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8664: 	    return 'not_in_class';
                   8665: 	}
1.80      www      8666:     }
                   8667: # --------------------------------------------------------------- Make the user
1.81      www      8668:     my $reply=&modifyuser
1.209     matthew  8669: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8670:          $desiredhome,$email,$inststatus);
1.80      www      8671:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8672:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  8673:     # student's environment
1.297     matthew  8674:     $uid = undef if (!$forceid);
1.455     albertel 8675:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  8676:                                         $gene,$usec,$end,$start,$type,$locktype,
                   8677:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8678:     return $reply;
                   8679: }
                   8680: 
                   8681: sub modify_student_enrollment {
1.1216    raeburn  8682:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8683:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8684:     my ($cdom,$cnum,$chome);
                   8685:     if (!$cid) {
1.620     albertel 8686: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8687: 	    return 'not_in_class';
                   8688: 	}
1.620     albertel 8689: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8690: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8691:     } else {
                   8692: 	($cdom,$cnum)=split(/_/,$cid);
                   8693:     }
1.620     albertel 8694:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8695:     if (!$chome) {
1.457     raeburn  8696: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8697:     }
1.455     albertel 8698:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8699:     # Make sure the user exists
1.81      www      8700:     my $uhome=&homeserver($uname,$udom);
                   8701:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8702: 	return 'error: no such user';
                   8703:     }
1.297     matthew  8704:     # Get student data if we were not given enough information
                   8705:     if (!defined($first)  || $first  eq '' || 
                   8706:         !defined($last)   || $last   eq '' || 
                   8707:         !defined($uid)    || $uid    eq '' || 
                   8708:         !defined($middle) || $middle eq '' || 
                   8709:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8710:         # They did not supply us with enough data to enroll the student, so
                   8711:         # we need to pick up more information.
1.297     matthew  8712:         my %tmp = &get('environment',
1.294     matthew  8713:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8714:                        ,$udom,$uname);
                   8715: 
1.800     albertel 8716:         #foreach my $key (keys(%tmp)) {
                   8717:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8718:         #}
1.294     matthew  8719:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8720:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8721:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8722:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8723:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8724:     }
1.556     albertel 8725:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8726:     my $user = "$uname:$udom";
                   8727:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8728:     my $reply=cput('classlist',
1.1148    raeburn  8729: 		   {$user => 
1.1216    raeburn  8730: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8731: 		   $cdom,$cnum);
1.1148    raeburn  8732:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8733:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8734:     } else { 
1.81      www      8735: 	return 'error: '.$reply;
                   8736:     }
1.297     matthew  8737:     # Add student role to user
1.83      www      8738:     my $uurl='/'.$cid;
1.81      www      8739:     $uurl=~s/\_/\//g;
                   8740:     if ($usec) {
                   8741: 	$uurl.='/'.$usec;
                   8742:     }
1.1148    raeburn  8743:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8744:                              $selfenroll,$context);
                   8745:     if ($result ne 'ok') {
                   8746:         if ($old_entry{$user} ne '') {
                   8747:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8748:         } else {
                   8749:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8750:         }
                   8751:     }
                   8752:     return $result; 
1.21      www      8753: }
                   8754: 
1.556     albertel 8755: sub format_name {
                   8756:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8757:     my $name;
                   8758:     if ($first ne 'lastname') {
                   8759: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8760:     } else {
                   8761: 	if ($lastname=~/\S/) {
                   8762: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8763: 	    $name=~s/\s+,/,/;
                   8764: 	} else {
                   8765: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8766: 	}
                   8767:     }
                   8768:     $name=~s/^\s+//;
                   8769:     $name=~s/\s+$//;
                   8770:     $name=~s/\s+/ /g;
                   8771:     return $name;
                   8772: }
                   8773: 
1.84      www      8774: # ------------------------------------------------- Write to course preferences
                   8775: 
                   8776: sub writecoursepref {
                   8777:     my ($courseid,%prefs)=@_;
                   8778:     $courseid=~s/^\///;
                   8779:     $courseid=~s/\_/\//g;
                   8780:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8781:     my $chome=homeserver($cnum,$cdomain);
                   8782:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8783: 	return 'error: no such course';
                   8784:     }
                   8785:     my $cstring='';
1.800     albertel 8786:     foreach my $pref (keys(%prefs)) {
                   8787: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8788:     }
1.84      www      8789:     $cstring=~s/\&$//;
                   8790:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8791: }
                   8792: 
                   8793: # ---------------------------------------------------------- Make/modify course
                   8794: 
                   8795: sub createcourse {
1.741     raeburn  8796:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8797:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8798:     $url=&declutter($url);
                   8799:     my $cid='';
1.1028    raeburn  8800:     if ($context eq 'requestcourses') {
                   8801:         my $can_create = 0;
                   8802:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8803:         if ($udom eq $ownerdom) {
                   8804:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8805:                                   $context)) {
                   8806:                 $can_create = 1;
                   8807:             }
                   8808:         } else {
                   8809:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8810:                                            $category);
                   8811:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8812:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8813:                 if (@curr > 0) {
                   8814:                     my @options = qw(approval validate autolimit);
                   8815:                     my $optregex = join('|',@options);
                   8816:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8817:                         $can_create = 1;
                   8818:                     }
                   8819:                 }
                   8820:             }
                   8821:         }
                   8822:         if ($can_create) {
                   8823:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8824:                 unless (&allowed('ccc',$udom)) {
                   8825:                     return 'refused'; 
                   8826:                 }
1.1017    raeburn  8827:             }
                   8828:         } else {
                   8829:             return 'refused';
                   8830:         }
1.1028    raeburn  8831:     } elsif (!&allowed('ccc',$udom)) {
                   8832:         return 'refused';
1.84      www      8833:     }
1.1011    raeburn  8834: # --------------------------------------------------------------- Get Unique ID
                   8835:     my $uname;
                   8836:     if ($cnum =~ /^$match_courseid$/) {
                   8837:         my $chome=&homeserver($cnum,$udom,'true');
                   8838:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8839:             $uname = $cnum;
                   8840:         } else {
1.1038    raeburn  8841:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8842:         }
                   8843:     } else {
1.1038    raeburn  8844:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8845:     }
                   8846:     return $uname if ($uname =~ /^error/);
                   8847: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8848:     if (!defined($course_server)) {
                   8849:         if (defined(&domain($udom,'primary'))) {
                   8850:             $course_server = &domain($udom,'primary');
                   8851:         } else {
                   8852:             $course_server = $env{'user.home'}; 
                   8853:         }
                   8854:     }
                   8855:     my %host_servers =
                   8856:         &Apache::lonnet::get_servers($udom,'library');
                   8857:     unless ($host_servers{$course_server}) {
                   8858:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8859:     }
1.84      www      8860: # ------------------------------------------------------------- Make the course
                   8861:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8862:                       $course_server);
1.84      www      8863:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8864:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8865:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8866: 	return 'error: no such course';
                   8867:     }
1.271     www      8868: # ----------------------------------------------------------------- Course made
1.516     raeburn  8869: # log existence
1.1029    raeburn  8870:     my $now = time;
1.918     raeburn  8871:     my $newcourse = {
                   8872:                     $udom.'_'.$uname => {
1.921     raeburn  8873:                                      description => $description,
                   8874:                                      inst_code   => $inst_code,
                   8875:                                      owner       => $course_owner,
                   8876:                                      type        => $crstype,
1.1029    raeburn  8877:                                      creator     => $env{'user.name'}.':'.
                   8878:                                                     $env{'user.domain'},
                   8879:                                      created     => $now,
                   8880:                                      context     => $context,
1.918     raeburn  8881:                                                 },
                   8882:                     };
1.921     raeburn  8883:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8884: # set toplevel url
1.271     www      8885:     my $topurl=$url;
                   8886:     unless ($nonstandard) {
                   8887: # ------------------------------------------ For standard courses, make top url
                   8888:         my $mapurl=&clutter($url);
1.278     www      8889:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8890:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8891: <map>
                   8892: <resource id="1" type="start"></resource>
                   8893: <resource id="2" src="$mapurl"></resource>
                   8894: <resource id="3" type="finish"></resource>
                   8895: <link index="1" from="1" to="2"></link>
                   8896: <link index="2" from="2" to="3"></link>
                   8897: </map>
                   8898: ENDINITMAP
                   8899:         $topurl=&declutter(
1.638     albertel 8900:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8901:                           );
                   8902:     }
                   8903: # ----------------------------------------------------------- Write preferences
1.84      www      8904:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8905:                      ('description'              => $description,
                   8906:                       'url'                      => $topurl,
                   8907:                       'internal.creator'         => $env{'user.name'}.':'.
                   8908:                                                     $env{'user.domain'},
                   8909:                       'internal.created'         => $now,
                   8910:                       'internal.creationcontext' => $context)
                   8911:                     );
1.84      www      8912:     return '/'.$udom.'/'.$uname;
                   8913: }
                   8914: 
1.1011    raeburn  8915: # ------------------------------------------------------------------- Create ID
                   8916: sub generate_coursenum {
1.1038    raeburn  8917:     my ($udom,$crstype) = @_;
1.1011    raeburn  8918:     my $domdesc = &domain($udom);
                   8919:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8920:     my $first;
                   8921:     if ($crstype eq 'Community') {
                   8922:         $first = '0';
                   8923:     } else {
                   8924:         $first = int(1+rand(9)); 
                   8925:     } 
                   8926:     my $uname=$first.
1.1011    raeburn  8927:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8928:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8929:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8930: # ----------------------------------------------- Make sure that does not exist
                   8931:     my $uhome=&homeserver($uname,$udom,'true');
                   8932:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8933:         if ($crstype eq 'Community') {
                   8934:             $first = '0';
                   8935:         } else {
                   8936:             $first = int(1+rand(9));
                   8937:         }
                   8938:         $uname=$first.
1.1011    raeburn  8939:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8940:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8941:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8942:         $uhome=&homeserver($uname,$udom,'true');
                   8943:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8944:             return 'error: unable to generate unique course-ID';
                   8945:         }
                   8946:     }
                   8947:     return $uname;
                   8948: }
                   8949: 
1.813     albertel 8950: sub is_course {
1.1167    droeschl 8951:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8952:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8953: 
                   8954:     return unless $cdom and $cnum;
                   8955: 
                   8956:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8957:         '.');
                   8958: 
1.1219    raeburn  8959:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 8960:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8961: }
                   8962: 
1.1015    raeburn  8963: sub store_userdata {
                   8964:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8965:     my $result;
1.1016    raeburn  8966:     if ($datakey ne '') {
1.1013    raeburn  8967:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8968:             if ($udom eq '' || $uname eq '') {
                   8969:                 $udom = $env{'user.domain'};
                   8970:                 $uname = $env{'user.name'};
                   8971:             }
                   8972:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8973:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8974:                 $result = 'error: no_host';
                   8975:             } else {
                   8976:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8977:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8978: 
                   8979:                 my $namevalue='';
                   8980:                 foreach my $key (keys(%{$storehash})) {
                   8981:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8982:                 }
                   8983:                 $namevalue=~s/\&$//;
1.1224    raeburn  8984:                 unless ($namespace eq 'courserequests') {
                   8985:                     $datakey = &escape($datakey);
                   8986:                 }
1.1105    raeburn  8987:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8988:                                   $namevalue,$uhome);
1.1013    raeburn  8989:             }
                   8990:         } else {
                   8991:             $result = 'error: data to store was not a hash reference'; 
                   8992:         }
                   8993:     } else {
                   8994:         $result= 'error: invalid requestkey'; 
                   8995:     }
                   8996:     return $result;
                   8997: }
                   8998: 
1.21      www      8999: # ---------------------------------------------------------- Assign Custom Role
                   9000: 
                   9001: sub assigncustomrole {
1.957     raeburn  9002:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9003:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9004:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9005: }
                   9006: 
                   9007: # ----------------------------------------------------------------- Revoke Role
                   9008: 
                   9009: sub revokerole {
1.957     raeburn  9010:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9011:     my $now=time;
1.965     raeburn  9012:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9013: }
                   9014: 
                   9015: # ---------------------------------------------------------- Revoke Custom Role
                   9016: 
                   9017: sub revokecustomrole {
1.957     raeburn  9018:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9019:     my $now=time;
1.357     www      9020:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9021:            $deleteflag,$selfenroll,$context);
1.17      www      9022: }
                   9023: 
1.533     banghart 9024: # ------------------------------------------------------------ Disk usage
1.535     albertel 9025: sub diskusage {
1.955     raeburn  9026:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9027:     $directorypath =~ s/\/$//;
                   9028:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9029:                        .&escape($getpropath).':'.&escape($uname).':'
                   9030:                        .&escape($udom),homeserver($uname,$udom));
                   9031:     if ($listing eq 'unknown_cmd') {
                   9032:         if ($getpropath) {
                   9033:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9034:         }
                   9035:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9036:     }
1.514     albertel 9037:     return $listing;
1.512     banghart 9038: }
                   9039: 
1.566     banghart 9040: sub is_locked {
1.1096    raeburn  9041:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9042:     my @check;
                   9043:     my $is_locked;
1.1093    raeburn  9044:     push (@check,$file_name);
1.613     albertel 9045:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9046: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9047:     my ($tmp)=keys(%locked);
                   9048:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9049:     
1.566     banghart 9050:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9051:         $is_locked = 'false';
                   9052:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9053:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9054:                $is_locked = 'true';
1.1096    raeburn  9055:                if (ref($which) eq 'ARRAY') {
                   9056:                    push(@{$which},$entry);
                   9057:                } else {
                   9058:                    last;
                   9059:                }
1.745     raeburn  9060:            }
                   9061:        }
1.566     banghart 9062:     } else {
                   9063:         $is_locked = 'false';
                   9064:     }
1.1093    raeburn  9065:     return $is_locked;
1.566     banghart 9066: }
                   9067: 
1.759     albertel 9068: sub declutter_portfile {
                   9069:     my ($file) = @_;
1.833     albertel 9070:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9071:     return $file;
                   9072: }
                   9073: 
1.559     banghart 9074: # ------------------------------------------------------------- Mark as Read Only
                   9075: 
                   9076: sub mark_as_readonly {
                   9077:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9078:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9079:     my ($tmp)=keys(%current_permissions);
                   9080:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9081:     foreach my $file (@{$files}) {
1.759     albertel 9082: 	$file = &declutter_portfile($file);
1.561     banghart 9083:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9084:     }
1.613     albertel 9085:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9086:     return;
                   9087: }
                   9088: 
1.572     banghart 9089: # ------------------------------------------------------------Save Selected Files
                   9090: 
                   9091: sub save_selected_files {
                   9092:     my ($user, $path, @files) = @_;
                   9093:     my $filename = $user."savedfiles";
1.573     banghart 9094:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9095:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9096:     foreach my $file (@files) {
1.620     albertel 9097:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9098:     }
                   9099:     foreach my $file (@other_files) {
1.574     banghart 9100:         print (OUT $file."\n");
1.572     banghart 9101:     }
1.574     banghart 9102:     close (OUT);
1.572     banghart 9103:     return 'ok';
                   9104: }
                   9105: 
1.574     banghart 9106: sub clear_selected_files {
                   9107:     my ($user) = @_;
                   9108:     my $filename = $user."savedfiles";
1.1117    foxr     9109:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9110:     print (OUT undef);
                   9111:     close (OUT);
                   9112:     return ("ok");    
                   9113: }
                   9114: 
1.572     banghart 9115: sub files_in_path {
                   9116:     my ($user, $path) = @_;
                   9117:     my $filename = $user."savedfiles";
                   9118:     my %return_files;
1.1117    foxr     9119:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9120:     while (my $line_in = <IN>) {
1.574     banghart 9121:         chomp ($line_in);
                   9122:         my @paths_and_file = split (m!/!, $line_in);
                   9123:         my $file_part = pop (@paths_and_file);
                   9124:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9125:         $path_part.='/';
                   9126:         my $path_and_file = $path_part.$file_part;
                   9127:         if ($path_part eq $path) {
                   9128:             $return_files{$file_part}= 'selected';
                   9129:         }
                   9130:     }
1.574     banghart 9131:     close (IN);
                   9132:     return (\%return_files);
1.572     banghart 9133: }
                   9134: 
                   9135: # called in portfolio select mode, to show files selected NOT in current directory
                   9136: sub files_not_in_path {
                   9137:     my ($user, $path) = @_;
                   9138:     my $filename = $user."savedfiles";
                   9139:     my @return_files;
                   9140:     my $path_part;
1.1117    foxr     9141:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9142:     while (my $line = <IN>) {
1.572     banghart 9143:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9144:         my @paths_and_file = split(m|/|, $line);
                   9145:         my $file_part = pop(@paths_and_file);
                   9146:         chomp($file_part);
                   9147:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9148:         $path_part .= '/';
                   9149:         my $path_and_file = $path_part.$file_part;
                   9150:         if ($path_part ne $path) {
1.800     albertel 9151:             push(@return_files, ($path_and_file));
1.572     banghart 9152:         }
                   9153:     }
1.800     albertel 9154:     close(OUT);
1.574     banghart 9155:     return (@return_files);
1.572     banghart 9156: }
                   9157: 
1.745     raeburn  9158: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9159: 
1.745     raeburn  9160: sub get_portfile_permissions {
                   9161:     my ($domain,$user) = @_;
1.613     albertel 9162:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9163:     my ($tmp)=keys(%current_permissions);
                   9164:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9165:     return \%current_permissions;
                   9166: }
                   9167: 
                   9168: #---------------------------------------------Get portfolio file access controls
                   9169: 
1.749     raeburn  9170: sub get_access_controls {
1.745     raeburn  9171:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9172:     my %access;
                   9173:     my $real_file = $file;
                   9174:     $file =~ s/\.meta$//;
1.745     raeburn  9175:     if (defined($file)) {
1.749     raeburn  9176:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9177:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9178:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9179:             }
                   9180:         }
1.745     raeburn  9181:     } else {
1.749     raeburn  9182:         foreach my $key (keys(%{$current_permissions})) {
                   9183:             if ($key =~ /\0accesscontrol$/) {
                   9184:                 if (defined($group)) {
                   9185:                     if ($key !~ m-^\Q$group\E/-) {
                   9186:                         next;
                   9187:                     }
                   9188:                 }
                   9189:                 my ($fullpath) = split(/\0/,$key);
                   9190:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9191:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9192:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9193:                     }
                   9194:                 }
                   9195:             }
                   9196:         }
                   9197:     }
                   9198:     return %access;
                   9199: }
                   9200: 
                   9201: sub modify_access_controls {
                   9202:     my ($file_name,$changes,$domain,$user)=@_;
                   9203:     my ($outcome,$deloutcome);
                   9204:     my %store_permissions;
                   9205:     my %new_values;
                   9206:     my %new_control;
                   9207:     my %translation;
                   9208:     my @deletions = ();
                   9209:     my $now = time;
                   9210:     if (exists($$changes{'activate'})) {
                   9211:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9212:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9213:             my $numnew = scalar(@newitems);
                   9214:             for (my $i=0; $i<$numnew; $i++) {
                   9215:                 my $newkey = $newitems[$i];
                   9216:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9217:                 if ($newkey =~ /^\d+:/) { 
                   9218:                     $newkey =~ s/^(\d+)/$newid/;
                   9219:                     $translation{$1} = $newid;
                   9220:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9221:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9222:                     $translation{$1} = $newid;
                   9223:                 }
1.749     raeburn  9224:                 $new_values{$file_name."\0".$newkey} = 
                   9225:                                           $$changes{'activate'}{$newitems[$i]};
                   9226:                 $new_control{$newkey} = $now;
                   9227:             }
                   9228:         }
                   9229:     }
                   9230:     my %todelete;
                   9231:     my %changed_items;
                   9232:     foreach my $action ('delete','update') {
                   9233:         if (exists($$changes{$action})) {
                   9234:             if (ref($$changes{$action}) eq 'HASH') {
                   9235:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9236:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9237:                     if ($action eq 'delete') { 
                   9238:                         $todelete{$itemnum} = 1;
                   9239:                     } else {
                   9240:                         $changed_items{$itemnum} = $key;
                   9241:                     }
                   9242:                 }
1.745     raeburn  9243:             }
                   9244:         }
1.749     raeburn  9245:     }
                   9246:     # get lock on access controls for file.
                   9247:     my $lockhash = {
                   9248:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9249:                                                        ':'.$env{'user.domain'},
                   9250:                    }; 
                   9251:     my $tries = 0;
                   9252:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9253:    
                   9254:     while (($gotlock ne 'ok') && $tries <3) {
                   9255:         $tries ++;
                   9256:         sleep 1;
                   9257:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9258:     }
                   9259:     if ($gotlock eq 'ok') {
                   9260:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9261:         my ($tmp)=keys(%curr_permissions);
                   9262:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9263:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9264:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9265:             if (ref($curr_controls) eq 'HASH') {
                   9266:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9267:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9268:                     if (defined($todelete{$itemnum})) {
                   9269:                         push(@deletions,$file_name."\0".$control_item);
                   9270:                     } else {
                   9271:                         if (defined($changed_items{$itemnum})) {
                   9272:                             $new_control{$changed_items{$itemnum}} = $now;
                   9273:                             push(@deletions,$file_name."\0".$control_item);
                   9274:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9275:                         } else {
                   9276:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9277:                         }
                   9278:                     }
1.745     raeburn  9279:                 }
                   9280:             }
                   9281:         }
1.970     raeburn  9282:         my ($group);
                   9283:         if (&is_course($domain,$user)) {
                   9284:             ($group,my $file) = split(/\//,$file_name,2);
                   9285:         }
1.749     raeburn  9286:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9287:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9288:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9289:         #  remove lock
                   9290:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9291:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9292:         my $sqlresult =
1.970     raeburn  9293:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9294:                                     $group);
1.749     raeburn  9295:     } else {
                   9296:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9297:     }
1.749     raeburn  9298:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9299: }
                   9300: 
1.827     raeburn  9301: sub make_public_indefinitely {
1.1271  ! raeburn  9302:     my (@requrl) = @_;
        !          9303:     return &automated_portfile_access('public',\@requrl);
        !          9304: }
        !          9305: 
        !          9306: sub automated_portfile_access {
        !          9307:     my ($accesstype,$addsref,$delsref,$info) = @_;
        !          9308:     return unless (($accesstype eq 'public') || ($accesstype eq 'ip'));
        !          9309:     my %urls;
        !          9310:     if (ref($addsref) eq 'ARRAY') {
        !          9311:         foreach my $requrl (@{$addsref}) {
        !          9312:             if (&is_portfolio_url($requrl)) {
        !          9313:                 unless (exists($urls{$requrl})) {
        !          9314:                     $urls{$requrl} = 'add';
        !          9315:                 }
        !          9316:             }
        !          9317:         }
        !          9318:     }
        !          9319:     if (ref($delsref) eq 'ARRAY') {
        !          9320:         foreach my $requrl (@{$delsref}) { 
        !          9321:             if (&is_portfolio_url($requrl)) {
        !          9322:                 unless (exists($urls{$requrl})) {
        !          9323:                     $urls{$requrl} = 'delete'; 
        !          9324:                 }
        !          9325:             }
        !          9326:         }
        !          9327:     }
        !          9328:     unless (keys(%urls)) {
        !          9329:         return 'invalid';
        !          9330:     }
        !          9331:     my $ip;
        !          9332:     if ($accesstype eq 'ip') {
        !          9333:         if (ref($info) eq 'HASH') {
        !          9334:             if ($info->{'ip'} ne '') {
        !          9335:                 $ip = $info->{'ip'};
        !          9336:             }
        !          9337:         }
        !          9338:         if ($ip eq '') {
        !          9339:             return 'invalid';
        !          9340:         }
        !          9341:     }
        !          9342:     my $errors;
1.827     raeburn  9343:     my $now = time;
1.1271  ! raeburn  9344:     my %current_perms;
        !          9345:     foreach my $requrl (sort(keys(%urls))) {
        !          9346:         my $action;
        !          9347:         if ($urls{$requrl} eq 'add') {
        !          9348:             $action = 'activate';
        !          9349:         } else {
        !          9350:             $action = 'none';
        !          9351:         }
        !          9352:         my $aclnum = 0;
1.827     raeburn  9353:         my (undef,$udom,$unum,$file_name,$group) =
                   9354:             &parse_portfolio_url($requrl);
1.1271  ! raeburn  9355:         unless (exists($current_perms{$unum.':'.$udom})) {
        !          9356:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
        !          9357:         }
        !          9358:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  9359:                                                    $group,$file_name);
                   9360:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9361:             my ($num,$scope,$end,$start) = 
                   9362:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271  ! raeburn  9363:             if ($scope eq $accesstype) {
        !          9364:                 if (($start <= $now) && ($end == 0)) {
        !          9365:                     if ($accesstype eq 'ip') {
        !          9366:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
        !          9367:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
        !          9368:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
        !          9369:                                     if ($urls{$requrl} eq 'add') {
        !          9370:                                         $action = 'none';
        !          9371:                                         last;
        !          9372:                                     } else {
        !          9373:                                         $action = 'delete';
        !          9374:                                         $aclnum = $num;
        !          9375:                                         last;
        !          9376:                                     }
        !          9377:                                 }
        !          9378:                             }
        !          9379:                         }
        !          9380:                     } elsif ($accesstype eq 'public') {
        !          9381:                         if ($urls{$requrl} eq 'add') {
        !          9382:                             $action = 'none';
        !          9383:                             last;
        !          9384:                         } else {
        !          9385:                             $action = 'delete';
        !          9386:                             $aclnum = $num;
        !          9387:                             last;
        !          9388:                         }
        !          9389:                     }
        !          9390:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  9391:                     $action = 'update';
                   9392:                     $aclnum = $num;
1.1271  ! raeburn  9393:                     last;
1.827     raeburn  9394:                 }
                   9395:             }
                   9396:         }
                   9397:         if ($action eq 'none') {
1.1271  ! raeburn  9398:             next;
1.827     raeburn  9399:         } else {
                   9400:             my %changes;
                   9401:             my $newend = 0;
                   9402:             my $newstart = $now;
1.1271  ! raeburn  9403:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  9404:             $changes{$action}{$newkey} = {
1.1271  ! raeburn  9405:                 type => $accesstype,
1.827     raeburn  9406:                 time => {
                   9407:                     start => $newstart,
                   9408:                     end   => $newend,
                   9409:                 },
                   9410:             };
1.1271  ! raeburn  9411:             if ($accesstype eq 'ip') {
        !          9412:                 $changes{$action}{$newkey}{'ip'} = [$ip];
        !          9413:             }
1.827     raeburn  9414:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9415:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271  ! raeburn  9416:             unless ($outcome eq 'ok') {
        !          9417:                 $errors .= $outcome.' ';
        !          9418:             }
1.827     raeburn  9419:         }
1.1271  ! raeburn  9420:     }
        !          9421:     if ($errors) {
        !          9422:         $errors =~ s/\s$//;
        !          9423:         return $errors;
1.827     raeburn  9424:     } else {
1.1271  ! raeburn  9425:         return 'ok';
1.827     raeburn  9426:     }
                   9427: }
                   9428: 
1.745     raeburn  9429: #------------------------------------------------------Get Marked as Read Only
                   9430: 
                   9431: sub get_marked_as_readonly {
                   9432:     my ($domain,$user,$what,$group) = @_;
                   9433:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9434:     my @readonly_files;
1.629     banghart 9435:     my $cmp1=$what;
                   9436:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9437:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9438:         if (defined($group)) {
                   9439:             if ($file_name !~ m-^\Q$group\E/-) {
                   9440:                 next;
                   9441:             }
                   9442:         }
1.561     banghart 9443:         if (ref($value) eq "ARRAY"){
                   9444:             foreach my $stored_what (@{$value}) {
1.629     banghart 9445:                 my $cmp2=$stored_what;
1.759     albertel 9446:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9447:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9448:                 }
1.629     banghart 9449:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9450:                     push(@readonly_files, $file_name);
1.745     raeburn  9451:                     last;
1.563     banghart 9452:                 } elsif (!defined($what)) {
                   9453:                     push(@readonly_files, $file_name);
1.745     raeburn  9454:                     last;
1.561     banghart 9455:                 }
                   9456:             }
1.745     raeburn  9457:         }
1.561     banghart 9458:     }
                   9459:     return @readonly_files;
                   9460: }
1.577     banghart 9461: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9462: 
1.577     banghart 9463: sub get_marked_as_readonly_hash {
1.745     raeburn  9464:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9465:     my %readonly_files;
1.745     raeburn  9466:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9467:         if (defined($group)) {
                   9468:             if ($file_name !~ m-^\Q$group\E/-) {
                   9469:                 next;
                   9470:             }
                   9471:         }
1.577     banghart 9472:         if (ref($value) eq "ARRAY"){
                   9473:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9474:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9475:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9476:                         if ($lock_descriptor eq 'graded') {
                   9477:                             $readonly_files{$file_name} = 'graded';
                   9478:                         } elsif ($lock_descriptor eq 'handback') {
                   9479:                             $readonly_files{$file_name} = 'handback';
                   9480:                         } else {
                   9481:                             if (!exists($readonly_files{$file_name})) {
                   9482:                                 $readonly_files{$file_name} = 'locked';
                   9483:                             }
                   9484:                         }
1.745     raeburn  9485:                     }
1.750     banghart 9486:                 } 
1.577     banghart 9487:             }
                   9488:         } 
                   9489:     }
                   9490:     return %readonly_files;
                   9491: }
1.559     banghart 9492: # ------------------------------------------------------------ Unmark as Read Only
                   9493: 
                   9494: sub unmark_as_readonly {
1.629     banghart 9495:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9496:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9497:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9498:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9499:     my $symb_crs = $what;
                   9500:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9501:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9502:     my ($tmp)=keys(%current_permissions);
                   9503:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9504:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9505:     foreach my $file (@readonly_files) {
1.759     albertel 9506: 	my $clean_file = &declutter_portfile($file);
                   9507: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9508: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9509:         my @new_locks;
                   9510:         my @del_keys;
                   9511:         if (ref($current_locks) eq "ARRAY"){
                   9512:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9513:                 my $compare=$locker;
1.749     raeburn  9514:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9515:                     $compare=join('',@{$locker});
1.746     raeburn  9516:                     if ($compare ne $symb_crs) {
                   9517:                         push(@new_locks, $locker);
                   9518:                     }
1.563     banghart 9519:                 }
                   9520:             }
1.650     albertel 9521:             if (scalar(@new_locks) > 0) {
1.563     banghart 9522:                 $current_permissions{$file} = \@new_locks;
                   9523:             } else {
                   9524:                 push(@del_keys, $file);
1.613     albertel 9525:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9526:                 delete($current_permissions{$file});
1.563     banghart 9527:             }
                   9528:         }
1.561     banghart 9529:     }
1.613     albertel 9530:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9531:     return;
                   9532: }
1.512     banghart 9533: 
1.17      www      9534: # ------------------------------------------------------------ Directory lister
                   9535: 
                   9536: sub dirlist {
1.955     raeburn  9537:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9538:     $uri=~s/^\///;
                   9539:     $uri=~s/\/$//;
1.253     stredwic 9540:     my ($udom, $uname);
1.955     raeburn  9541:     if ($getuserdir) {
1.253     stredwic 9542:         $udom = $userdomain;
                   9543:         $uname = $username;
1.955     raeburn  9544:     } else {
                   9545:         (undef,$udom,$uname)=split(/\//,$uri);
                   9546:         if(defined($userdomain)) {
                   9547:             $udom = $userdomain;
                   9548:         }
                   9549:         if(defined($username)) {
                   9550:             $uname = $username;
                   9551:         }
1.253     stredwic 9552:     }
1.955     raeburn  9553:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9554: 
1.955     raeburn  9555:     $dirRoot = $perlvar{'lonDocRoot'};
                   9556:     if (defined($getpropath)) {
                   9557:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9558:         $dirRoot =~ s/\/$//;
1.955     raeburn  9559:     } elsif (defined($getuserdir)) {
                   9560:         my $subdir=$uname.'__';
                   9561:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9562:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9563:                    ."/$udom/$subdir/$uname";
                   9564:     } elsif (defined($alternateRoot)) {
                   9565:         $dirRoot = $alternateRoot;
1.751     banghart 9566:     }
1.253     stredwic 9567: 
                   9568:     if($udom) {
                   9569:         if($uname) {
1.1135    raeburn  9570:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9571:             if ($uhome eq 'no_host') {
                   9572:                 return ([],'no_host');
                   9573:             }
1.955     raeburn  9574:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9575:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9576:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9577:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9578:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9579:             } else {
                   9580:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9581:             }
1.605     matthew  9582:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9583:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9584:                 @listing_results = split(/:/,$listing);
                   9585:             } else {
                   9586:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9587:             }
1.1135    raeburn  9588:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9589:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9590:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9591:                 return ([],$listing);
                   9592:             } else {
                   9593:                 return (\@listing_results);
1.1135    raeburn  9594:             }
1.955     raeburn  9595:         } elsif(!$alternateRoot) {
1.1136    raeburn  9596:             my (%allusers,%listerror);
1.841     albertel 9597: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9598:  	    foreach my $tryserver (keys(%servers)) {
                   9599:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9600:                                   &escape($udom),$tryserver);
                   9601:                 if ($listing eq 'unknown_cmd') {
                   9602: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9603: 				      $udom, $tryserver);
                   9604:                 } else {
                   9605:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9606:                 }
1.841     albertel 9607: 		if ($listing eq 'unknown_cmd') {
                   9608: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9609: 				      $udom, $tryserver);
                   9610: 		    @listing_results = split(/:/,$listing);
                   9611: 		} else {
                   9612: 		    @listing_results =
                   9613: 			map { &unescape($_); } split(/:/,$listing);
                   9614: 		}
1.1136    raeburn  9615:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9616:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9617:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9618:                     $listerror{$tryserver} = $listing;
                   9619:                 } else {
1.841     albertel 9620: 		    foreach my $line (@listing_results) {
                   9621: 			my ($entry) = split(/&/,$line,2);
                   9622: 			$allusers{$entry} = 1;
                   9623: 		    }
                   9624: 		}
1.253     stredwic 9625:             }
1.1136    raeburn  9626:             my @alluserslist=();
1.800     albertel 9627:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9628:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9629:             }
1.1136    raeburn  9630:             return (\@alluserslist);
1.253     stredwic 9631:         } else {
1.1136    raeburn  9632:             return ([],'missing username');
1.253     stredwic 9633:         }
1.955     raeburn  9634:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9635:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9636:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9637:         return (\@all_domains);
1.955     raeburn  9638:     } else {
1.1136    raeburn  9639:         return ([],'missing domain');
1.275     stredwic 9640:     }
                   9641: }
                   9642: 
                   9643: # --------------------------------------------- GetFileTimestamp
                   9644: # This function utilizes dirlist and returns the date stamp for
                   9645: # when it was last modified.  It will also return an error of -1
                   9646: # if an error occurs
                   9647: 
                   9648: sub GetFileTimestamp {
1.955     raeburn  9649:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9650:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9651:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9652:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9653:                                     undef,$getuserdir);
                   9654:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9655:         return -1;
                   9656:     }
                   9657:     if (ref($fileref) eq 'ARRAY') {
                   9658:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9659:         # @stats contains first the filename, then the stat output
                   9660:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9661:     } else {
                   9662:         return -1;
1.253     stredwic 9663:     }
1.26      www      9664: }
                   9665: 
1.712     albertel 9666: sub stat_file {
                   9667:     my ($uri) = @_;
1.787     albertel 9668:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9669: 
1.955     raeburn  9670:     my ($udom,$uname,$file);
1.712     albertel 9671:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9672: 	($udom,$uname,$file) =
1.811     albertel 9673: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9674: 	$file = 'userfiles/'.$file;
                   9675:     }
                   9676:     if ($uri =~ m-^/res/-) {
                   9677: 	($udom,$uname) = 
1.807     albertel 9678: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9679: 	$file = $uri;
                   9680:     }
                   9681: 
                   9682:     if (!$udom || !$uname || !$file) {
                   9683: 	# unable to handle the uri
                   9684: 	return ();
                   9685:     }
1.956     raeburn  9686:     my $getpropath;
                   9687:     if ($file =~ /^userfiles\//) {
                   9688:         $getpropath = 1;
                   9689:     }
1.1136    raeburn  9690:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9691:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9692:         return ();
                   9693:     } else {
                   9694:         if (ref($listref) eq 'ARRAY') {
                   9695:             my @stats = split('&',$listref->[0]);
                   9696: 	    shift(@stats); #filename is first
                   9697: 	    return @stats;
                   9698:         }
1.712     albertel 9699:     }
                   9700:     return ();
                   9701: }
                   9702: 
1.26      www      9703: # -------------------------------------------------------- Value of a Condition
                   9704: 
1.713     albertel 9705: # gets the value of a specific preevaluated condition
                   9706: #    stored in the string  $env{user.state.<cid>}
                   9707: # or looks up a condition reference in the bighash and if if hasn't
                   9708: # already been evaluated recurses into docondval to get the value of
                   9709: # the condition, then memoizing it to 
                   9710: #   $env{user.state.<cid>.<condition>}
1.40      www      9711: sub directcondval {
                   9712:     my $number=shift;
1.620     albertel 9713:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9714: 	&Apache::lonuserstate::evalstate();
                   9715:     }
1.713     albertel 9716:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9717: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9718:     } elsif ($number =~ /^_/) {
                   9719: 	my $sub_condition;
                   9720: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9721: 		&GDBM_READER(),0640)) {
                   9722: 	    $sub_condition=$bighash{'conditions'.$number};
                   9723: 	    untie(%bighash);
                   9724: 	}
                   9725: 	my $value = &docondval($sub_condition);
1.949     raeburn  9726: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9727: 	return $value;
                   9728:     }
1.620     albertel 9729:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9730:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9731:     } else {
                   9732:        return 2;
                   9733:     }
                   9734: }
                   9735: 
1.713     albertel 9736: # get the collection of conditions for this resource
1.26      www      9737: sub condval {
                   9738:     my $condidx=shift;
1.54      www      9739:     my $allpathcond='';
1.713     albertel 9740:     foreach my $cond (split(/\|/,$condidx)) {
                   9741: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9742: 	    $allpathcond.=
                   9743: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9744: 	}
1.191     harris41 9745:     }
1.54      www      9746:     $allpathcond=~s/\|$//;
1.713     albertel 9747:     return &docondval($allpathcond);
                   9748: }
                   9749: 
                   9750: #evaluates an expression of conditions
                   9751: sub docondval {
                   9752:     my ($allpathcond) = @_;
                   9753:     my $result=0;
                   9754:     if ($env{'request.course.id'}
                   9755: 	&& defined($allpathcond)) {
                   9756: 	my $operand='|';
                   9757: 	my @stack;
                   9758: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9759: 	    if ($chunk eq '(') {
                   9760: 		push @stack,($operand,$result);
                   9761: 	    } elsif ($chunk eq ')') {
                   9762: 		my $before=pop @stack;
                   9763: 		if (pop @stack eq '&') {
                   9764: 		    $result=$result>$before?$before:$result;
                   9765: 		} else {
                   9766: 		    $result=$result>$before?$result:$before;
                   9767: 		}
                   9768: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9769: 		$operand=$chunk;
                   9770: 	    } else {
                   9771: 		my $new=directcondval($chunk);
                   9772: 		if ($operand eq '&') {
                   9773: 		    $result=$result>$new?$new:$result;
                   9774: 		} else {
                   9775: 		    $result=$result>$new?$result:$new;
                   9776: 		}
                   9777: 	    }
                   9778: 	}
1.26      www      9779:     }
                   9780:     return $result;
1.421     albertel 9781: }
                   9782: 
                   9783: # ---------------------------------------------------- Devalidate courseresdata
                   9784: 
                   9785: sub devalidatecourseresdata {
                   9786:     my ($coursenum,$coursedomain)=@_;
                   9787:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9788:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9789: }
                   9790: 
1.763     www      9791: 
1.200     www      9792: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9793: #
                   9794: #  Parameters:
                   9795: #      $coursenum    - Number of the course.
                   9796: #      $coursedomain - Domain at which the course was created.
                   9797: #  Returns:
                   9798: #     A hash of the course parameters along (I think) with timestamps
                   9799: #     and version info.
1.877     foxr     9800: 
1.624     albertel 9801: sub get_courseresdata {
                   9802:     my ($coursenum,$coursedomain)=@_;
1.200     www      9803:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9804:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9805:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9806:     my %dumpreply;
1.417     albertel 9807:     unless (defined($cached)) {
1.624     albertel 9808: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9809: 	$result=\%dumpreply;
1.251     albertel 9810: 	my ($tmp) = keys(%dumpreply);
                   9811: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9812: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9813: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9814: 	    return $tmp;
1.416     albertel 9815: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9816: 	    $result=undef;
1.599     albertel 9817: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9818: 	}
                   9819:     }
1.624     albertel 9820:     return $result;
                   9821: }
                   9822: 
1.633     albertel 9823: sub devalidateuserresdata {
                   9824:     my ($uname,$udom)=@_;
                   9825:     my $hashid="$udom:$uname";
                   9826:     &devalidate_cache_new('userres',$hashid);
                   9827: }
                   9828: 
1.624     albertel 9829: sub get_userresdata {
                   9830:     my ($uname,$udom)=@_;
                   9831:     #most student don\'t have any data set, check if there is some data
                   9832:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9833: 
                   9834:     my $hashid="$udom:$uname";
                   9835:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9836:     if (!defined($cached)) {
                   9837: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9838: 	$result=\%resourcedata;
                   9839: 	&do_cache_new('userres',$hashid,$result,600);
                   9840:     }
                   9841:     my ($tmp)=keys(%$result);
                   9842:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9843: 	return $result;
                   9844:     }
                   9845:     #error 2 occurs when the .db doesn't exist
                   9846:     if ($tmp!~/error: 2 /) {
1.672     albertel 9847: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9848: 		 " Trying to get resource data for ".
                   9849: 		 $uname." at ".$udom.": ".
                   9850: 		 $tmp."</font>");
                   9851:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9852: 	#&EXT_cache_set($udom,$uname);
                   9853: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9854: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9855:     }
                   9856:     return $tmp;
                   9857: }
1.879     foxr     9858: #----------------------------------------------- resdata - return resource data
                   9859: #  Purpose:
                   9860: #    Return resource data for either users or for a course.
                   9861: #  Parameters:
                   9862: #     $name      - Course/user name.
                   9863: #     $domain    - Name of the domain the user/course is registered on.
                   9864: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9865: #     @which     - Array of names of resources desired.
                   9866: #  Returns:
                   9867: #     The value of the first reasource in @which that is found in the
                   9868: #     resource hash.
                   9869: #  Exceptional Conditions:
                   9870: #     If the $type passed in is not valid (not the string 'course' or 
                   9871: #     'user', an undefined  reference is returned.
                   9872: #     If none of the resources are found, an undef is returned
1.624     albertel 9873: sub resdata {
                   9874:     my ($name,$domain,$type,@which)=@_;
                   9875:     my $result;
                   9876:     if ($type eq 'course') {
                   9877: 	$result=&get_courseresdata($name,$domain);
                   9878:     } elsif ($type eq 'user') {
                   9879: 	$result=&get_userresdata($name,$domain);
                   9880:     }
                   9881:     if (!ref($result)) { return $result; }    
1.251     albertel 9882:     foreach my $item (@which) {
1.927     albertel 9883: 	if (defined($result->{$item->[0]})) {
                   9884: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9885: 	}
1.250     albertel 9886:     }
1.291     albertel 9887:     return undef;
1.200     www      9888: }
                   9889: 
1.1236    raeburn  9890: sub get_numsuppfiles {
                   9891:     my ($cnum,$cdom,$ignorecache)=@_;
                   9892:     my $hashid=$cnum.':'.$cdom;
                   9893:     my ($suppcount,$cached);
                   9894:     unless ($ignorecache) {
                   9895:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   9896:     }
                   9897:     unless (defined($cached)) {
                   9898:         my $chome=&homeserver($cnum,$cdom);
                   9899:         unless ($chome eq 'no_host') {
                   9900:             ($suppcount,my $errors) = (0,0);
                   9901:             my $suppmap = 'supplemental.sequence';
                   9902:             ($suppcount,$errors) = 
                   9903:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   9904:         }
                   9905:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   9906:     }
                   9907:     return $suppcount;
                   9908: }
                   9909: 
1.379     matthew  9910: #
                   9911: # EXT resource caching routines
                   9912: #
                   9913: 
                   9914: sub clear_EXT_cache_status {
1.383     albertel 9915:     &delenv('cache.EXT.');
1.379     matthew  9916: }
                   9917: 
                   9918: sub EXT_cache_status {
                   9919:     my ($target_domain,$target_user) = @_;
1.383     albertel 9920:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9921:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9922:         # We know already the user has no data
                   9923:         return 1;
                   9924:     } else {
                   9925:         return 0;
                   9926:     }
                   9927: }
                   9928: 
                   9929: sub EXT_cache_set {
                   9930:     my ($target_domain,$target_user) = @_;
1.383     albertel 9931:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9932:     #&appenv({$cachename => time});
1.379     matthew  9933: }
                   9934: 
1.28      www      9935: # --------------------------------------------------------- Value of a Variable
1.58      www      9936: sub EXT {
1.715     albertel 9937: 
1.1228    raeburn  9938:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      9939:     unless ($varname) { return ''; }
1.218     albertel 9940:     #get real user name/domain, courseid and symb
                   9941:     my $courseid;
1.359     albertel 9942:     my $publicuser;
1.427     www      9943:     if ($symbparm) {
                   9944: 	$symbparm=&get_symb_from_alias($symbparm);
                   9945:     }
1.218     albertel 9946:     if (!($uname && $udom)) {
1.790     albertel 9947:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9948:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9949:     } else {
1.620     albertel 9950: 	$courseid=$env{'request.course.id'};
1.218     albertel 9951:     }
1.48      www      9952:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9953:     my $rest;
1.320     albertel 9954:     if (defined($therest[0])) {
1.48      www      9955:        $rest=join('.',@therest);
                   9956:     } else {
                   9957:        $rest='';
                   9958:     }
1.320     albertel 9959: 
1.57      www      9960:     my $qualifierrest=$qualifier;
                   9961:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9962:     my $spacequalifierrest=$space;
                   9963:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9964:     if ($realm eq 'user') {
1.48      www      9965: # --------------------------------------------------------------- user.resource
                   9966: 	if ($space eq 'resource') {
1.651     albertel 9967: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9968: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9969: 		 &&
1.744     albertel 9970: 		 ($symbparm eq &symbread()) ) {	
                   9971: 		# if we are in the middle of processing the resource the
                   9972: 		# get the value we are planning on committing
                   9973:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9974:                     return $Apache::lonhomework::results{$qualifierrest};
                   9975:                 } else {
                   9976:                     return $Apache::lonhomework::history{$qualifierrest};
                   9977:                 }
1.335     albertel 9978: 	    } else {
1.359     albertel 9979: 		my %restored;
1.620     albertel 9980: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9981: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9982: 		} else {
                   9983: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9984: 		}
1.335     albertel 9985: 		return $restored{$qualifierrest};
                   9986: 	    }
1.48      www      9987: # ----------------------------------------------------------------- user.access
                   9988:         } elsif ($space eq 'access') {
1.218     albertel 9989: 	    # FIXME - not supporting calls for a specific user
1.48      www      9990:             return &allowed($qualifier,$rest);
                   9991: # ------------------------------------------ user.preferences, user.environment
                   9992:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9993: 	    if (($uname eq $env{'user.name'}) &&
                   9994: 		($udom eq $env{'user.domain'})) {
                   9995: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9996: 	    } else {
1.359     albertel 9997: 		my %returnhash;
                   9998: 		if (!$publicuser) {
                   9999: 		    %returnhash=&userenvironment($udom,$uname,
                   10000: 						 $qualifierrest);
                   10001: 		}
1.218     albertel 10002: 		return $returnhash{$qualifierrest};
                   10003: 	    }
1.48      www      10004: # ----------------------------------------------------------------- user.course
                   10005:         } elsif ($space eq 'course') {
1.218     albertel 10006: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10007:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10008: # ------------------------------------------------------------------- user.role
                   10009:         } elsif ($space eq 'role') {
1.218     albertel 10010: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10011:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10012:             if ($qualifier eq 'value') {
                   10013: 		return $role;
                   10014:             } elsif ($qualifier eq 'extent') {
                   10015:                 return $where;
                   10016:             }
                   10017: # ----------------------------------------------------------------- user.domain
                   10018:         } elsif ($space eq 'domain') {
1.218     albertel 10019:             return $udom;
1.48      www      10020: # ------------------------------------------------------------------- user.name
                   10021:         } elsif ($space eq 'name') {
1.218     albertel 10022:             return $uname;
1.48      www      10023: # ---------------------------------------------------- Any other user namespace
1.29      www      10024:         } else {
1.359     albertel 10025: 	    my %reply;
                   10026: 	    if (!$publicuser) {
                   10027: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10028: 	    }
                   10029: 	    return $reply{$qualifierrest};
1.48      www      10030:         }
1.236     www      10031:     } elsif ($realm eq 'query') {
                   10032: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10033:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10034: 						[$spacequalifierrest]);
1.620     albertel 10035: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10036:    } elsif ($realm eq 'request') {
1.48      www      10037: # ------------------------------------------------------------- request.browser
                   10038:         if ($space eq 'browser') {
1.1145    bisitz   10039:             return $env{'browser.'.$qualifier};
1.57      www      10040: # ------------------------------------------------------------ request.filename
                   10041:         } else {
1.620     albertel 10042:             return $env{'request.'.$spacequalifierrest};
1.29      www      10043:         }
1.28      www      10044:     } elsif ($realm eq 'course') {
1.48      www      10045: # ---------------------------------------------------------- course.description
1.620     albertel 10046:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10047:     } elsif ($realm eq 'resource') {
1.165     www      10048: 
1.620     albertel 10049: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10050: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10051: 	}
1.693     albertel 10052: 
1.1232    raeburn  10053:         if ($qualifier eq '') {
                   10054: 	    if ($space eq 'title') {
                   10055: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10056: 	        return &gettitle($symbparm);
                   10057: 	    }
1.693     albertel 10058: 	
1.1232    raeburn  10059: 	    if ($space eq 'map') {
                   10060: 	        my ($map) = &decode_symb($symbparm);
                   10061: 	        return &symbread($map);
                   10062: 	    }
                   10063:             if ($space eq 'maptitle') {
                   10064:                 my ($map) = &decode_symb($symbparm);
                   10065:                 return &gettitle($map);
                   10066:             }
                   10067: 	    if ($space eq 'filename') {
                   10068: 	        if ($symbparm) {
                   10069: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10070: 	        }
                   10071: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10072: 	    }
1.1232    raeburn  10073: 
1.1233    raeburn  10074:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10075:                 if ($space eq 'visibleparts') {
                   10076:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10077:                     my $item;
                   10078:                     if (ref($navmap)) {
                   10079:                         my $res = $navmap->getBySymb($symbparm);
                   10080:                         my $parts = $res->parts();
                   10081:                         if (ref($parts) eq 'ARRAY') {
                   10082:                             $item = join(',',@{$parts});
                   10083:                         }
                   10084:                         undef($navmap);
1.1232    raeburn  10085:                     }
1.1233    raeburn  10086:                     return $item;
1.1232    raeburn  10087:                 }
                   10088:             }
                   10089:         }
1.693     albertel 10090: 
                   10091: 	my ($section, $group, @groups);
1.593     albertel 10092: 	my ($courselevelm,$courselevel);
1.1228    raeburn  10093:         if (($courseid eq '') && ($cid)) {
                   10094:             $courseid = $cid;
                   10095:         }
                   10096: 	if (($symbparm && $courseid) && 
                   10097: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      10098: 
1.218     albertel 10099: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10100: 
1.60      www      10101: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10102: 	    my $symbp=$symbparm;
1.735     albertel 10103: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10104: 
                   10105: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10106: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10107: 
1.620     albertel 10108: 	    if (($env{'user.name'} eq $uname) &&
                   10109: 		($env{'user.domain'} eq $udom)) {
                   10110: 		$section=$env{'request.course.sec'};
1.733     raeburn  10111:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10112:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10113: 	    } else {
1.539     albertel 10114: 		if (! defined($usection)) {
1.551     albertel 10115: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10116: 		} else {
                   10117: 		    $section = $usection;
                   10118: 		}
1.733     raeburn  10119:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10120: 	    }
                   10121: 
                   10122: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10123: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10124: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10125: 
1.593     albertel 10126: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10127: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10128: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10129: 
1.60      www      10130: # ----------------------------------------------------------- first, check user
1.624     albertel 10131: 
                   10132: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10133: 				       ([$courselevelr,'resource'],
                   10134: 					[$courselevelm,'map'     ],
                   10135: 					[$courselevel, 'course'  ]));
1.931     albertel 10136: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10137: 
1.594     albertel 10138: # ------------------------------------------------ second, check some of course
1.684     raeburn  10139:             my $coursereply;
1.691     raeburn  10140:             if (@groups > 0) {
                   10141:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10142:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10143:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10144:             }
1.96      www      10145: 
1.684     raeburn  10146: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10147: 				  $env{'course.'.$courseid.'.domain'},
                   10148: 				  'course',
                   10149: 				  ([$seclevelr,   'resource'],
                   10150: 				   [$seclevelm,   'map'     ],
                   10151: 				   [$seclevel,    'course'  ],
                   10152: 				   [$courselevelr,'resource']));
                   10153: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10154: 
1.60      www      10155: # ------------------------------------------------------ third, check map parms
1.218     albertel 10156: 	    my %parmhash=();
                   10157: 	    my $thisparm='';
                   10158: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10159: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10160: 		    &GDBM_READER(),0640)) {
1.218     albertel 10161: 		$thisparm=$parmhash{$symbparm};
                   10162: 		untie(%parmhash);
                   10163: 	    }
1.927     albertel 10164: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10165: 	}
1.594     albertel 10166: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10167: 
1.218     albertel 10168: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10169: 	my $filename;
                   10170: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10171: 	if ($symbparm) {
1.409     www      10172: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10173: 	} else {
1.620     albertel 10174: 	    $filename=$env{'request.filename'};
1.282     albertel 10175: 	}
                   10176: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10177: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10178: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10179: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10180: 
1.927     albertel 10181: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10182: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10183: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10184: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10185: 				     $env{'course.'.$courseid.'.domain'},
                   10186: 				     'course',
1.927     albertel 10187: 				     ([$courselevelm,'map'   ],
                   10188: 				      [$courselevel, 'course']));
                   10189: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10190: 	}
1.145     www      10191: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10192: 	unless ($space eq '0') {
1.336     albertel 10193: 	    my @parts=split(/_/,$space);
                   10194: 	    my $id=pop(@parts);
                   10195: 	    my $part=join('_',@parts);
                   10196: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10197: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10198: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10199: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10200: 	}
1.395     albertel 10201: 	if ($recurse) { return undef; }
                   10202: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10203: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10204: # ---------------------------------------------------- Any other user namespace
                   10205:     } elsif ($realm eq 'environment') {
                   10206: # ----------------------------------------------------------------- environment
1.620     albertel 10207: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10208: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10209: 	} else {
1.770     albertel 10210: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10211: 		return '';
                   10212: 	    }
1.219     albertel 10213: 	    my %returnhash=&userenvironment($udom,$uname,
                   10214: 					    $spacequalifierrest);
                   10215: 	    return $returnhash{$spacequalifierrest};
                   10216: 	}
1.28      www      10217:     } elsif ($realm eq 'system') {
1.48      www      10218: # ----------------------------------------------------------------- system.time
                   10219: 	if ($space eq 'time') {
                   10220: 	    return time;
                   10221:         }
1.696     albertel 10222:     } elsif ($realm eq 'server') {
                   10223: # ----------------------------------------------------------------- system.time
                   10224: 	if ($space eq 'name') {
                   10225: 	    return $ENV{'SERVER_NAME'};
                   10226:         }
1.28      www      10227:     }
1.48      www      10228:     return '';
1.61      www      10229: }
                   10230: 
1.927     albertel 10231: sub get_reply {
                   10232:     my ($reply_value) = @_;
1.940     raeburn  10233:     if (ref($reply_value) eq 'ARRAY') {
                   10234:         if (wantarray) {
                   10235: 	    return @$reply_value;
                   10236:         }
                   10237:         return $reply_value->[0];
                   10238:     } else {
                   10239:         return $reply_value;
1.927     albertel 10240:     }
                   10241: }
                   10242: 
1.691     raeburn  10243: sub check_group_parms {
                   10244:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10245:     my @groupitems = ();
                   10246:     my $resultitem;
1.927     albertel 10247:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10248:     foreach my $group (@{$groups}) {
                   10249:         foreach my $level (@levels) {
1.927     albertel 10250:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10251:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10252:         }
                   10253:     }
                   10254:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10255:                             $env{'course.'.$courseid.'.domain'},
                   10256:                                      'course',@groupitems);
                   10257:     return $coursereply;
                   10258: }
                   10259: 
                   10260: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10261:     my ($courseid,@groups) = @_;
                   10262:     @groups = sort(@groups);
1.691     raeburn  10263:     return @groups;
                   10264: }
                   10265: 
1.395     albertel 10266: sub packages_tab_default {
                   10267:     my ($uri,$varname)=@_;
                   10268:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10269: 
                   10270:     my (@extension,@specifics,$do_default);
                   10271:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10272: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10273: 	if ($pack_type eq 'default') {
                   10274: 	    $do_default=1;
                   10275: 	} elsif ($pack_type eq 'extension') {
                   10276: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10277: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10278: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10279: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10280: 	}
                   10281:     }
                   10282:     # first look for a package that matches the requested part id
                   10283:     foreach my $package (@specifics) {
                   10284: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10285: 	next if ($pack_part ne $part);
                   10286: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10287: 	    return $packagetab{"$pack_type&$name&default"};
                   10288: 	}
                   10289:     }
                   10290:     # look for any possible matching non extension_ package
                   10291:     foreach my $package (@specifics) {
                   10292: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10293: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10294: 	    return $packagetab{"$pack_type&$name&default"};
                   10295: 	}
1.585     albertel 10296: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10297: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10298: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10299: 	}
                   10300:     }
1.738     albertel 10301:     # look for any posible extension_ match
                   10302:     foreach my $package (@extension) {
                   10303: 	my ($package,$pack_type)=@{$package};
                   10304: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10305: 	    return $packagetab{"$pack_type&$name&default"};
                   10306: 	}
                   10307: 	if (defined($packagetab{$package."&$name&default"})) {
                   10308: 	    return $packagetab{$package."&$name&default"};
                   10309: 	}
                   10310:     }
                   10311:     # look for a global default setting
                   10312:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10313: 	return $packagetab{"default&$name&default"};
                   10314:     }
1.395     albertel 10315:     return undef;
                   10316: }
                   10317: 
1.334     albertel 10318: sub add_prefix_and_part {
                   10319:     my ($prefix,$part)=@_;
                   10320:     my $keyroot;
                   10321:     if (defined($prefix) && $prefix !~ /^__/) {
                   10322: 	# prefix that has a part already
                   10323: 	$keyroot=$prefix;
                   10324:     } elsif (defined($prefix)) {
                   10325: 	# prefix that is missing a part
                   10326: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10327:     } else {
                   10328: 	# no prefix at all
                   10329: 	if (defined($part)) { $keyroot='_'.$part; }
                   10330:     }
                   10331:     return $keyroot;
                   10332: }
                   10333: 
1.71      www      10334: # ---------------------------------------------------------------- Get metadata
                   10335: 
1.599     albertel 10336: my %metaentry;
1.1070    www      10337: my %importedpartids;
1.71      www      10338: sub metadata {
1.176     www      10339:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10340:     $uri=&declutter($uri);
1.288     albertel 10341:     # if it is a non metadata possible uri return quickly
1.529     albertel 10342:     if (($uri eq '') || 
                   10343: 	(($uri =~ m|^/*adm/|) && 
1.1217    raeburn  10344: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10345:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10346: 	return undef;
                   10347:     }
1.1261    raeburn  10348:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10349: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10350: 	return undef;
1.288     albertel 10351:     }
1.73      www      10352:     my $filename=$uri;
                   10353:     $uri=~s/\.meta$//;
1.172     www      10354: #
                   10355: # Is the metadata already cached?
1.177     www      10356: # Look at timestamp of caching
1.172     www      10357: # Everything is cached by the main uri, libraries are never directly cached
                   10358: #
1.428     albertel 10359:     if (!defined($liburi)) {
1.599     albertel 10360: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10361: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10362:     }
                   10363:     {
1.1069    www      10364: # Imported parts would go here
1.1070    www      10365:         my %importedids=();
                   10366:         my @origfileimportpartids=();
1.1069    www      10367:         my $importedparts=0;
1.172     www      10368: #
                   10369: # Is this a recursive call for a library?
                   10370: #
1.599     albertel 10371: #	if (! exists($metacache{$uri})) {
                   10372: #	    $metacache{$uri}={};
                   10373: #	}
1.924     albertel 10374: 	my $cachetime = 60*60;
1.171     www      10375:         if ($liburi) {
                   10376: 	    $liburi=&declutter($liburi);
                   10377:             $filename=$liburi;
1.401     bowersj2 10378:         } else {
1.599     albertel 10379: 	    &devalidate_cache_new('meta',$uri);
                   10380: 	    undef(%metaentry);
1.401     bowersj2 10381: 	}
1.140     www      10382:         my %metathesekeys=();
1.73      www      10383:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10384: 	my $metastring;
1.1140    www      10385: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10386: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10387: 	    $metastring = 
1.929     albertel 10388: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10389: 					  ('grade_target' => 'meta'));
                   10390: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10391: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10392:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10393: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10394: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10395: 	    $metastring=&getfile($file);
1.489     albertel 10396: 	}
1.208     albertel 10397:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10398:         my $token;
1.140     www      10399:         undef %metathesekeys;
1.71      www      10400:         while ($token=$parser->get_token) {
1.339     albertel 10401: 	    if ($token->[0] eq 'S') {
                   10402: 		if (defined($token->[2]->{'package'})) {
1.172     www      10403: #
                   10404: # This is a package - get package info
                   10405: #
1.339     albertel 10406: 		    my $package=$token->[2]->{'package'};
                   10407: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10408: 		    if (defined($token->[2]->{'id'})) { 
                   10409: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10410: 		    }
1.599     albertel 10411: 		    if ($metaentry{':packages'}) {
                   10412: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10413: 		    } else {
1.599     albertel 10414: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10415: 		    }
1.736     albertel 10416: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10417: 			my $part=$keyroot;
                   10418: 			$part=~s/^\_//;
1.736     albertel 10419: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10420: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10421: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10422: 			    # ignore package.tab specified default values
                   10423:                             # here &package_tab_default() will fetch those
                   10424: 			    if ($subp eq 'default') { next; }
1.736     albertel 10425: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10426: 			    my $unikey;
                   10427: 			    if ($pack =~ /_0$/) {
                   10428: 				$unikey='parameter_0_'.$name;
                   10429: 				$part=0;
                   10430: 			    } else {
                   10431: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10432: 			    }
1.339     albertel 10433: 			    if ($subp eq 'display') {
                   10434: 				$value.=' [Part: '.$part.']';
                   10435: 			    }
1.599     albertel 10436: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10437: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10438: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10439: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10440: 			    }
1.599     albertel 10441: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10442: 				$metaentry{':'.$unikey}=
                   10443: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10444: 			    }
1.339     albertel 10445: 			}
                   10446: 		    }
                   10447: 		} else {
1.172     www      10448: #
                   10449: # This is not a package - some other kind of start tag
1.339     albertel 10450: #
                   10451: 		    my $entry=$token->[1];
1.1068    www      10452: 		    my $unikey='';
1.175     www      10453: 
1.339     albertel 10454: 		    if ($entry eq 'import') {
1.175     www      10455: #
                   10456: # Importing a library here
1.339     albertel 10457: #
1.1067    www      10458:                         my $location=$parser->get_text('/import');
                   10459:                         my $dir=$filename;
                   10460:                         $dir=~s|[^/]*$||;
                   10461:                         $location=&filelocation($dir,$location);
1.1069    www      10462:                        
1.1068    www      10463:                         my $importmode=$token->[2]->{'importmode'};
                   10464:                         if ($importmode eq 'problem') {
1.1069    www      10465: # Import as problem/response
1.1068    www      10466:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10467:                         } elsif ($importmode eq 'part') {
                   10468: # Import as part(s)
1.1069    www      10469:                            $importedparts=1;
                   10470: # We need to get the original file and the imported file to get the part order correct
                   10471: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10472: # Load and inspect original file
1.1070    www      10473:                            if ($#origfileimportpartids<0) {
                   10474:                               undef(%importedpartids);
                   10475:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10476:                               my $origfile=&getfile($origfilelocation);
                   10477:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10478:                            }
                   10479: 
1.1069    www      10480: # Load and inspect imported file
                   10481:                            my $impfile=&getfile($location);
                   10482:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10483:                            if ($#impfilepartids>=0) {
                   10484: # This problem had parts
1.1070    www      10485:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10486:                            } else {
                   10487: # Importing by turning a single problem into a problem part
                   10488: # It gets the import-tags ID as part-ID
                   10489:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10490:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10491:                            }
1.1068    www      10492:                         } else {
                   10493: # Normal import
                   10494:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10495:                            if (defined($token->[2]->{'id'})) {
                   10496:                               $unikey.='_'.$token->[2]->{'id'};
                   10497:                            }
1.1067    www      10498:                         }
                   10499: 
1.339     albertel 10500: 			if ($depthcount<20) {
1.736     albertel 10501: 			    my $metadata = 
                   10502: 				&metadata($uri,'keys', $location,$unikey,
                   10503: 					  $depthcount+1);
                   10504: 			    foreach my $meta (split(',',$metadata)) {
                   10505: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10506: 				$metathesekeys{$meta}=1;
1.339     albertel 10507: 			    }
1.1068    www      10508: 			
                   10509:                         }
1.1067    www      10510: 		    } else {
                   10511: #
                   10512: # Not importing, some other kind of non-package, non-library start tag
                   10513: # 
                   10514:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10515:                         if (defined($token->[2]->{'id'})) {
                   10516:                             $unikey.='_'.$token->[2]->{'id'};
                   10517:                         }
1.339     albertel 10518: 			if (defined($token->[2]->{'name'})) { 
                   10519: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10520: 			}
                   10521: 			$metathesekeys{$unikey}=1;
1.736     albertel 10522: 			foreach my $param (@{$token->[3]}) {
                   10523: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10524: 				$token->[2]->{$param};
1.339     albertel 10525: 			}
                   10526: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10527: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10528: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10529: 		 # only ws inside the tag, and not in default, so use default
                   10530: 		 # as value
1.599     albertel 10531: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10532: 			} elsif ( $internaltext =~ /\S/ ) {
                   10533: 		  # something interesting inside the tag
                   10534: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10535: 			} else {
1.908     albertel 10536: 		  # no interesting values, don't set a default
1.339     albertel 10537: 			}
1.172     www      10538: # end of not-a-package not-a-library import
1.339     albertel 10539: 		    }
1.172     www      10540: # end of not-a-package start tag
1.339     albertel 10541: 		}
1.172     www      10542: # the next is the end of "start tag"
1.339     albertel 10543: 	    }
                   10544: 	}
1.483     albertel 10545: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10546: 	$extension = lc($extension);
                   10547: 	if ($extension eq 'htm') { $extension='html'; }
                   10548: 
1.737     albertel 10549: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10550: 	    #no specific packages #how's our extension
                   10551: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10552: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10553: 					 \%metathesekeys);
                   10554: 	}
1.883     albertel 10555: 
                   10556: 	if (!exists($metaentry{':packages'})
                   10557: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10558: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10559: 		#no specific packages well let's get default then
                   10560: 		if ($key!~/^default&/) { next; }
1.488     albertel 10561: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10562: 					     \%metathesekeys);
                   10563: 	    }
                   10564: 	}
1.338     www      10565: # are there custom rights to evaluate
1.599     albertel 10566: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10567: 
1.338     www      10568:     #
                   10569:     # Importing a rights file here
1.339     albertel 10570:     #
                   10571: 	    unless ($depthcount) {
1.599     albertel 10572: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10573: 		my $dir=$filename;
                   10574: 		$dir=~s|[^/]*$||;
                   10575: 		$location=&filelocation($dir,$location);
1.736     albertel 10576: 		my $rights_metadata =
                   10577: 		    &metadata($uri,'keys',$location,'_rights',
                   10578: 			      $depthcount+1);
                   10579: 		foreach my $rights (split(',',$rights_metadata)) {
                   10580: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10581: 		    $metathesekeys{$rights}=1;
1.339     albertel 10582: 		}
                   10583: 	    }
                   10584: 	}
1.737     albertel 10585: 	# uniqifiy package listing
                   10586: 	my %seen;
                   10587: 	my @uniq_packages =
                   10588: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10589: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10590: 
1.1070    www      10591:         if ($importedparts) {
                   10592: # We had imported parts and need to rebuild partorder
                   10593:            $metaentry{':partorder'}='';
                   10594:            $metathesekeys{'partorder'}=1;
                   10595:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10596:                if ($origfileimportpartids[$index] eq 'part') {
                   10597: # original part, part of the problem
                   10598:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10599:                } else {
                   10600: # we have imported parts at this position
                   10601:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10602:                }
                   10603:            }
                   10604:            $metaentry{':partorder'}=~s/^\,//;
                   10605:         }
                   10606: 
1.737     albertel 10607: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10608: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10609: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10610: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10611: # this is the end of "was not already recently cached
1.71      www      10612:     }
1.599     albertel 10613:     return $metaentry{':'.$what};
1.261     albertel 10614: }
                   10615: 
1.488     albertel 10616: sub metadata_create_package_def {
1.483     albertel 10617:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10618:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10619:     if ($subp eq 'default') { next; }
                   10620:     
1.599     albertel 10621:     if (defined($metaentry{':packages'})) {
                   10622: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10623:     } else {
1.599     albertel 10624: 	$metaentry{':packages'}=$package;
1.483     albertel 10625:     }
                   10626:     my $value=$packagetab{$key};
                   10627:     my $unikey;
                   10628:     $unikey='parameter_0_'.$name;
1.599     albertel 10629:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10630:     $$metathesekeys{$unikey}=1;
1.599     albertel 10631:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10632: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10633:     }
1.599     albertel 10634:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10635: 	$metaentry{':'.$unikey}=
                   10636: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10637:     }
                   10638: }
                   10639: 
1.261     albertel 10640: sub metadata_generate_part0 {
                   10641:     my ($metadata,$metacache,$uri) = @_;
                   10642:     my %allnames;
1.737     albertel 10643:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10644: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10645: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10646: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10647: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10648: 	    $allnames{$name}=$part;
                   10649: 	  }
                   10650: 	}
                   10651:     }
                   10652:     foreach my $name (keys(%allnames)) {
                   10653:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10654:       my $key=":parameter_0_$name";
1.261     albertel 10655:       $$metacache{"$key.part"}='0';
                   10656:       $$metacache{"$key.name"}=$name;
1.428     albertel 10657:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10658: 					   $allnames{$name}.'_'.$name.
                   10659: 					   '.type'};
1.428     albertel 10660:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10661: 			     '.display'};
1.644     www      10662:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10663:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10664:       $$metacache{"$key.display"}=$olddis;
                   10665:     }
1.71      www      10666: }
                   10667: 
1.764     albertel 10668: # ------------------------------------------------------ Devalidate title cache
                   10669: 
                   10670: sub devalidate_title_cache {
                   10671:     my ($url)=@_;
                   10672:     if (!$env{'request.course.id'}) { return; }
                   10673:     my $symb=&symbread($url);
                   10674:     if (!$symb) { return; }
                   10675:     my $key=$env{'request.course.id'}."\0".$symb;
                   10676:     &devalidate_cache_new('title',$key);
                   10677: }
                   10678: 
1.1014    droeschl 10679: # ------------------------------------------------- Get the title of a course
                   10680: 
                   10681: sub current_course_title {
                   10682:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10683: }
1.301     www      10684: # ------------------------------------------------- Get the title of a resource
                   10685: 
                   10686: sub gettitle {
                   10687:     my $urlsymb=shift;
                   10688:     my $symb=&symbread($urlsymb);
1.534     albertel 10689:     if ($symb) {
1.620     albertel 10690: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10691: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10692: 	if (defined($cached)) { 
                   10693: 	    return $result;
                   10694: 	}
1.534     albertel 10695: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10696: 	my $title='';
1.907     albertel 10697: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10698: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10699: 	} else {
                   10700: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10701: 		    &GDBM_READER(),0640)) {
                   10702: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10703: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10704: 		untie(%bighash);
                   10705: 	    }
1.534     albertel 10706: 	}
                   10707: 	$title=~s/\&colon\;/\:/gs;
                   10708: 	if ($title) {
1.1159    www      10709: # Remember both $symb and $title for dynamic metadata
                   10710:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10711:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10712: # Cache this title and then return it
1.599     albertel 10713: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10714: 	}
                   10715: 	$urlsymb=$url;
                   10716:     }
                   10717:     my $title=&metadata($urlsymb,'title');
                   10718:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10719:     return $title;
1.301     www      10720: }
1.613     albertel 10721: 
1.614     albertel 10722: sub get_slot {
                   10723:     my ($which,$cnum,$cdom)=@_;
                   10724:     if (!$cnum || !$cdom) {
1.790     albertel 10725: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10726: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10727: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10728:     }
1.703     albertel 10729:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10730:     my %slotinfo;
                   10731:     if (exists($remembered{$key})) {
                   10732: 	$slotinfo{$which} = $remembered{$key};
                   10733:     } else {
                   10734: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10735: 	&Apache::lonhomework::showhash(%slotinfo);
                   10736: 	my ($tmp)=keys(%slotinfo);
                   10737: 	if ($tmp=~/^error:/) { return (); }
                   10738: 	$remembered{$key} = $slotinfo{$which};
                   10739:     }
1.616     albertel 10740:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10741: 	return %{$slotinfo{$which}};
                   10742:     }
                   10743:     return $slotinfo{$which};
1.614     albertel 10744: }
1.1150    raeburn  10745: 
                   10746: sub get_reservable_slots {
                   10747:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10748:     my $now = time;
                   10749:     my $reservable_info;
                   10750:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10751:     if (exists($remembered{$key})) {
                   10752:         $reservable_info = $remembered{$key};
                   10753:     } else {
                   10754:         my %resv;
                   10755:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10756:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10757:         $reservable_info = \%resv;
                   10758:         $remembered{$key} = $reservable_info;
                   10759:     }
                   10760:     return $reservable_info;
                   10761: }
                   10762: 
                   10763: sub get_course_slots {
                   10764:     my ($cnum,$cdom) = @_;
                   10765:     my $hashid=$cnum.':'.$cdom;
                   10766:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10767:     if (defined($cached)) {
                   10768:         if (ref($result) eq 'HASH') {
                   10769:             return %{$result};
                   10770:         }
                   10771:     } else {
                   10772:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10773:         my ($tmp) = keys(%slots);
                   10774:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  10775:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10776:             return %slots;
                   10777:         }
                   10778:     }
                   10779:     return;
                   10780: }
                   10781: 
                   10782: sub devalidate_slots_cache {
                   10783:     my ($cnum,$cdom)=@_;
                   10784:     my $hashid=$cnum.':'.$cdom;
                   10785:     &devalidate_cache_new('allslots',$hashid);
                   10786: }
                   10787: 
1.1181    raeburn  10788: sub get_coursechange {
                   10789:     my ($cdom,$cnum) = @_;
                   10790:     if ($cdom eq '' || $cnum eq '') {
                   10791:         return unless ($env{'request.course.id'});
                   10792:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10793:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10794:     }
                   10795:     my $hashid=$cdom.'_'.$cnum;
                   10796:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10797:     if ((defined($cached)) && ($change ne '')) {
                   10798:         return $change;
                   10799:     } else {
                   10800:         my %crshash;
                   10801:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10802:         if ($crshash{'internal.contentchange'} eq '') {
                   10803:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10804:             if ($change eq '') {
                   10805:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10806:                 $change = $crshash{'internal.created'};
                   10807:             }
                   10808:         } else {
                   10809:             $change = $crshash{'internal.contentchange'};
                   10810:         }
                   10811:         my $cachetime = 600;
                   10812:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10813:     }
                   10814:     return $change;
                   10815: }
                   10816: 
                   10817: sub devalidate_coursechange_cache {
                   10818:     my ($cnum,$cdom)=@_;
                   10819:     my $hashid=$cnum.':'.$cdom;
                   10820:     &devalidate_cache_new('crschange',$hashid);
                   10821: }
                   10822: 
1.31      www      10823: # ------------------------------------------------- Update symbolic store links
                   10824: 
                   10825: sub symblist {
                   10826:     my ($mapname,%newhash)=@_;
1.438     www      10827:     $mapname=&deversion(&declutter($mapname));
1.31      www      10828:     my %hash;
1.620     albertel 10829:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10830:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10831:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10832: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10833: 		next if ($url eq 'last_known'
                   10834: 			 && $env{'form.no_update_last_known'});
                   10835: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10836: 						    $newhash{$url}->[1],
                   10837: 						    $newhash{$url}->[0]);
1.191     harris41 10838:             }
1.31      www      10839:             if (untie(%hash)) {
                   10840: 		return 'ok';
                   10841:             }
                   10842:         }
                   10843:     }
                   10844:     return 'error';
1.212     www      10845: }
                   10846: 
                   10847: # --------------------------------------------------------------- Verify a symb
                   10848: 
                   10849: sub symbverify {
1.1190    raeburn  10850:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10851:     my $thisfn=$thisurl;
1.439     www      10852:     $thisfn=&declutter($thisfn);
1.215     www      10853: # direct jump to resource in page or to a sequence - will construct own symbs
                   10854:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10855: # check URL part
1.409     www      10856:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10857: 
1.431     www      10858:     unless ($url eq $thisfn) { return 0; }
1.213     www      10859: 
1.216     www      10860:     $symb=&symbclean($symb);
1.510     www      10861:     $thisurl=&deversion($thisurl);
1.439     www      10862:     $thisfn=&deversion($thisfn);
1.213     www      10863: 
                   10864:     my %bighash;
                   10865:     my $okay=0;
1.431     www      10866: 
1.620     albertel 10867:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10868:                             &GDBM_READER(),0640)) {
1.1204    raeburn  10869:         my $noclutter;
1.1032    raeburn  10870:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10871:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  10872:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10873:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10874:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10875:                 $noclutter = 1;
                   10876:             }
                   10877:         }
                   10878:         my $ids;
                   10879:         if ($noclutter) {
                   10880:             $ids=$bighash{'ids_'.$thisurl};
                   10881:         } else {
                   10882:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10883:         }
1.1102    raeburn  10884:         unless ($ids) {
                   10885:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   10886:             $ids=$bighash{$idkey};
1.216     www      10887:         }
                   10888:         if ($ids) {
                   10889: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  10890:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  10891:                 $symb =~ s/\?.+$//;
1.1202    raeburn  10892:             }
1.800     albertel 10893: 	    foreach my $id (split(/\,/,$ids)) {
                   10894: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10895:                if (
                   10896:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  10897:    eq $symb) {
                   10898:                    if (ref($encstate)) {
                   10899:                        $$encstate = $bighash{'encrypted_'.$id};
                   10900:                    }
1.620     albertel 10901: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  10902: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   10903:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  10904: 		       $okay=1;
1.1202    raeburn  10905:                        last;
1.582     albertel 10906: 		   }
                   10907: 	       }
1.216     www      10908: 	   }
                   10909:         }
1.213     www      10910: 	untie(%bighash);
                   10911:     }
                   10912:     return $okay;
1.31      www      10913: }
                   10914: 
1.210     www      10915: # --------------------------------------------------------------- Clean-up symb
                   10916: 
                   10917: sub symbclean {
                   10918:     my $symb=shift;
1.568     albertel 10919:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10920: # remove version from map
                   10921:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10922: 
1.210     www      10923: # remove version from URL
                   10924:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10925: 
1.507     www      10926: # remove wrapper
                   10927: 
1.510     www      10928:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10929:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10930:     return $symb;
1.409     www      10931: }
                   10932: 
                   10933: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10934: 
                   10935: sub encode_symb {
                   10936:     my ($map,$resid,$url)=@_;
                   10937:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10938: }
1.409     www      10939: 
                   10940: sub decode_symb {
1.568     albertel 10941:     my $symb=shift;
                   10942:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10943:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10944:     return (&fixversion($map),$resid,&fixversion($url));
                   10945: }
                   10946: 
                   10947: sub fixversion {
                   10948:     my $fn=shift;
1.609     banghart 10949:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10950:     my %bighash;
                   10951:     my $uri=&clutter($fn);
1.620     albertel 10952:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10953: # is this cached?
1.599     albertel 10954:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10955:     if (defined($cached)) { return $result; }
                   10956: # unfortunately not cached, or expired
1.620     albertel 10957:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10958: 	    &GDBM_READER(),0640)) {
                   10959:  	if ($bighash{'version_'.$uri}) {
                   10960:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10961:  	    unless (($version eq 'mostrecent') || 
                   10962: 		    ($version==&getversion($uri))) {
1.440     www      10963:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10964:  	    }
                   10965:  	}
                   10966:  	untie %bighash;
1.413     www      10967:     }
1.599     albertel 10968:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10969: }
                   10970: 
                   10971: sub deversion {
                   10972:     my $url=shift;
                   10973:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10974:     return $url;
1.210     www      10975: }
                   10976: 
1.31      www      10977: # ------------------------------------------------------ Return symb list entry
                   10978: 
                   10979: sub symbread {
1.249     www      10980:     my ($thisfn,$donotrecurse)=@_;
1.1265    raeburn  10981:     my $cache_str='request.symbread.cached.'.$thisfn;
                   10982:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      10983: # no filename provided? try from environment
1.1265    raeburn  10984:     unless ($thisfn) {
1.620     albertel 10985:         if ($env{'request.symb'}) {
                   10986: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 10987: 	}
1.620     albertel 10988: 	$thisfn=$env{'request.filename'};
1.44      www      10989:     }
1.569     albertel 10990:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10991: # is that filename actually a symb? Verify, clean, and return
                   10992:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10993: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10994: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10995: 	}
1.242     www      10996:     }
1.44      www      10997:     $thisfn=declutter($thisfn);
1.31      www      10998:     my %hash;
1.37      www      10999:     my %bighash;
                   11000:     my $syval='';
1.620     albertel 11001:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11002:         my $targetfn = $thisfn;
1.609     banghart 11003:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11004:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11005:         }
1.687     albertel 11006: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11007: 	    $targetfn=$1;
                   11008: 	}
1.620     albertel 11009:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11010:                       &GDBM_READER(),0640)) {
1.481     raeburn  11011: 	    $syval=$hash{$targetfn};
1.37      www      11012:             untie(%hash);
                   11013:         }
                   11014: # ---------------------------------------------------------- There was an entry
                   11015:         if ($syval) {
1.601     albertel 11016: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11017: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11018: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11019: 		    #return $env{$cache_str}='';
1.601     albertel 11020: 		#}    
                   11021: 		#$syval.=$1;
                   11022: 	    #}
1.37      www      11023:         } else {
                   11024: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11025:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11026:                             &GDBM_READER(),0640)) {
1.37      www      11027: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11028:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11029:               unless ($ids) { 
                   11030:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11031:               }
                   11032:               unless ($ids) {
                   11033: # alias?
                   11034: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11035:               }
1.37      www      11036:               if ($ids) {
                   11037: # ------------------------------------------------------------------- Has ID(s)
                   11038:                  my @possibilities=split(/\,/,$ids);
1.39      www      11039:                  if ($#possibilities==0) {
                   11040: # ----------------------------------------------- There is only one possibility
1.37      www      11041: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11042: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11043: 						    $resid,$thisfn);
1.249     www      11044:                  } elsif (!$donotrecurse) {
1.39      www      11045: # ------------------------------------------ There is more than one possibility
                   11046:                      my $realpossible=0;
1.800     albertel 11047:                      foreach my $id (@possibilities) {
                   11048: 			 my $file=$bighash{'src_'.$id};
1.39      www      11049:                          if (&allowed('bre',$file)) {
1.800     albertel 11050:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      11051:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11052: 				$realpossible++;
1.626     albertel 11053:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11054: 						    $resid,$thisfn);
1.39      www      11055:                             }
                   11056: 			 }
1.191     harris41 11057:                      }
1.39      www      11058: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11059:                  } else {
                   11060:                      $syval='';
1.37      www      11061:                  }
                   11062: 	      }
                   11063:               untie(%bighash)
1.481     raeburn  11064:            }
1.31      www      11065:         }
1.62      www      11066:         if ($syval) {
1.620     albertel 11067: 	    return $env{$cache_str}=$syval;
1.62      www      11068:         }
1.31      www      11069:     }
1.949     raeburn  11070:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11071:     return $env{$cache_str}='';
1.31      www      11072: }
                   11073: 
                   11074: # ---------------------------------------------------------- Return random seed
                   11075: 
1.32      www      11076: sub numval {
                   11077:     my $txt=shift;
                   11078:     $txt=~tr/A-J/0-9/;
                   11079:     $txt=~tr/a-j/0-9/;
                   11080:     $txt=~tr/K-T/0-9/;
                   11081:     $txt=~tr/k-t/0-9/;
                   11082:     $txt=~tr/U-Z/0-5/;
                   11083:     $txt=~tr/u-z/0-5/;
                   11084:     $txt=~s/\D//g;
1.564     albertel 11085:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11086:     return int($txt);
1.368     albertel 11087: }
                   11088: 
1.484     albertel 11089: sub numval2 {
                   11090:     my $txt=shift;
                   11091:     $txt=~tr/A-J/0-9/;
                   11092:     $txt=~tr/a-j/0-9/;
                   11093:     $txt=~tr/K-T/0-9/;
                   11094:     $txt=~tr/k-t/0-9/;
                   11095:     $txt=~tr/U-Z/0-5/;
                   11096:     $txt=~tr/u-z/0-5/;
                   11097:     $txt=~s/\D//g;
                   11098:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11099:     my $total;
                   11100:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11101:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11102:     return int($total);
                   11103: }
                   11104: 
1.575     albertel 11105: sub numval3 {
                   11106:     use integer;
                   11107:     my $txt=shift;
                   11108:     $txt=~tr/A-J/0-9/;
                   11109:     $txt=~tr/a-j/0-9/;
                   11110:     $txt=~tr/K-T/0-9/;
                   11111:     $txt=~tr/k-t/0-9/;
                   11112:     $txt=~tr/U-Z/0-5/;
                   11113:     $txt=~tr/u-z/0-5/;
                   11114:     $txt=~s/\D//g;
                   11115:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11116:     my $total;
                   11117:     foreach my $val (@txts) { $total+=$val; }
                   11118:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11119:     return $total;
                   11120: }
                   11121: 
1.675     albertel 11122: sub digest {
                   11123:     my ($data)=@_;
                   11124:     my $digest=&Digest::MD5::md5($data);
                   11125:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11126:     my ($e,$f);
                   11127:     {
                   11128:         use integer;
                   11129:         $e=($a+$b);
                   11130:         $f=($c+$d);
                   11131:         if ($_64bit) {
                   11132:             $e=(($e<<32)>>32);
                   11133:             $f=(($f<<32)>>32);
                   11134:         }
                   11135:     }
                   11136:     if (wantarray) {
                   11137: 	return ($e,$f);
                   11138:     } else {
                   11139: 	my $g;
                   11140: 	{
                   11141: 	    use integer;
                   11142: 	    $g=($e+$f);
                   11143: 	    if ($_64bit) {
                   11144: 		$g=(($g<<32)>>32);
                   11145: 	    }
                   11146: 	}
                   11147: 	return $g;
                   11148:     }
                   11149: }
                   11150: 
1.368     albertel 11151: sub latest_rnd_algorithm_id {
1.675     albertel 11152:     return '64bit5';
1.366     albertel 11153: }
1.32      www      11154: 
1.503     albertel 11155: sub get_rand_alg {
                   11156:     my ($courseid)=@_;
1.790     albertel 11157:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11158:     if ($courseid) {
1.620     albertel 11159: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11160:     }
                   11161:     return &latest_rnd_algorithm_id();
                   11162: }
                   11163: 
1.562     albertel 11164: sub validCODE {
                   11165:     my ($CODE)=@_;
                   11166:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11167:     return 0;
                   11168: }
                   11169: 
1.491     albertel 11170: sub getCODE {
1.620     albertel 11171:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11172:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11173: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11174: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11175: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11176:     }
                   11177:     return undef;
                   11178: }
1.1133    foxr     11179: #
                   11180: #  Determines the random seed for a specific context:
                   11181: #
                   11182: # parameters:
                   11183: #   symb      - in course context the symb for the seed.
                   11184: #   course_id - The course id of the form domain_coursenum.
                   11185: #   domain    - Domain for the user.
                   11186: #   course    - Course for the user.
                   11187: #   cenv      - environment of the course.
                   11188: #
                   11189: # NOTE:
                   11190: #   All parameters are picked out of the environment if missing
                   11191: #   or not defined.
                   11192: #   If a symb cannot be determined the current time is used instead.
                   11193: #
                   11194: #  For a given well defined symb, courside, domain, username,
                   11195: #  and course environment, the seed is reproducible.
                   11196: #
1.31      www      11197: sub rndseed {
1.1133    foxr     11198:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11199:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11200:     if (!defined($symb)) {
1.366     albertel 11201: 	unless ($symb=$wsymb) { return time; }
                   11202:     }
1.1146    foxr     11203:     if (!defined $courseid) { 
                   11204: 	$courseid=$wcourseid; 
                   11205:     }
                   11206:     if (!defined $domain) { $domain=$wdomain; }
                   11207:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11208: 
                   11209:     my $which;
                   11210:     if (defined($cenv->{'rndseed'})) {
                   11211: 	$which = $cenv->{'rndseed'};
                   11212:     } else {
                   11213: 	$which =&get_rand_alg($courseid);
                   11214:     }
1.491     albertel 11215:     if (defined(&getCODE())) {
1.1133    foxr     11216: 
1.675     albertel 11217: 	if ($which eq '64bit5') {
                   11218: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11219: 	} elsif ($which eq '64bit4') {
1.575     albertel 11220: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11221: 	} else {
                   11222: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11223: 	}
1.675     albertel 11224:     } elsif ($which eq '64bit5') {
                   11225: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11226:     } elsif ($which eq '64bit4') {
                   11227: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11228:     } elsif ($which eq '64bit3') {
                   11229: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11230:     } elsif ($which eq '64bit2') {
                   11231: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11232:     } elsif ($which eq '64bit') {
                   11233: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11234:     }
                   11235:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11236: }
                   11237: 
                   11238: sub rndseed_32bit {
                   11239:     my ($symb,$courseid,$domain,$username)=@_;
                   11240:     {
                   11241: 	use integer;
                   11242: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11243: 	my $symbseed=numval($symb) << 22;
                   11244: 	my $namechck=unpack("%32C*",$username) << 17;
                   11245: 	my $nameseed=numval($username) << 12;
                   11246: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11247: 	my $courseseed=unpack("%32C*",$courseid);
                   11248: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11249: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11250: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11251: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11252: 	return $num;
                   11253:     }
                   11254: }
                   11255: 
                   11256: sub rndseed_64bit {
                   11257:     my ($symb,$courseid,$domain,$username)=@_;
                   11258:     {
                   11259: 	use integer;
                   11260: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11261: 	my $symbseed=numval($symb) << 10;
                   11262: 	my $namechck=unpack("%32S*",$username);
                   11263: 	
                   11264: 	my $nameseed=numval($username) << 21;
                   11265: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11266: 	my $courseseed=unpack("%32S*",$courseid);
                   11267: 	
                   11268: 	my $num1=$symbchck+$symbseed+$namechck;
                   11269: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11270: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11271: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11272: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11273: 	return "$num1,$num2";
1.155     albertel 11274:     }
1.366     albertel 11275: }
                   11276: 
1.443     albertel 11277: sub rndseed_64bit2 {
                   11278:     my ($symb,$courseid,$domain,$username)=@_;
                   11279:     {
                   11280: 	use integer;
                   11281: 	# strings need to be an even # of cahracters long, it it is odd the
                   11282:         # last characters gets thrown away
                   11283: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11284: 	my $symbseed=numval($symb) << 10;
                   11285: 	my $namechck=unpack("%32S*",$username.' ');
                   11286: 	
                   11287: 	my $nameseed=numval($username) << 21;
1.501     albertel 11288: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11289: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11290: 	
                   11291: 	my $num1=$symbchck+$symbseed+$namechck;
                   11292: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11293: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11294: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11295: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11296: 	return "$num1,$num2";
                   11297:     }
                   11298: }
                   11299: 
                   11300: sub rndseed_64bit3 {
                   11301:     my ($symb,$courseid,$domain,$username)=@_;
                   11302:     {
                   11303: 	use integer;
                   11304: 	# strings need to be an even # of cahracters long, it it is odd the
                   11305:         # last characters gets thrown away
                   11306: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11307: 	my $symbseed=numval2($symb) << 10;
                   11308: 	my $namechck=unpack("%32S*",$username.' ');
                   11309: 	
                   11310: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11311: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11312: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11313: 	
                   11314: 	my $num1=$symbchck+$symbseed+$namechck;
                   11315: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11316: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11317: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11318: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11319: 	
1.503     albertel 11320: 	return "$num1:$num2";
1.443     albertel 11321:     }
                   11322: }
                   11323: 
1.575     albertel 11324: sub rndseed_64bit4 {
                   11325:     my ($symb,$courseid,$domain,$username)=@_;
                   11326:     {
                   11327: 	use integer;
                   11328: 	# strings need to be an even # of cahracters long, it it is odd the
                   11329:         # last characters gets thrown away
                   11330: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11331: 	my $symbseed=numval3($symb) << 10;
                   11332: 	my $namechck=unpack("%32S*",$username.' ');
                   11333: 	
                   11334: 	my $nameseed=numval3($username) << 21;
                   11335: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11336: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11337: 	
                   11338: 	my $num1=$symbchck+$symbseed+$namechck;
                   11339: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11340: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11341: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11342: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11343: 	
1.575     albertel 11344: 	return "$num1:$num2";
                   11345:     }
                   11346: }
                   11347: 
1.675     albertel 11348: sub rndseed_64bit5 {
                   11349:     my ($symb,$courseid,$domain,$username)=@_;
                   11350:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11351:     return "$num1:$num2";
                   11352: }
                   11353: 
1.366     albertel 11354: sub rndseed_CODE_64bit {
                   11355:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11356:     {
1.366     albertel 11357: 	use integer;
1.443     albertel 11358: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11359: 	my $symbseed=numval2($symb);
1.491     albertel 11360: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11361: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11362: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11363: 	my $num1=$symbseed+$CODEchck;
                   11364: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11365: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11366: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11367: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11368: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11369: 	return "$num1:$num2";
1.366     albertel 11370:     }
                   11371: }
                   11372: 
1.575     albertel 11373: sub rndseed_CODE_64bit4 {
                   11374:     my ($symb,$courseid,$domain,$username)=@_;
                   11375:     {
                   11376: 	use integer;
                   11377: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11378: 	my $symbseed=numval3($symb);
                   11379: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11380: 	my $CODEseed=numval3(&getCODE());
                   11381: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11382: 	my $num1=$symbseed+$CODEchck;
                   11383: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11384: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11385: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11386: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11387: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11388: 	return "$num1:$num2";
                   11389:     }
                   11390: }
                   11391: 
1.675     albertel 11392: sub rndseed_CODE_64bit5 {
                   11393:     my ($symb,$courseid,$domain,$username)=@_;
                   11394:     my $code = &getCODE();
                   11395:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11396:     return "$num1:$num2";
                   11397: }
                   11398: 
1.366     albertel 11399: sub setup_random_from_rndseed {
                   11400:     my ($rndseed)=@_;
1.503     albertel 11401:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  11402:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   11403:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   11404:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   11405:         } else {
                   11406:             &Math::Random::random_set_seed($num1,$num2);
                   11407:         }
1.366     albertel 11408:     } else {
                   11409: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11410:     }
1.36      albertel 11411: }
                   11412: 
1.474     albertel 11413: sub latest_receipt_algorithm_id {
1.835     albertel 11414:     return 'receipt3';
1.474     albertel 11415: }
                   11416: 
1.480     www      11417: sub recunique {
                   11418:     my $fucourseid=shift;
                   11419:     my $unique;
1.835     albertel 11420:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11421: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11422: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11423:     } else {
                   11424: 	$unique=$perlvar{'lonReceipt'};
                   11425:     }
                   11426:     return unpack("%32C*",$unique);
                   11427: }
                   11428: 
                   11429: sub recprefix {
                   11430:     my $fucourseid=shift;
                   11431:     my $prefix;
1.835     albertel 11432:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11433: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11434: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11435:     } else {
                   11436: 	$prefix=$perlvar{'lonHostID'};
                   11437:     }
                   11438:     return unpack("%32C*",$prefix);
                   11439: }
                   11440: 
1.76      www      11441: sub ireceipt {
1.474     albertel 11442:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11443: 
                   11444:     my $return =&recprefix($fucourseid).'-';
                   11445: 
                   11446:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11447: 	$env{'request.state'} eq 'construct') {
                   11448: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11449: 	return $return;
                   11450:     }
                   11451: 
1.76      www      11452:     my $cuname=unpack("%32C*",$funame);
                   11453:     my $cudom=unpack("%32C*",$fudom);
                   11454:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11455:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11456:     my $cunique=&recunique($fucourseid);
1.474     albertel 11457:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11458:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11459: 
1.790     albertel 11460: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11461: 			       
                   11462: 	$return.= ($cunique%$cuname+
                   11463: 		   $cunique%$cudom+
                   11464: 		   $cusymb%$cuname+
                   11465: 		   $cusymb%$cudom+
                   11466: 		   $cucourseid%$cuname+
                   11467: 		   $cucourseid%$cudom+
                   11468: 		   $cpart%$cuname+
                   11469: 		   $cpart%$cudom);
                   11470:     } else {
                   11471: 	$return.= ($cunique%$cuname+
                   11472: 		   $cunique%$cudom+
                   11473: 		   $cusymb%$cuname+
                   11474: 		   $cusymb%$cudom+
                   11475: 		   $cucourseid%$cuname+
                   11476: 		   $cucourseid%$cudom);
                   11477:     }
                   11478:     return $return;
1.76      www      11479: }
                   11480: 
                   11481: sub receipt {
1.474     albertel 11482:     my ($part)=@_;
1.790     albertel 11483:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11484:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11485: }
1.260     ng       11486: 
1.790     albertel 11487: sub whichuser {
                   11488:     my ($passedsymb)=@_;
                   11489:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11490:     if (defined($env{'form.grade_symb'})) {
                   11491: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11492: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11493: 	if (!$allowed &&
                   11494: 	    exists($env{'request.course.sec'}) &&
                   11495: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11496: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11497: 			      '/'.$env{'request.course.sec'});
                   11498: 	}
                   11499: 	if ($allowed) {
                   11500: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11501: 	    $courseid=$tmp_courseid;
                   11502: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11503: 	    ($name)=&get_env_multiple('form.grade_username');
                   11504: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11505: 	}
                   11506:     }
                   11507:     if (!$passedsymb) {
                   11508: 	$symb=&symbread();
                   11509:     } else {
                   11510: 	$symb=$passedsymb;
                   11511:     }
                   11512:     $courseid=$env{'request.course.id'};
                   11513:     $domain=$env{'user.domain'};
                   11514:     $name=$env{'user.name'};
                   11515:     if ($name eq 'public' && $domain eq 'public') {
                   11516: 	if (!defined($env{'form.username'})) {
                   11517: 	    $env{'form.username'}.=time.rand(10000000);
                   11518: 	}
                   11519: 	$name.=$env{'form.username'};
                   11520:     }
                   11521:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11522: 
                   11523: }
                   11524: 
1.36      albertel 11525: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11526: # returns either the contents of the file or 
                   11527: # -1 if the file doesn't exist
1.481     raeburn  11528: #
                   11529: # if the target is a file that was uploaded via DOCS, 
                   11530: # a check will be made to see if a current copy exists on the local server,
                   11531: # if it does this will be served, otherwise a copy will be retrieved from
                   11532: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11533: # the local server.   
1.472     albertel 11534: 
1.36      albertel 11535: sub getfile {
1.538     albertel 11536:     my ($file) = @_;
1.609     banghart 11537:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11538:     &repcopy($file);
                   11539:     return &readfile($file);
                   11540: }
                   11541: 
                   11542: sub repcopy_userfile {
                   11543:     my ($file)=@_;
1.1142    raeburn  11544:     my $londocroot = $perlvar{'lonDocRoot'};
                   11545:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11546:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11547:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11548: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11549:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11550:     if (-e "$file") {
1.828     www      11551: # we already have a local copy, check it out
1.538     albertel 11552: 	my @fileinfo = stat($file);
1.828     www      11553: 	my $rtncode;
                   11554: 	my $info;
1.538     albertel 11555: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11556: 	if ($lwpresp ne 'ok') {
1.828     www      11557: # there is no such file anymore, even though we had a local copy
1.482     albertel 11558: 	    if ($rtncode eq '404') {
1.538     albertel 11559: 		unlink($file);
1.482     albertel 11560: 	    }
                   11561: 	    return -1;
                   11562: 	}
                   11563: 	if ($info < $fileinfo[9]) {
1.828     www      11564: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11565: 	    return 'ok';
1.828     www      11566: 	} else {
                   11567: # the file is outdated, get rid of it
                   11568: 	    unlink($file);
1.482     albertel 11569: 	}
1.828     www      11570:     }
                   11571: # one way or the other, at this point, we don't have the file
                   11572: # construct the correct path for the file
                   11573:     my @parts = ($cdom,$cnum); 
                   11574:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11575: 	push @parts, split(/\//,$1);
                   11576:     }
                   11577:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11578:     foreach my $part (@parts) {
                   11579: 	$path .= '/'.$part;
                   11580: 	if (!-e $path) {
                   11581: 	    mkdir($path,0770);
1.482     albertel 11582: 	}
                   11583:     }
1.828     www      11584: # now the path exists for sure
                   11585: # get a user agent
                   11586:     my $ua=new LWP::UserAgent;
                   11587:     my $transferfile=$file.'.in.transfer';
                   11588: # FIXME: this should flock
                   11589:     if (-e $transferfile) { return 'ok'; }
                   11590:     my $request;
                   11591:     $uri=~s/^\///;
1.980     raeburn  11592:     my $homeserver = &homeserver($cnum,$cdom);
                   11593:     my $protocol = $protocol{$homeserver};
                   11594:     $protocol = 'http' if ($protocol ne 'https');
                   11595:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11596:     my $response=$ua->request($request,$transferfile);
                   11597: # did it work?
                   11598:     if ($response->is_error()) {
                   11599: 	unlink($transferfile);
                   11600: 	&logthis("Userfile repcopy failed for $uri");
                   11601: 	return -1;
                   11602:     }
                   11603: # worked, rename the transfer file
                   11604:     rename($transferfile,$file);
1.607     raeburn  11605:     return 'ok';
1.481     raeburn  11606: }
                   11607: 
1.517     albertel 11608: sub tokenwrapper {
                   11609:     my $uri=shift;
1.980     raeburn  11610:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11611:     $uri=~s|^/||;
1.620     albertel 11612:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11613:     my $token=$1;
1.552     albertel 11614:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11615:     if ($udom && $uname && $file) {
                   11616: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11617:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11618:         my $homeserver = &homeserver($uname,$udom);
                   11619:         my $protocol = $protocol{$homeserver};
                   11620:         $protocol = 'http' if ($protocol ne 'https');
                   11621:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11622:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11623:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11624:     } else {
                   11625:         return '/adm/notfound.html';
                   11626:     }
                   11627: }
                   11628: 
1.828     www      11629: # call with reqtype HEAD: get last modification time
                   11630: # call with reqtype GET: get the file contents
                   11631: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11632: #
1.481     raeburn  11633: sub getuploaded {
                   11634:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11635:     $uri=~s/^\///;
1.980     raeburn  11636:     my $homeserver = &homeserver($cnum,$cdom);
                   11637:     my $protocol = $protocol{$homeserver};
                   11638:     $protocol = 'http' if ($protocol ne 'https');
                   11639:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11640:     my $ua=new LWP::UserAgent;
                   11641:     my $request=new HTTP::Request($reqtype,$uri);
                   11642:     my $response=$ua->request($request);
                   11643:     $$rtncode = $response->code;
1.482     albertel 11644:     if (! $response->is_success()) {
                   11645: 	return 'failed';
                   11646:     }      
                   11647:     if ($reqtype eq 'HEAD') {
1.486     www      11648: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11649:     } elsif ($reqtype eq 'GET') {
                   11650: 	$$info = $response->content;
1.472     albertel 11651:     }
1.482     albertel 11652:     return 'ok';
1.36      albertel 11653: }
                   11654: 
1.481     raeburn  11655: sub readfile {
                   11656:     my $file = shift;
                   11657:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11658:     my $fh;
                   11659:     open($fh,"<$file");
                   11660:     my $a='';
1.800     albertel 11661:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11662:     return $a;
                   11663: }
                   11664: 
1.36      albertel 11665: sub filelocation {
1.590     banghart 11666:     my ($dir,$file) = @_;
                   11667:     my $location;
                   11668:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11669: 
                   11670:     if ($file =~ m-^/adm/-) {
                   11671: 	$file=~s-^/adm/wrapper/-/-;
                   11672: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11673:     }
1.882     albertel 11674: 
1.1139    www      11675:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11676:         $location = $file;
1.609     banghart 11677:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11678:         my ($udom,$uname,$filename)=
1.811     albertel 11679:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11680:         my $home=&homeserver($uname,$udom);
                   11681:         my $is_me=0;
                   11682:         my @ids=&current_machine_ids();
                   11683:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11684:         if ($is_me) {
1.1117    foxr     11685:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11686:         } else {
                   11687:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11688:   	      $udom.'/'.$uname.'/'.$filename;
                   11689:         }
1.882     albertel 11690:     } elsif ($file =~ m-^/adm/-) {
                   11691: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11692:     } else {
                   11693:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11694:         $file=~s:^/(res|priv)/:/:;
                   11695:         my $space=$1;
1.590     banghart 11696:         if ( !( $file =~ m:^/:) ) {
                   11697:             $location = $dir. '/'.$file;
                   11698:         } else {
1.1142    raeburn  11699:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11700:         }
1.59      albertel 11701:     }
1.590     banghart 11702:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11703:     while ($location=~m{/\.\./}) {
                   11704: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11705: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11706: 	} else {
                   11707: 	    $location=~ s{/\.\./}{/}g;
                   11708: 	}
                   11709:     } #remove dir/..
1.590     banghart 11710:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11711:     return $location;
1.46      www      11712: }
1.36      albertel 11713: 
1.46      www      11714: sub hreflocation {
                   11715:     my ($dir,$file)=@_;
1.980     raeburn  11716:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11717: 	$file=filelocation($dir,$file);
1.700     albertel 11718:     } elsif ($file=~m-^/adm/-) {
                   11719: 	$file=~s-^/adm/wrapper/-/-;
                   11720: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11721:     }
                   11722:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11723: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11724:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11725: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11726: 	        {/uploaded/$1/$2/}x;
1.46      www      11727:     }
1.913     albertel 11728:     if ($file=~ m{^/userfiles/}) {
                   11729: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11730:     }
1.462     albertel 11731:     return $file;
1.465     albertel 11732: }
                   11733: 
1.1139    www      11734: 
                   11735: 
                   11736: 
                   11737: 
1.465     albertel 11738: sub current_machine_domains {
1.853     albertel 11739:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11740: }
                   11741: 
                   11742: sub machine_domains {
                   11743:     my ($hostname) = @_;
1.465     albertel 11744:     my @domains;
1.838     albertel 11745:     my %hostname = &all_hostnames();
1.465     albertel 11746:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11747: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11748: 	if ($hostname eq $name) {
1.844     albertel 11749: 	    push(@domains,&host_domain($id));
1.465     albertel 11750: 	}
                   11751:     }
                   11752:     return @domains;
                   11753: }
                   11754: 
                   11755: sub current_machine_ids {
1.853     albertel 11756:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11757: }
                   11758: 
                   11759: sub machine_ids {
                   11760:     my ($hostname) = @_;
                   11761:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11762:     my @ids;
1.888     albertel 11763:     my %name_to_host = &all_names();
1.889     albertel 11764:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11765: 	return @{ $name_to_host{$hostname} };
                   11766:     }
                   11767:     return;
1.31      www      11768: }
                   11769: 
1.824     raeburn  11770: sub additional_machine_domains {
                   11771:     my @domains;
                   11772:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11773:     while( my $line = <$fh>) {
                   11774:         $line =~ s/\s//g;
                   11775:         push(@domains,$line);
                   11776:     }
                   11777:     return @domains;
                   11778: }
                   11779: 
                   11780: sub default_login_domain {
                   11781:     my $domain = $perlvar{'lonDefDomain'};
                   11782:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11783:     foreach my $posdom (&current_machine_domains(),
                   11784:                         &additional_machine_domains()) {
                   11785:         if (lc($posdom) eq lc($testdomain)) {
                   11786:             $domain=$posdom;
                   11787:             last;
                   11788:         }
                   11789:     }
                   11790:     return $domain;
                   11791: }
                   11792: 
1.31      www      11793: # ------------------------------------------------------------- Declutters URLs
                   11794: 
                   11795: sub declutter {
                   11796:     my $thisfn=shift;
1.569     albertel 11797:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  11798:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   11799:         $thisfn=~s{^/home/httpd/html}{};
                   11800:     }
1.31      www      11801:     $thisfn=~s/^\///;
1.697     albertel 11802:     $thisfn=~s|^adm/wrapper/||;
                   11803:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11804:     $thisfn=~s/^res\///;
1.1172    bisitz   11805:     $thisfn=~s/^priv\///;
1.1032    raeburn  11806:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11807:         $thisfn=~s/\?.+$//;
                   11808:     }
1.268     www      11809:     return $thisfn;
                   11810: }
                   11811: 
                   11812: # ------------------------------------------------------------- Clutter up URLs
                   11813: 
                   11814: sub clutter {
                   11815:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11816:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11817: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11818:        $thisfn='/res'.$thisfn; 
                   11819:     }
1.1031    raeburn  11820:     if ($thisfn !~m|^/adm|) {
                   11821: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11822: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11823: 	} else {
                   11824: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11825: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11826: 	    if ($embstyle eq 'ssi'
                   11827: 		|| ($embstyle eq 'hdn')
                   11828: 		|| ($embstyle eq 'rat')
                   11829: 		|| ($embstyle eq 'prv')
                   11830: 		|| ($embstyle eq 'ign')) {
                   11831: 		#do nothing with these
                   11832: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11833: 		|| ($embstyle eq 'emb')
                   11834: 		|| ($embstyle eq 'wrp')) {
                   11835: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11836: 	    } elsif ($embstyle eq 'unk'
                   11837: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11838: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11839: 	    } else {
1.718     www      11840: #		&logthis("Got a blank emb style");
1.695     albertel 11841: 	    }
1.694     albertel 11842: 	}
                   11843:     }
1.31      www      11844:     return $thisfn;
1.12      www      11845: }
                   11846: 
1.787     albertel 11847: sub clutter_with_no_wrapper {
                   11848:     my $uri = &clutter(shift);
                   11849:     if ($uri =~ m-^/adm/-) {
                   11850: 	$uri =~ s-^/adm/wrapper/-/-;
                   11851: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11852:     }
                   11853:     return $uri;
                   11854: }
                   11855: 
1.557     albertel 11856: sub freeze_escape {
                   11857:     my ($value)=@_;
                   11858:     if (ref($value)) {
                   11859: 	$value=&nfreeze($value);
                   11860: 	return '__FROZEN__'.&escape($value);
                   11861:     }
                   11862:     return &escape($value);
                   11863: }
                   11864: 
1.11      www      11865: 
1.557     albertel 11866: sub thaw_unescape {
                   11867:     my ($value)=@_;
                   11868:     if ($value =~ /^__FROZEN__/) {
                   11869: 	substr($value,0,10,undef);
                   11870: 	$value=&unescape($value);
                   11871: 	return &thaw($value);
                   11872:     }
                   11873:     return &unescape($value);
                   11874: }
                   11875: 
1.436     albertel 11876: sub correct_line_ends {
                   11877:     my ($result)=@_;
                   11878:     $$result =~s/\r\n/\n/mg;
                   11879:     $$result =~s/\r/\n/mg;
1.415     albertel 11880: }
1.1       albertel 11881: # ================================================================ Main Program
                   11882: 
1.184     www      11883: sub goodbye {
1.204     albertel 11884:    &logthis("Starting Shut down");
1.443     albertel 11885: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11886:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11887: #converted
1.599     albertel 11888: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11889:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11890: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11891: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11892: #1.1 only
1.870     albertel 11893: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11894: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11895: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11896: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11897:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11898:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11899:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11900:    &flushcourselogs();
                   11901:    &logthis("Shutting down");
                   11902: }
                   11903: 
1.852     albertel 11904: sub get_dns {
1.1210    raeburn  11905:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11906:     if (!$ignore_cache) {
                   11907: 	my ($content,$cached)=
                   11908: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11909: 	if ($cached) {
1.1210    raeburn  11910: 	    &$func($content,$hashref);
1.869     albertel 11911: 	    return;
                   11912: 	}
                   11913:     }
                   11914: 
                   11915:     my %alldns;
1.852     albertel 11916:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11917:     foreach my $dns (<$config>) {
                   11918: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11919:         my $line = $1;
                   11920:         my ($host,$protocol) = split(/:/,$line);
                   11921:         if ($protocol ne 'https') {
                   11922:             $protocol = 'http';
                   11923:         }
                   11924: 	$alldns{$host} = $protocol;
1.869     albertel 11925:     }
                   11926:     while (%alldns) {
1.1263    raeburn  11927: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 11928: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11929:         $ua->timeout(30);
1.979     raeburn  11930: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11931: 	my $response=$ua->request($request);
1.979     raeburn  11932:         delete($alldns{$dns});
1.852     albertel 11933: 	next if ($response->is_error());
                   11934: 	my @content = split("\n",$response->content);
1.1210    raeburn  11935: 	unless ($nocache) {
1.1219    raeburn  11936: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  11937: 	}
                   11938: 	&$func(\@content,$hashref);
1.869     albertel 11939: 	return;
1.852     albertel 11940:     }
                   11941:     close($config);
1.871     albertel 11942:     my $which = (split('/',$url))[3];
                   11943:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11944:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11945:     my @content = <$config>;
1.1210    raeburn  11946:     &$func(\@content,$hashref);
                   11947:     return;
                   11948: }
                   11949: 
                   11950: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  11951: sub parse_dns_checksums_tab {
1.1210    raeburn  11952:     my ($lines,$hashref) = @_;
1.1264    raeburn  11953:     my $lonhost = $perlvar{'lonHostID'};
                   11954:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  11955:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  11956:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   11957:     my $webconfdir = '/etc/httpd/conf';
                   11958:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   11959:         $webconfdir = '/etc/apache2';
                   11960:     } elsif ($distro =~ /^sles(\d+)$/) {
                   11961:         if ($1 >= 10) {
                   11962:             $webconfdir = '/etc/apache2';
                   11963:         }
                   11964:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   11965:         if ($1 >= 10.0) {
                   11966:             $webconfdir = '/etc/apache2';
                   11967:         }
                   11968:     }
1.1210    raeburn  11969:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11970:     my (%chksum,%revnum);
                   11971:     if (ref($lines) eq 'ARRAY') {
                   11972:         chomp(@{$lines});
1.1238    raeburn  11973:         my $version = shift(@{$lines});
                   11974:         if ($version eq $release) {  
1.1210    raeburn  11975:             foreach my $line (@{$lines}) {
1.1238    raeburn  11976:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  11977:                 if ($file =~ m{^/etc/httpd/conf}) {
                   11978:                     if ($webconfdir eq '/etc/apache2') {
                   11979:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   11980:                     }
                   11981:                 }
1.1238    raeburn  11982:                 $chksum{$file} = $shasum;
                   11983:                 $revnum{$file} = $version;
1.1210    raeburn  11984:             }
                   11985:             if (ref($hashref) eq 'HASH') {
                   11986:                 %{$hashref} = (
                   11987:                                 sums     => \%chksum,
                   11988:                                 versions => \%revnum,
                   11989:                               );
                   11990:             }
                   11991:         }
                   11992:     }
1.869     albertel 11993:     return;
1.852     albertel 11994: }
1.1210    raeburn  11995: 
                   11996: sub fetch_dns_checksums {
1.1238    raeburn  11997:     my %checksums;
                   11998:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  11999:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  12000:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12001:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  12002:              \%checksums);
1.1210    raeburn  12003:     return \%checksums;
                   12004: }
                   12005: 
1.327     albertel 12006: # ------------------------------------------------------------ Read domain file
                   12007: {
1.852     albertel 12008:     my $loaded;
1.846     albertel 12009:     my %domain;
                   12010: 
1.852     albertel 12011:     sub parse_domain_tab {
                   12012: 	my ($lines) = @_;
                   12013: 	foreach my $line (@$lines) {
                   12014: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12015: 
1.846     albertel 12016: 	    chomp($line);
1.852     albertel 12017: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12018: 	    my %this_domain;
                   12019: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12020: 			       'lang_def', 'city', 'longi', 'lati',
                   12021: 			       'primary') {
                   12022: 		$this_domain{$field} = shift(@elements);
                   12023: 	    }
                   12024: 	    $domain{$name} = \%this_domain;
1.852     albertel 12025: 	}
                   12026:     }
1.864     albertel 12027: 
                   12028:     sub reset_domain_info {
                   12029: 	undef($loaded);
                   12030: 	undef(%domain);
                   12031:     }
                   12032: 
1.852     albertel 12033:     sub load_domain_tab {
1.869     albertel 12034: 	my ($ignore_cache) = @_;
                   12035: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 12036: 	my $fh;
                   12037: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12038: 	    my @lines = <$fh>;
                   12039: 	    &parse_domain_tab(\@lines);
1.448     albertel 12040: 	}
1.852     albertel 12041: 	close($fh);
                   12042: 	$loaded = 1;
1.327     albertel 12043:     }
1.846     albertel 12044: 
                   12045:     sub domain {
1.852     albertel 12046: 	&load_domain_tab() if (!$loaded);
                   12047: 
1.846     albertel 12048: 	my ($name,$what) = @_;
                   12049: 	return if ( !exists($domain{$name}) );
                   12050: 
                   12051: 	if (!$what) {
                   12052: 	    return $domain{$name}{'description'};
                   12053: 	}
                   12054: 	return $domain{$name}{$what};
                   12055:     }
1.974     raeburn  12056: 
                   12057:     sub domain_info {
                   12058:         &load_domain_tab() if (!$loaded);
                   12059:         return %domain;
                   12060:     }
                   12061: 
1.327     albertel 12062: }
                   12063: 
                   12064: 
1.1       albertel 12065: # ------------------------------------------------------------- Read hosts file
                   12066: {
1.838     albertel 12067:     my %hostname;
1.844     albertel 12068:     my %hostdom;
1.845     albertel 12069:     my %libserv;
1.852     albertel 12070:     my $loaded;
1.888     albertel 12071:     my %name_to_host;
1.1074    raeburn  12072:     my %internetdom;
1.1107    raeburn  12073:     my %LC_dns_serv;
1.852     albertel 12074: 
                   12075:     sub parse_hosts_tab {
                   12076: 	my ($file) = @_;
                   12077: 	foreach my $configline (@$file) {
                   12078: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12079:             chomp($configline);
                   12080: 	    if ($configline =~ /^\^/) {
                   12081:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12082:                     $LC_dns_serv{$1} = 1;
                   12083:                 }
                   12084:                 next;
                   12085:             }
1.1074    raeburn  12086: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12087: 	    $name=~s/\s//g;
                   12088: 	    if ($id && $domain && $role && $name) {
                   12089: 		$hostname{$id}=$name;
1.888     albertel 12090: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12091: 		$hostdom{$id}=$domain;
                   12092: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12093:                 if (defined($protocol)) {
                   12094:                     if ($protocol eq 'https') {
                   12095:                         $protocol{$id} = $protocol;
                   12096:                     } else {
                   12097:                         $protocol{$id} = 'http'; 
                   12098:                     }
1.968     raeburn  12099:                 } else {
1.969     raeburn  12100:                     $protocol{$id} = 'http';
1.968     raeburn  12101:                 }
1.1074    raeburn  12102:                 if (defined($intdom)) {
                   12103:                     $internetdom{$id} = $intdom;
                   12104:                 }
1.852     albertel 12105: 	    }
                   12106: 	}
                   12107:     }
1.864     albertel 12108:     
                   12109:     sub reset_hosts_info {
1.897     albertel 12110: 	&purge_remembered();
1.864     albertel 12111: 	&reset_domain_info();
                   12112: 	&reset_hosts_ip_info();
1.892     albertel 12113: 	undef(%name_to_host);
1.864     albertel 12114: 	undef(%hostname);
                   12115: 	undef(%hostdom);
                   12116: 	undef(%libserv);
                   12117: 	undef($loaded);
                   12118:     }
1.1       albertel 12119: 
1.852     albertel 12120:     sub load_hosts_tab {
1.869     albertel 12121: 	my ($ignore_cache) = @_;
                   12122: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 12123: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12124: 	my @config = <$config>;
                   12125: 	&parse_hosts_tab(\@config);
                   12126: 	close($config);
                   12127: 	$loaded=1;
1.1       albertel 12128:     }
1.852     albertel 12129: 
1.838     albertel 12130:     sub hostname {
1.852     albertel 12131: 	&load_hosts_tab() if (!$loaded);
                   12132: 
1.838     albertel 12133: 	my ($lonid) = @_;
                   12134: 	return $hostname{$lonid};
                   12135:     }
1.845     albertel 12136: 
1.838     albertel 12137:     sub all_hostnames {
1.852     albertel 12138: 	&load_hosts_tab() if (!$loaded);
                   12139: 
1.838     albertel 12140: 	return %hostname;
                   12141:     }
1.845     albertel 12142: 
1.888     albertel 12143:     sub all_names {
                   12144: 	&load_hosts_tab() if (!$loaded);
                   12145: 
                   12146: 	return %name_to_host;
                   12147:     }
                   12148: 
1.974     raeburn  12149:     sub all_host_domain {
                   12150:         &load_hosts_tab() if (!$loaded);
                   12151:         return %hostdom;
                   12152:     }
                   12153: 
1.845     albertel 12154:     sub is_library {
1.852     albertel 12155: 	&load_hosts_tab() if (!$loaded);
                   12156: 
1.845     albertel 12157: 	return exists($libserv{$_[0]});
                   12158:     }
                   12159: 
                   12160:     sub all_library {
1.852     albertel 12161: 	&load_hosts_tab() if (!$loaded);
                   12162: 
1.845     albertel 12163: 	return %libserv;
                   12164:     }
                   12165: 
1.1062    droeschl 12166:     sub unique_library {
                   12167: 	#2x reverse removes all hostnames that appear more than once
                   12168:         my %unique = reverse &all_library();
                   12169:         return reverse %unique;
                   12170:     }
                   12171: 
1.841     albertel 12172:     sub get_servers {
1.852     albertel 12173: 	&load_hosts_tab() if (!$loaded);
                   12174: 
1.841     albertel 12175: 	my ($domain,$type) = @_;
                   12176: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12177: 	                                          : %hostname;
                   12178: 	my %result;
1.842     albertel 12179: 	if (ref($domain) eq 'ARRAY') {
                   12180: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12181: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12182: 		    $result{$host} = $hostname;
                   12183: 		}
                   12184: 	    }
                   12185: 	} else {
                   12186: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12187: 		if ($hostdom{$host} eq $domain) {
                   12188: 		    $result{$host} = $hostname;
                   12189: 		}
1.841     albertel 12190: 	    }
                   12191: 	}
                   12192: 	return %result;
                   12193:     }
1.845     albertel 12194: 
1.1062    droeschl 12195:     sub get_unique_servers {
                   12196:         my %unique = reverse &get_servers(@_);
                   12197: 	return reverse %unique;
                   12198:     }
                   12199: 
1.844     albertel 12200:     sub host_domain {
1.852     albertel 12201: 	&load_hosts_tab() if (!$loaded);
                   12202: 
1.844     albertel 12203: 	my ($lonid) = @_;
                   12204: 	return $hostdom{$lonid};
                   12205:     }
                   12206: 
1.841     albertel 12207:     sub all_domains {
1.852     albertel 12208: 	&load_hosts_tab() if (!$loaded);
                   12209: 
1.841     albertel 12210: 	my %seen;
                   12211: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12212: 	return @uniq;
                   12213:     }
1.1074    raeburn  12214: 
                   12215:     sub internet_dom {
                   12216:         &load_hosts_tab() if (!$loaded);
                   12217: 
                   12218:         my ($lonid) = @_;
                   12219:         return $internetdom{$lonid};
                   12220:     }
1.1107    raeburn  12221: 
                   12222:     sub is_LC_dns {
                   12223:         &load_hosts_tab() if (!$loaded);
                   12224: 
                   12225:         my ($hostname) = @_;
                   12226:         return exists($LC_dns_serv{$hostname});
                   12227:     }
                   12228: 
1.1       albertel 12229: }
                   12230: 
1.847     albertel 12231: { 
                   12232:     my %iphost;
1.856     albertel 12233:     my %name_to_ip;
                   12234:     my %lonid_to_ip;
1.869     albertel 12235: 
1.847     albertel 12236:     sub get_hosts_from_ip {
                   12237: 	my ($ip) = @_;
                   12238: 	my %iphosts = &get_iphost();
                   12239: 	if (ref($iphosts{$ip})) {
                   12240: 	    return @{$iphosts{$ip}};
                   12241: 	}
                   12242: 	return;
1.839     albertel 12243:     }
1.864     albertel 12244:     
                   12245:     sub reset_hosts_ip_info {
                   12246: 	undef(%iphost);
                   12247: 	undef(%name_to_ip);
                   12248: 	undef(%lonid_to_ip);
                   12249:     }
1.856     albertel 12250: 
                   12251:     sub get_host_ip {
                   12252: 	my ($lonid) = @_;
                   12253: 	if (exists($lonid_to_ip{$lonid})) {
                   12254: 	    return $lonid_to_ip{$lonid};
                   12255: 	}
                   12256: 	my $name=&hostname($lonid);
                   12257:    	my $ip = gethostbyname($name);
                   12258: 	return if (!$ip || length($ip) ne 4);
                   12259: 	$ip=inet_ntoa($ip);
                   12260: 	$name_to_ip{$name}   = $ip;
                   12261: 	$lonid_to_ip{$lonid} = $ip;
                   12262: 	return $ip;
                   12263:     }
1.847     albertel 12264:     
                   12265:     sub get_iphost {
1.869     albertel 12266: 	my ($ignore_cache) = @_;
1.894     albertel 12267: 
1.869     albertel 12268: 	if (!$ignore_cache) {
                   12269: 	    if (%iphost) {
                   12270: 		return %iphost;
                   12271: 	    }
                   12272: 	    my ($ip_info,$cached)=
                   12273: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12274: 	    if ($cached) {
                   12275: 		%iphost      = %{$ip_info->[0]};
                   12276: 		%name_to_ip  = %{$ip_info->[1]};
                   12277: 		%lonid_to_ip = %{$ip_info->[2]};
                   12278: 		return %iphost;
                   12279: 	    }
                   12280: 	}
1.894     albertel 12281: 
                   12282: 	# get yesterday's info for fallback
                   12283: 	my %old_name_to_ip;
                   12284: 	my ($ip_info,$cached)=
                   12285: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12286: 	if ($cached) {
                   12287: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12288: 	}
                   12289: 
1.888     albertel 12290: 	my %name_to_host = &all_names();
                   12291: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12292: 	    my $ip;
                   12293: 	    if (!exists($name_to_ip{$name})) {
                   12294: 		$ip = gethostbyname($name);
                   12295: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12296: 		    if (defined($old_name_to_ip{$name})) {
                   12297: 			$ip = $old_name_to_ip{$name};
                   12298: 			&logthis("Can't find $name defaulting to old $ip");
                   12299: 		    } else {
                   12300: 			&logthis("Name $name no IP found");
                   12301: 			next;
                   12302: 		    }
                   12303: 		} else {
                   12304: 		    $ip=inet_ntoa($ip);
1.847     albertel 12305: 		}
                   12306: 		$name_to_ip{$name} = $ip;
                   12307: 	    } else {
                   12308: 		$ip = $name_to_ip{$name};
1.653     albertel 12309: 	    }
1.888     albertel 12310: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12311: 		$lonid_to_ip{$id} = $ip;
                   12312: 	    }
                   12313: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12314: 	}
1.1219    raeburn  12315: 	&do_cache_new('iphost','iphost',
                   12316: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12317: 		      48*60*60);
1.869     albertel 12318: 
1.847     albertel 12319: 	return %iphost;
1.598     albertel 12320:     }
                   12321: 
1.992     raeburn  12322:     #
                   12323:     #  Given a DNS returns the loncapa host name for that DNS 
                   12324:     # 
                   12325:     sub host_from_dns {
                   12326:         my ($dns) = @_;
                   12327:         my @hosts;
                   12328:         my $ip;
                   12329: 
1.993     raeburn  12330:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12331:             $ip = $name_to_ip{$dns};
                   12332:         }
                   12333:         if (!$ip) {
                   12334:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12335:             if (length($ip) == 4) { 
                   12336: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12337:             }
                   12338:         }
                   12339:         if ($ip) {
                   12340: 	    @hosts = get_hosts_from_ip($ip);
                   12341: 	    return $hosts[0];
                   12342:         }
                   12343:         return undef;
1.986     foxr     12344:     }
1.992     raeburn  12345: 
1.1074    raeburn  12346:     sub get_internet_names {
                   12347:         my ($lonid) = @_;
                   12348:         return if ($lonid eq '');
                   12349:         my ($idnref,$cached)=
                   12350:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12351:         if ($cached) {
                   12352:             return $idnref;
                   12353:         }
                   12354:         my $ip = &get_host_ip($lonid);
                   12355:         my @hosts = &get_hosts_from_ip($ip);
                   12356:         my %iphost = &get_iphost();
                   12357:         my (@idns,%seen);
                   12358:         foreach my $id (@hosts) {
                   12359:             my $dom = &host_domain($id);
                   12360:             my $prim_id = &domain($dom,'primary');
                   12361:             my $prim_ip = &get_host_ip($prim_id);
                   12362:             next if ($seen{$prim_ip});
                   12363:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12364:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12365:                     my $intdom = &internet_dom($id);
                   12366:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12367:                         push(@idns,$intdom);
                   12368:                     }
                   12369:                 }
                   12370:             }
                   12371:             $seen{$prim_ip} = 1;
                   12372:         }
1.1219    raeburn  12373:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12374:     }
                   12375: 
1.986     foxr     12376: }
                   12377: 
1.1079    raeburn  12378: sub all_loncaparevs {
1.1249    raeburn  12379:     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  12380: }
                   12381: 
1.1227    raeburn  12382: # ---------------------------------------------------------- Read loncaparev table
                   12383: {
                   12384:     sub load_loncaparevs { 
                   12385:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12386:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12387:                 while (my $configline=<$config>) {
                   12388:                     chomp($configline);
                   12389:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12390:                     $loncaparevs{$hostid}=$loncaparev;
                   12391:                 }
                   12392:                 close($config);
                   12393:             }
                   12394:         }
                   12395:     }
                   12396: }
                   12397: 
                   12398: # ---------------------------------------------------------- Read serverhostID table
                   12399: {
                   12400:     sub load_serverhomeIDs {
                   12401:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12402:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12403:                 while (my $configline=<$config>) {
                   12404:                     chomp($configline);
                   12405:                     my ($name,$id)=split(/:/,$configline);
                   12406:                     $serverhomeIDs{$name}=$id;
                   12407:                 }
                   12408:                 close($config);
                   12409:             }
                   12410:         }
                   12411:     }
                   12412: }
                   12413: 
                   12414: 
1.862     albertel 12415: BEGIN {
                   12416: 
                   12417: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12418:     unless ($readit) {
                   12419: {
                   12420:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12421:     %perlvar = (%perlvar,%{$configvars});
                   12422: }
                   12423: 
                   12424: 
1.1       albertel 12425: # ------------------------------------------------------ Read spare server file
                   12426: {
1.448     albertel 12427:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12428: 
                   12429:     while (my $configline=<$config>) {
                   12430:        chomp($configline);
1.284     matthew  12431:        if ($configline) {
1.784     albertel 12432: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12433: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12434: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12435:        }
                   12436:     }
1.448     albertel 12437:     close($config);
1.1       albertel 12438: }
1.11      www      12439: # ------------------------------------------------------------ Read permissions
                   12440: {
1.448     albertel 12441:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12442: 
                   12443:     while (my $configline=<$config>) {
1.448     albertel 12444: 	chomp($configline);
                   12445: 	if ($configline) {
                   12446: 	    my ($role,$perm)=split(/ /,$configline);
                   12447: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12448: 	}
1.11      www      12449:     }
1.448     albertel 12450:     close($config);
1.11      www      12451: }
                   12452: 
                   12453: # -------------------------------------------- Read plain texts for permissions
                   12454: {
1.448     albertel 12455:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12456: 
                   12457:     while (my $configline=<$config>) {
1.448     albertel 12458: 	chomp($configline);
                   12459: 	if ($configline) {
1.742     raeburn  12460: 	    my ($short,@plain)=split(/:/,$configline);
                   12461:             %{$prp{$short}} = ();
                   12462: 	    if (@plain > 0) {
                   12463:                 $prp{$short}{'std'} = $plain[0];
                   12464:                 for (my $i=1; $i<@plain; $i++) {
                   12465:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12466:                 }
                   12467:             }
1.448     albertel 12468: 	}
1.135     www      12469:     }
1.448     albertel 12470:     close($config);
1.135     www      12471: }
                   12472: 
                   12473: # ---------------------------------------------------------- Read package table
                   12474: {
1.448     albertel 12475:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12476: 
                   12477:     while (my $configline=<$config>) {
1.483     albertel 12478: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12479: 	chomp($configline);
                   12480: 	my ($short,$plain)=split(/:/,$configline);
                   12481: 	my ($pack,$name)=split(/\&/,$short);
                   12482: 	if ($plain ne '') {
                   12483: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12484: 	    $packagetab{$short}=$plain; 
                   12485: 	}
1.11      www      12486:     }
1.448     albertel 12487:     close($config);
1.329     matthew  12488: }
                   12489: 
1.1073    raeburn  12490: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  12491: 
                   12492: &load_loncaparevs();
1.1073    raeburn  12493: 
1.1074    raeburn  12494: # ---------------------------------------------------------- Read serverhostID table
                   12495: 
1.1227    raeburn  12496: &load_serverhomeIDs();
                   12497: 
                   12498: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12499: {
                   12500:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12501:     if (-e $file) {
                   12502:         my $parser = HTML::LCParser->new($file);
                   12503:         while (my $token = $parser->get_token()) {
                   12504:             if ($token->[0] eq 'S') {
                   12505:                 my $item = $token->[1];
                   12506:                 my $name = $token->[2]{'name'};
                   12507:                 my $value = $token->[2]{'value'};
                   12508:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12509:                     my $release = $parser->get_text();
                   12510:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12511:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12512:                 }
                   12513:             }
                   12514:         }
                   12515:     }
1.1073    raeburn  12516: }
                   12517: 
1.1138    raeburn  12518: # ---------------------------------------------------------- Read managers table
                   12519: {
                   12520:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12521:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12522:             while (my $configline=<$config>) {
                   12523:                 chomp($configline);
                   12524:                 next if ($configline =~ /^\#/);
                   12525:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12526:                     $managerstab{$configline} = 1;
                   12527:                 }
                   12528:             }
                   12529:             close($config);
                   12530:         }
                   12531:     }
                   12532: }
                   12533: 
1.329     matthew  12534: # ------------- set up temporary directory
                   12535: {
1.1117    foxr     12536:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12537: 
1.11      www      12538: }
                   12539: 
1.794     albertel 12540: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12541: 				'compress_threshold'=> 20_000,
                   12542:  			        });
1.185     www      12543: 
1.281     www      12544: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12545: $dumpcount=0;
1.958     www      12546: $locknum=0;
1.22      www      12547: 
1.163     harris41 12548: &logtouch();
1.672     albertel 12549: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12550: $readit=1;
1.564     albertel 12551:     {
                   12552: 	use integer;
                   12553: 	my $test=(2**32)+1;
1.568     albertel 12554: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12555: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12556:     }
1.195     www      12557: }
1.1       albertel 12558: }
1.179     www      12559: 
1.1       albertel 12560: 1;
1.191     harris41 12561: __END__
                   12562: 
1.243     albertel 12563: =pod
                   12564: 
1.191     harris41 12565: =head1 NAME
                   12566: 
1.243     albertel 12567: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12568: 
                   12569: =head1 SYNOPSIS
                   12570: 
1.243     albertel 12571: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12572: 
                   12573:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12574: 
1.243     albertel 12575: Common parameters:
                   12576: 
                   12577: =over 4
                   12578: 
                   12579: =item *
                   12580: 
                   12581: $uname : an internal username (if $cname expecting a course Id specifically)
                   12582: 
                   12583: =item *
                   12584: 
                   12585: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12586: 
                   12587: =item *
                   12588: 
                   12589: $symb : a resource instance identifier
                   12590: 
                   12591: =item *
                   12592: 
                   12593: $namespace : the name of a .db file that contains the data needed or
                   12594: being set.
                   12595: 
                   12596: =back
                   12597: 
1.394     bowersj2 12598: =head1 OVERVIEW
1.191     harris41 12599: 
1.394     bowersj2 12600: lonnet provides subroutines which interact with the
                   12601: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12602: about classes, users, and resources.
1.243     albertel 12603: 
                   12604: For many of these objects you can also use this to store data about
                   12605: them or modify them in various ways.
1.191     harris41 12606: 
1.394     bowersj2 12607: =head2 Symbs
1.191     harris41 12608: 
1.394     bowersj2 12609: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12610: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12611: map, the resource number of the resource in the map, and the URL of
                   12612: the resource itself. The latter is somewhat redundant, but might help
                   12613: if maps change.
                   12614: 
                   12615: An example is
                   12616: 
                   12617:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12618: 
                   12619: The respective map entry is
                   12620: 
                   12621:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12622:   title="Problem 2">
                   12623:  </resource>
                   12624: 
                   12625: Symbs are used by the random number generator, as well as to store and
                   12626: restore data specific to a certain instance of for example a problem.
                   12627: 
                   12628: =head2 Storing And Retrieving Data
                   12629: 
                   12630: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12631: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12632: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12633: is is the non-critical message twin of cstore. These functions are for
                   12634: handlers to store a perl hash to a user's permanent data space in an
                   12635: easy manner, and to retrieve it again on another call. It is expected
                   12636: that a handler would use this once at the beginning to retrieve data,
                   12637: and then again once at the end to send only the new data back.
                   12638: 
                   12639: The data is stored in the user's data directory on the user's
                   12640: homeserver under the ID of the course.
                   12641: 
                   12642: The hash that is returned by restore will have all of the previous
                   12643: value for all of the elements of the hash.
                   12644: 
                   12645: Example:
                   12646: 
                   12647:  #creating a hash
                   12648:  my %hash;
                   12649:  $hash{'foo'}='bar';
                   12650: 
                   12651:  #storing it
                   12652:  &Apache::lonnet::cstore(\%hash);
                   12653: 
                   12654:  #changing a value
                   12655:  $hash{'foo'}='notbar';
                   12656: 
                   12657:  #adding a new value
                   12658:  $hash{'bar'}='foo';
                   12659:  &Apache::lonnet::cstore(\%hash);
                   12660: 
                   12661:  #retrieving the hash
                   12662:  my %history=&Apache::lonnet::restore();
                   12663: 
                   12664:  #print the hash
                   12665:  foreach my $key (sort(keys(%history))) {
                   12666:    print("\%history{$key} = $history{$key}");
                   12667:  }
                   12668: 
                   12669: Will print out:
1.191     harris41 12670: 
1.394     bowersj2 12671:  %history{1:foo} = bar
                   12672:  %history{1:keys} = foo:timestamp
                   12673:  %history{1:timestamp} = 990455579
                   12674:  %history{2:bar} = foo
                   12675:  %history{2:foo} = notbar
                   12676:  %history{2:keys} = foo:bar:timestamp
                   12677:  %history{2:timestamp} = 990455580
                   12678:  %history{bar} = foo
                   12679:  %history{foo} = notbar
                   12680:  %history{timestamp} = 990455580
                   12681:  %history{version} = 2
                   12682: 
                   12683: Note that the special hash entries C<keys>, C<version> and
                   12684: C<timestamp> were added to the hash. C<version> will be equal to the
                   12685: total number of versions of the data that have been stored. The
                   12686: C<timestamp> attribute will be the UNIX time the hash was
                   12687: stored. C<keys> is available in every historical section to list which
                   12688: keys were added or changed at a specific historical revision of a
                   12689: hash.
                   12690: 
                   12691: B<Warning>: do not store the hash that restore returns directly. This
                   12692: will cause a mess since it will restore the historical keys as if the
                   12693: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12694: 
1.394     bowersj2 12695: Calling convention:
1.191     harris41 12696: 
1.1225    raeburn  12697:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  12698:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 12699: 
1.394     bowersj2 12700: For more detailed information, see lonnet specific documentation.
1.191     harris41 12701: 
1.394     bowersj2 12702: =head1 RETURN MESSAGES
1.191     harris41 12703: 
1.394     bowersj2 12704: =over 4
1.191     harris41 12705: 
1.394     bowersj2 12706: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12707: 
1.394     bowersj2 12708: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12709: when the connection is brought back up
1.191     harris41 12710: 
1.394     bowersj2 12711: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12712: for later delivery
1.191     harris41 12713: 
1.967     bisitz   12714: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12715: 
1.394     bowersj2 12716: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12717: that was requested
1.191     harris41 12718: 
1.243     albertel 12719: =back
1.191     harris41 12720: 
1.243     albertel 12721: =head1 PUBLIC SUBROUTINES
1.191     harris41 12722: 
1.243     albertel 12723: =head2 Session Environment Functions
1.191     harris41 12724: 
1.243     albertel 12725: =over 4
1.191     harris41 12726: 
1.394     bowersj2 12727: =item * 
                   12728: X<appenv()>
1.949     raeburn  12729: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12730: the user envirnoment file, and will be restored for each access this
1.620     albertel 12731: user makes during this session, also modifies the %env for the current
1.949     raeburn  12732: process. Optional rolesarrayref - if defined contains a reference to an array
                   12733: of roles which are exempt from the restriction on modifying user.role entries 
                   12734: in the user's environment.db and in %env.    
1.191     harris41 12735: 
                   12736: =item *
1.394     bowersj2 12737: X<delenv()>
1.987     raeburn  12738: B<delenv($delthis,$regexp)>: removes all items from the session
                   12739: environment file that begin with $delthis. If the 
                   12740: optional second arg - $regexp - is true, $delthis is treated as a 
                   12741: regular expression, otherwise \Q$delthis\E is used. 
                   12742: The values are also deleted from the current processes %env.
1.191     harris41 12743: 
1.795     albertel 12744: =item * get_env_multiple($name) 
                   12745: 
                   12746: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12747: values may be defined and end up as an array ref.
                   12748: 
                   12749: returns an array of values
                   12750: 
1.243     albertel 12751: =back
                   12752: 
                   12753: =head2 User Information
1.191     harris41 12754: 
1.243     albertel 12755: =over 4
1.191     harris41 12756: 
                   12757: =item *
1.394     bowersj2 12758: X<queryauthenticate()>
                   12759: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12760: authentication scheme
                   12761: 
                   12762: =item *
1.394     bowersj2 12763: X<authenticate()>
1.1073    raeburn  12764: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12765: authenticate user from domain's lib servers (first use the current
                   12766: one). C<$upass> should be the users password.
1.1073    raeburn  12767: $checkdefauth is optional (value is 1 if a check should be made to
                   12768:    authenticate user using default authentication method, and allow
                   12769:    account creation if username does not have account in the domain).
                   12770: $clientcancheckhost is optional (value is 1 if checking whether the
                   12771:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12772: 
                   12773: =item *
1.394     bowersj2 12774: X<homeserver()>
                   12775: B<homeserver($uname,$udom)>: find the server which has
                   12776: the user's directory and files (there must be only one), this caches
                   12777: the answer, and also caches if there is a borken connection.
1.191     harris41 12778: 
                   12779: =item *
1.394     bowersj2 12780: X<idget()>
                   12781: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12782: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12783: username, and only 1 username per ID in a specific domain) (returns
                   12784: hash: id=>name,id=>name)
1.191     harris41 12785: 
                   12786: =item *
1.394     bowersj2 12787: X<idrget()>
                   12788: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12789: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12790: 
                   12791: =item *
1.394     bowersj2 12792: X<idput()>
                   12793: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12794: 
                   12795: =item *
1.394     bowersj2 12796: X<rolesinit()>
1.1169    droeschl 12797: B<rolesinit($udom,$username)>: get user privileges.
                   12798: returns user role, first access and timer interval hashes
1.243     albertel 12799: 
                   12800: =item *
1.1171    droeschl 12801: X<privileged()>
                   12802: B<privileged($username,$domain)>: returns a true if user has a
                   12803: privileged and active role (i.e. su or dc), false otherwise.
                   12804: 
                   12805: =item *
1.551     albertel 12806: X<getsection()>
                   12807: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12808: course $cname, return section name/number or '' for "not in course"
                   12809: and '-1' for "no section"
                   12810: 
                   12811: =item *
1.394     bowersj2 12812: X<userenvironment()>
                   12813: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12814: passed in @what from the requested user's environment, returns a hash
                   12815: 
1.858     raeburn  12816: =item * 
                   12817: X<userlog_query()>
1.859     albertel 12818: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12819: activity.log file. %filters defines filters applied when parsing the
                   12820: log file. These can be start or end timestamps, or the type of action
                   12821: - log to look for Login or Logout events, check for Checkin or
                   12822: Checkout, role for role selection. The response is in the form
                   12823: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12824: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12825: 
1.243     albertel 12826: =back
                   12827: 
                   12828: =head2 User Roles
                   12829: 
                   12830: =over 4
                   12831: 
                   12832: =item *
                   12833: 
1.810     raeburn  12834: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12835:  F: full access
                   12836:  U,I,K: authentication modes (cxx only)
                   12837:  '': forbidden
                   12838:  1: user needs to choose course
                   12839:  2: browse allowed
1.766     albertel 12840:  A: passphrase authentication needed
1.243     albertel 12841: 
                   12842: =item *
                   12843: 
1.1192    raeburn  12844: constructaccess($url,$setpriv) : check for access to construction space URL
                   12845: 
                   12846: See if the owner domain and name in the URL match those in the
                   12847: expected environment.  If so, return three element list
                   12848: ($ownername,$ownerdomain,$ownerhome).
                   12849: 
                   12850: Otherwise return the null string.
                   12851: 
                   12852: If second argument 'setpriv' is true, it assigns the privileges,
                   12853: and returns the same three element list, unless the owner has
                   12854: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12855: in which case the null string is returned.
                   12856: 
                   12857: =item *
                   12858: 
1.243     albertel 12859: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12860: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12861: and course level
                   12862: 
                   12863: =item *
                   12864: 
1.988     raeburn  12865: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12866: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12867: $type is Course (default) or Community.
1.988     raeburn  12868: If $forcedefault evaluates to true, text returned will be default 
                   12869: text for $type. Otherwise, if this is a course, the text returned 
                   12870: will be a custom name for the role (if defined in the course's 
                   12871: environment).  If no custom name is defined the default is returned.
                   12872:    
1.832     raeburn  12873: =item *
                   12874: 
1.1219    raeburn  12875: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12876: All arguments are optional. Returns a hash of a roles, either for
                   12877: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12878: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12879: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12880: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12881: For each key, value is set to colon-separated start and end times for
                   12882: the role.  If no username and domain are specified, will default to
1.934     raeburn  12883: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12884: of role statuses (active, future or previous), roles 
                   12885: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12886: to restrict the list of roles reported. If no array ref is 
                   12887: provided for types, will default to return only active roles.
1.834     albertel 12888: 
1.1195    raeburn  12889: =item *
                   12890: 
                   12891: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  12892: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   12893: 
                   12894: Additional optional arguments are: $type (if role checking is to be restricted 
                   12895: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  12896: available roles) or future (roles available in the future), and
                   12897: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  12898: have active Domain Coordinator role in course's domain or in additional
                   12899: domains (specified in 'Domains to check for privileged users' in course
                   12900: environment -- set via:  Course Settings -> Classlists and staff listing).
                   12901: 
                   12902: =item *
                   12903: 
                   12904: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   12905: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   12906: $possdomains and $possroles are optional array refs -- to domains to check and
                   12907: roles to check.  If $possdomains is not specified, a dump will be done of the
                   12908: users' roles.db to check for a dc or su role in any domain. This can be
                   12909: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   12910: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   12911: this then allows &privileged_by_domain() to be used, which caches the identity
                   12912: of privileged users, eliminating the need for repeated calls to &dump().
                   12913: 
                   12914: =item *
                   12915: 
                   12916: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   12917: where the outer hash keys are domains specified in the $possdomains array ref,
                   12918: next inner hash keys are privileged roles specified in the $roles array ref,
                   12919: and the innermost hash contains key = value pairs for username:domain = end:start
                   12920: for active or future "privileged" users with that role in that domain. To avoid
                   12921: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   12922: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  12923: 
1.243     albertel 12924: =back
                   12925: 
                   12926: =head2 User Modification
                   12927: 
                   12928: =over 4
                   12929: 
                   12930: =item *
                   12931: 
1.957     raeburn  12932: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12933: user for the level given by URL.  Optional start and end dates (leave empty
                   12934: string or zero for "no date")
1.191     harris41 12935: 
                   12936: =item *
                   12937: 
1.243     albertel 12938: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12939: change a users, password, possible return values are: ok,
                   12940: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12941: refused
1.191     harris41 12942: 
                   12943: =item *
                   12944: 
1.243     albertel 12945: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12946: 
                   12947: =item *
                   12948: 
1.1058    raeburn  12949: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12950:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12951: 
                   12952: will update user information (firstname,middlename,lastname,generation,
                   12953: permanentemail), and if forceid is true, student/employee ID also.
                   12954: A user's institutional affiliation(s) can also be updated.
                   12955: User information fields will not be overwritten with empty entries 
                   12956: unless the field is included in the $candelete array reference.
                   12957: This array is included when a single user is modified via "Manage Users",
                   12958: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12959: 
                   12960: =item *
                   12961: 
1.286     matthew  12962: modifystudent
                   12963: 
1.957     raeburn  12964: modify a student's enrollment and identification information.
1.1235    raeburn  12965: The course id is resolved based on the current user's environment.  
                   12966: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  12967: associated with a course.
                   12968: 
1.297     matthew  12969: This call is essentially a wrapper for lonnet::modifyuser and
                   12970: lonnet::modify_student_enrollment
1.286     matthew  12971: 
                   12972: Inputs: 
                   12973: 
                   12974: =over 4
                   12975: 
1.957     raeburn  12976: =item B<$udom> Student's loncapa domain
1.286     matthew  12977: 
1.957     raeburn  12978: =item B<$uname> Student's loncapa login name
1.286     matthew  12979: 
1.964     bisitz   12980: =item B<$uid> Student/Employee ID
1.286     matthew  12981: 
1.957     raeburn  12982: =item B<$umode> Student's authentication mode
1.286     matthew  12983: 
1.957     raeburn  12984: =item B<$upass> Student's password
1.286     matthew  12985: 
1.957     raeburn  12986: =item B<$first> Student's first name
1.286     matthew  12987: 
1.957     raeburn  12988: =item B<$middle> Student's middle name
1.286     matthew  12989: 
1.957     raeburn  12990: =item B<$last> Student's last name
1.286     matthew  12991: 
1.957     raeburn  12992: =item B<$gene> Student's generation
1.286     matthew  12993: 
1.957     raeburn  12994: =item B<$usec> Student's section in course
1.286     matthew  12995: 
                   12996: =item B<$end> Unix time of the roles expiration
                   12997: 
                   12998: =item B<$start> Unix time of the roles start date
                   12999: 
                   13000: =item B<$forceid> If defined, allow $uid to be changed
                   13001: 
                   13002: =item B<$desiredhome> server to use as home server for student
                   13003: 
1.957     raeburn  13004: =item B<$email> Student's permanent e-mail address
                   13005: 
                   13006: =item B<$type> Type of enrollment (auto or manual)
                   13007: 
1.963     raeburn  13008: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13009: 
                   13010: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13011: 
1.963     raeburn  13012: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13013: 
1.963     raeburn  13014: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13015: 
1.1216    raeburn  13016: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13017: 
                   13018: =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  13019: 
1.286     matthew  13020: =back
1.297     matthew  13021: 
                   13022: =item *
                   13023: 
                   13024: modify_student_enrollment
                   13025: 
1.1235    raeburn  13026: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13027: 'role.request.course' must be defined for this function to proceed.
                   13028: 
                   13029: Inputs:
                   13030: 
                   13031: =over 4
                   13032: 
1.1235    raeburn  13033: =item $udom, student's domain
1.297     matthew  13034: 
1.1235    raeburn  13035: =item $uname, student's name
1.297     matthew  13036: 
1.1235    raeburn  13037: =item $uid, student's user id
1.297     matthew  13038: 
1.1235    raeburn  13039: =item $first, student's first name
1.297     matthew  13040: 
                   13041: =item $middle
                   13042: 
                   13043: =item $last
                   13044: 
                   13045: =item $gene
                   13046: 
                   13047: =item $usec
                   13048: 
                   13049: =item $end
                   13050: 
                   13051: =item $start
                   13052: 
1.957     raeburn  13053: =item $type
                   13054: 
                   13055: =item $locktype
                   13056: 
                   13057: =item $cid
                   13058: 
                   13059: =item $selfenroll
                   13060: 
                   13061: =item $context
                   13062: 
1.1216    raeburn  13063: =item $credits, number of credits student will earn from this class
                   13064: 
1.297     matthew  13065: =back
                   13066: 
1.191     harris41 13067: 
                   13068: =item *
                   13069: 
1.243     albertel 13070: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13071: custom role; give a custom role to a user for the level given by URL.  Specify
                   13072: name and domain of role author, and role name
1.191     harris41 13073: 
                   13074: =item *
                   13075: 
1.243     albertel 13076: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13077: 
                   13078: =item *
                   13079: 
1.243     albertel 13080: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13081: 
                   13082: =back
                   13083: 
                   13084: =head2 Course Infomation
                   13085: 
                   13086: =over 4
1.191     harris41 13087: 
                   13088: =item *
                   13089: 
1.1118    foxr     13090: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13091: specified course id, including all environment settings for the
                   13092: course, the description of the course will be in the hash under the
                   13093: key 'description'
1.191     harris41 13094: 
1.1118    foxr     13095: $options is an optional parameter that if supplied is a hash reference that controls
                   13096: what how this function works.  It has the following key/values:
                   13097: 
                   13098: =over 4
                   13099: 
                   13100: =item freshen_cache
                   13101: 
                   13102: If defined, and the environment cache for the course is valid, it is 
                   13103: returned in the returned hash.
                   13104: 
                   13105: =item one_time
                   13106: 
                   13107: If defined, the last cache time is set to _now_
                   13108: 
                   13109: =item user
                   13110: 
                   13111: If defined, the supplied username is used instead of the current user.
                   13112: 
                   13113: 
                   13114: =back
                   13115: 
1.191     harris41 13116: =item *
                   13117: 
1.624     albertel 13118: resdata($name,$domain,$type,@which) : request for current parameter
                   13119: setting for a specific $type, where $type is either 'course' or 'user',
                   13120: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  13121: answers for 10 minutes.
1.243     albertel 13122: 
1.877     foxr     13123: =item *
                   13124: 
                   13125: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13126: data base, returning a hash that is keyed by the resource name and has
                   13127: values that are the resource value.  I believe that the timestamps and
                   13128: versions are also returned.
                   13129: 
1.1236    raeburn  13130: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13131: supplemental content area. This routine caches the number of files for 
                   13132: 10 minutes.
                   13133: 
1.243     albertel 13134: =back
                   13135: 
                   13136: =head2 Course Modification
                   13137: 
                   13138: =over 4
1.191     harris41 13139: 
                   13140: =item *
                   13141: 
1.243     albertel 13142: writecoursepref($courseid,%prefs) : write preferences (environment
                   13143: database) for a course
1.191     harris41 13144: 
                   13145: =item *
                   13146: 
1.1011    raeburn  13147: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13148: 
                   13149: =item *
                   13150: 
1.1038    raeburn  13151: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13152: 
1.1167    droeschl 13153: =item *
                   13154: 
                   13155: is_course($courseid), is_course($cdom, $cnum)
                   13156: 
                   13157: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13158: two component version $cdom, $cnum. It checks if the specified course exists.
                   13159: 
                   13160: Returns:
                   13161:     undef if the course doesn't exist, otherwise
                   13162:     in scalar context the combined courseid.
                   13163:     in list context the two components of the course identifier, domain and 
                   13164:     courseid.    
                   13165: 
1.243     albertel 13166: =back
                   13167: 
                   13168: =head2 Resource Subroutines
                   13169: 
                   13170: =over 4
1.191     harris41 13171: 
                   13172: =item *
                   13173: 
1.243     albertel 13174: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13175: 
                   13176: =item *
                   13177: 
1.243     albertel 13178: repcopy($filename) : subscribes to the requested file, and attempts to
                   13179: replicate from the owning library server, Might return
1.607     raeburn  13180: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13181: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13182: resource. Expects the local filesystem pathname
                   13183: (/home/httpd/html/res/....)
                   13184: 
                   13185: =back
                   13186: 
                   13187: =head2 Resource Information
                   13188: 
                   13189: =over 4
1.191     harris41 13190: 
                   13191: =item *
                   13192: 
1.1228    raeburn  13193: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13194: and returns the value of a variety of different possible values,
                   13195: $varname should be a request string, and the other parameters can be
                   13196: used to specify who and what one is asking about. Ordinarily, $cid 
                   13197: does not need to be specified, as it is retrived from 
                   13198: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13199: within lonuserstate::loadmap() when initializing a course, before
                   13200: $env{'request.course.id'} has been set, so it needs to be provided
                   13201: in that one case.
1.243     albertel 13202: 
                   13203: Possible values for $varname are environment.lastname (or other item
                   13204: from the envirnment hash), user.name (or someother aspect about the
                   13205: user), resource.0.maxtries (or some other part and parameter of a
                   13206: resource)
1.204     albertel 13207: 
                   13208: =item *
                   13209: 
1.243     albertel 13210: directcondval($number) : get current value of a condition; reads from a state
                   13211: string
1.204     albertel 13212: 
                   13213: =item *
                   13214: 
1.243     albertel 13215: condval($condidx) : value of condition index based on state
1.204     albertel 13216: 
                   13217: =item *
                   13218: 
1.243     albertel 13219: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13220: resource's metadata, $what should be either a specific key, or either
                   13221: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13222: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13223: 
                   13224: this function automatically caches all requests
1.191     harris41 13225: 
                   13226: =item *
                   13227: 
1.243     albertel 13228: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13229: network of library servers; returns file handle of where SQL and regex results
                   13230: will be stored for query
1.191     harris41 13231: 
                   13232: =item *
                   13233: 
1.243     albertel 13234: symbread($filename) : return symbolic list entry (filename argument optional);
                   13235: returns the data handle
1.191     harris41 13236: 
                   13237: =item *
                   13238: 
1.1190    raeburn  13239: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   13240: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13241: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  13242: on failure, user must be in a course, as it assumes the existence of
                   13243: the course initial hash, and uses $env('request.course.id'}.  The third
                   13244: arg is an optional reference to a scalar.  If this arg is passed in the 
                   13245: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13246: encrypted; otherwise it will be null.  
1.191     harris41 13247: 
                   13248: =item *
                   13249: 
1.243     albertel 13250: symbclean($symb) : removes versions numbers from a symb, returns the
                   13251: cleaned symb
1.191     harris41 13252: 
                   13253: =item *
                   13254: 
1.243     albertel 13255: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13256: course map, user must be in a course for it to work.
1.191     harris41 13257: 
                   13258: =item *
                   13259: 
1.243     albertel 13260: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13261: 
                   13262: =item *
                   13263: 
1.243     albertel 13264: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13265: a random seed, all arguments are optional, if they aren't sent it uses the
                   13266: environment to derive them. Note: if symb isn't sent and it can't get one
                   13267: from &symbread it will use the current time as its return value
1.191     harris41 13268: 
                   13269: =item *
                   13270: 
1.243     albertel 13271: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13272: unfakeable, receipt
1.191     harris41 13273: 
                   13274: =item *
                   13275: 
1.620     albertel 13276: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13277: 
                   13278: =item *
                   13279: 
1.243     albertel 13280: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13281: 
                   13282: =item *
                   13283: 
1.243     albertel 13284: 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 13285: 
                   13286: =item *
                   13287: 
1.243     albertel 13288: 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 13289: 
                   13290: =item *
                   13291: 
1.243     albertel 13292: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13293: 
                   13294: =item *
                   13295: 
1.243     albertel 13296: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13297: forcing spreadsheet to reevaluate the resource scores next time.
                   13298: 
1.1195    raeburn  13299: =item * 
                   13300: 
1.1196    raeburn  13301: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13302: when viewing in course context.
1.1195    raeburn  13303: 
1.1196    raeburn  13304:  input: six args -- filename (decluttered), course number, course domain,
                   13305:                     url, symb (if registered) and group (if this is a 
                   13306:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  13307: 
1.1196    raeburn  13308:  output: array of five scalars --
1.1195    raeburn  13309:          $cfile -- url for file editing if editable on current server
                   13310:          $home -- homeserver of resource (i.e., for author if published,
                   13311:                                           or course if uploaded.).
                   13312:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  13313:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   13314:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  13315: 
                   13316: =item *
                   13317: 
                   13318: is_course_upload($file,$cnum,$cdom)
                   13319: 
                   13320: Used in course context to determine if current file was uploaded to 
                   13321: the course (i.e., would be found in /userfiles/docs on the course's 
                   13322: homeserver.
                   13323: 
                   13324:   input: 3 args -- filename (decluttered), course number and course domain.
                   13325:   output: boolean -- 1 if file was uploaded.
                   13326: 
1.243     albertel 13327: =back
                   13328: 
                   13329: =head2 Storing/Retreiving Data
                   13330: 
                   13331: =over 4
1.191     harris41 13332: 
                   13333: =item *
                   13334: 
1.1269    raeburn  13335: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   13336: permanently for this url; hashref needs to be given and should be a \%hashname;
                   13337: the remaining args aren't required and if they aren't passed or are '' they will
                   13338: be derived from the env (with the exception of $laststore, which is an 
                   13339: optional arg used when a user's submission is stored in grading).
                   13340: $laststore is $version=$timestamp, where $version is the most recent version
                   13341: number retrieved for the corresponding $symb in the $namespace db file, and
                   13342: $timestamp is the timestamp for that transaction (UNIX time).
                   13343: $laststore is currently only passed when cstore() is called by 
                   13344: structuretags::finalize_storage().
1.191     harris41 13345: 
                   13346: =item *
                   13347: 
1.1269    raeburn  13348: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   13349: but uses critical subroutine
1.191     harris41 13350: 
                   13351: =item *
                   13352: 
1.243     albertel 13353: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13354: all args are optional
1.191     harris41 13355: 
                   13356: =item *
                   13357: 
1.717     albertel 13358: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13359: dumps the complete (or key matching regexp) namespace into a hash
                   13360: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13361: normally &store()ed into
                   13362: 
                   13363: $range should be either an integer '100' (give me the first 100
                   13364:                                            matching records)
                   13365:               or be  two integers sperated by a - with no spaces
                   13366:                  '30-50' (give me the 30th through the 50th matching
                   13367:                           records)
                   13368: 
                   13369: 
                   13370: =item *
                   13371: 
1.1269    raeburn  13372: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 13373: replaces a &store() version of data with a replacement set of data
                   13374: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  13375: reference. If $tolog is true, the transaction is logged in the courselog
                   13376: with an action=PUTSTORE.
1.717     albertel 13377: 
                   13378: =item *
                   13379: 
1.243     albertel 13380: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13381: works very similar to store/cstore, but all data is stored in a
                   13382: temporary location and can be reset using tmpreset, $storehash should
                   13383: be a hash reference, returns nothing on success
1.191     harris41 13384: 
                   13385: =item *
                   13386: 
1.243     albertel 13387: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13388: similar to restore, but all data is stored in a temporary location and
                   13389: can be reset using tmpreset. Returns a hash of values on success,
                   13390: error string otherwise.
1.191     harris41 13391: 
                   13392: =item *
                   13393: 
1.243     albertel 13394: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13395: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13396: 
                   13397: =item *
                   13398: 
1.243     albertel 13399: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13400: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13401: 
                   13402: =item *
                   13403: 
1.243     albertel 13404: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13405: namesp ($udom and $uname are optional)
1.191     harris41 13406: 
                   13407: =item *
                   13408: 
1.702     albertel 13409: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13410: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13411: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13412: 
1.702     albertel 13413: $range should be either an integer '100' (give me the first 100
                   13414:                                            matching records)
                   13415:               or be  two integers sperated by a - with no spaces
                   13416:                  '30-50' (give me the 30th through the 50th matching
                   13417:                           records)
1.449     matthew  13418: =item *
                   13419: 
                   13420: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13421: $store can be a scalar, an array reference, or if the amount to be 
                   13422: incremented is > 1, a hash reference.
                   13423: 
                   13424: ($udom and $uname are optional)
1.191     harris41 13425: 
                   13426: =item *
                   13427: 
1.243     albertel 13428: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13429: ($udom and $uname are optional)
1.191     harris41 13430: 
                   13431: =item *
                   13432: 
1.243     albertel 13433: cput($namespace,$storehash,$udom,$uname) : critical put
                   13434: ($udom and $uname are optional)
1.191     harris41 13435: 
                   13436: =item *
                   13437: 
1.748     albertel 13438: newput($namespace,$storehash,$udom,$uname) :
                   13439: 
                   13440: Attempts to store the items in the $storehash, but only if they don't
                   13441: currently exist, if this succeeds you can be certain that you have 
                   13442: successfully created a new key value pair in the $namespace db.
                   13443: 
                   13444: 
                   13445: Args:
                   13446:  $namespace: name of database to store values to
                   13447:  $storehash: hashref to store to the db
                   13448:  $udom: (optional) domain of user containing the db
                   13449:  $uname: (optional) name of user caontaining the db
                   13450: 
                   13451: Returns:
                   13452:  'ok' -> succeeded in storing all keys of $storehash
                   13453:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13454:                         least <key> already existed in the db (other
                   13455:                         requested keys may also already exist)
1.967     bisitz   13456:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13457:  'con_lost' -> unable to contact request server
                   13458:  'refused' -> action was not allowed by remote machine
                   13459: 
                   13460: 
                   13461: =item *
                   13462: 
1.243     albertel 13463: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13464: reference filled in from namesp (encrypts the return communication)
                   13465: ($udom and $uname are optional)
1.191     harris41 13466: 
                   13467: =item *
                   13468: 
1.243     albertel 13469: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13470: critical subroutine
                   13471: 
1.806     raeburn  13472: =item *
                   13473: 
1.860     raeburn  13474: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13475: array reference filled in from namespace found in domain level on either
                   13476: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13477: 
                   13478: =item *
                   13479: 
1.860     raeburn  13480: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13481: domain level either on specified domain server ($uhome) or primary domain 
                   13482: server ($udom and $uhome are optional)
1.806     raeburn  13483: 
1.943     raeburn  13484: =item * 
                   13485: 
1.1240    raeburn  13486: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   13487: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13488: the target domain.
                   13489: 
                   13490: May also include additional key => value pairs for the following groups:
                   13491: 
                   13492: =over
                   13493: 
                   13494: =item
                   13495: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13496: 
                   13497: =over
                   13498: 
                   13499: =item defaultquota, authorquota
                   13500: 
                   13501: =back
                   13502: 
                   13503: =item
                   13504: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13505: portfolio for users).
                   13506: 
                   13507: =over
                   13508: 
                   13509: =item
                   13510: aboutme, blog, webdav, portfolio
                   13511: 
                   13512: =back
                   13513: 
                   13514: =item
                   13515: requestcourses: ability to request courses, and how requests are processed.
                   13516: 
                   13517: =over
                   13518: 
                   13519: =item
1.1246    raeburn  13520: official, unofficial, community, textbook
1.1240    raeburn  13521: 
                   13522: =back
                   13523: 
                   13524: =item
                   13525: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13526: 
                   13527: =over
                   13528: 
                   13529: =item
1.1256    raeburn  13530: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  13531: 
                   13532: =back
                   13533: 
                   13534: =item
                   13535: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13536: for course's uploaded content.
                   13537: 
                   13538: =over
                   13539: 
                   13540: =item
1.1246    raeburn  13541: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
                   13542: communityquota, textbookquota
1.1240    raeburn  13543: 
                   13544: =back
                   13545: 
                   13546: =item
                   13547: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13548: on your servers.
                   13549: 
                   13550: =over
                   13551: 
                   13552: =item 
                   13553: remotesessions, hostedsessions
                   13554: 
                   13555: =back
                   13556: 
                   13557: =back
                   13558: 
                   13559: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13560: utility to create a configuration.db file on a domain's primary library server 
                   13561: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13562: -- corresponding values are authentication type (internal, krb4, krb5,
                   13563: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   13564: will be available. Values are retrieved from cache (if current), unless the
                   13565: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13566: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13567: 
                   13568: Typical usage:
1.943     raeburn  13569: 
1.1240    raeburn  13570: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13571: 
1.243     albertel 13572: =back
                   13573: 
                   13574: =head2 Network Status Functions
                   13575: 
                   13576: =over 4
1.191     harris41 13577: 
                   13578: =item *
                   13579: 
1.1137    raeburn  13580: dirlist() : return directory list based on URI (first arg).
                   13581: 
                   13582: Inputs: 1 required, 5 optional.
                   13583: 
                   13584: =over
                   13585: 
                   13586: =item 
                   13587: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13588: 
                   13589: =item
                   13590: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13591: 
                   13592: =item
                   13593: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13594: 
                   13595: =item
                   13596: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13597: 
                   13598: =item
                   13599: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13600: 
                   13601: =item 
                   13602: $alternateRoot - path to prepend in place of path from $uri.
                   13603: 
                   13604: =back
                   13605: 
                   13606: Returns: Array of up to two items.
                   13607: 
                   13608: =over
                   13609: 
                   13610: a reference to an array of files/subdirectories
                   13611: 
                   13612: =over
                   13613: 
                   13614: Each element in the array of files/subdirectories is a & separated list of
                   13615: item name and the result of running stat on the item.  If dirlist was requested
                   13616: for a file instead of a directory, the item name will be ''. For a directory 
                   13617: listing, if the item is a metadata file, the element will end &N&M 
                   13618: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13619: default copyright set (1).  
                   13620: 
                   13621: =back
                   13622: 
                   13623: a scalar containing error condition (if encountered).
                   13624: 
                   13625: =over
                   13626: 
                   13627: =item 
                   13628: no_host (no homeserver identified for $username:$domain).
                   13629: 
                   13630: =item 
                   13631: no_such_host (server contacted for listing not identified as valid host).
                   13632: 
                   13633: =item 
                   13634: con_lost (connection to remote server failed).
                   13635: 
                   13636: =item 
                   13637: refused (invalid $username:$domain received on lond side).
                   13638: 
                   13639: =item 
                   13640: no_such_dir (directory at specified path on lond side does not exist). 
                   13641: 
                   13642: =item 
                   13643: empty (directory at specified path on lond side is empty).
                   13644: 
                   13645: =over
                   13646: 
                   13647: This is currently not encountered because the &ls3, &ls2, 
                   13648: &ls (_handler) routines on the lond side do not filter out
                   13649: . and .. from a directory listing. 
                   13650: 
                   13651: =back
                   13652: 
                   13653: =back
                   13654: 
                   13655: =back
1.191     harris41 13656: 
                   13657: =item *
                   13658: 
1.243     albertel 13659: spareserver() : find server with least workload from spare.tab
                   13660: 
1.986     foxr     13661: 
                   13662: =item *
                   13663: 
                   13664: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13665: if there is no corresponding loncapa host.
                   13666: 
1.243     albertel 13667: =back
                   13668: 
1.986     foxr     13669: 
1.243     albertel 13670: =head2 Apache Request
                   13671: 
                   13672: =over 4
1.191     harris41 13673: 
                   13674: =item *
                   13675: 
1.243     albertel 13676: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13677: localhost, posts hash
                   13678: 
                   13679: =back
                   13680: 
                   13681: =head2 Data to String to Data
                   13682: 
                   13683: =over 4
1.191     harris41 13684: 
                   13685: =item *
                   13686: 
1.243     albertel 13687: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13688: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13689: 
                   13690: =item *
                   13691: 
1.243     albertel 13692: hashref2str($hashref) : convert a hashref into a string complete with
                   13693: escaping and '=' and '&' separators, supports elements that are
                   13694: arrayrefs and hashrefs
1.191     harris41 13695: 
                   13696: =item *
                   13697: 
1.243     albertel 13698: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13699: with escaping and '&' separators, supports elements that are arrayrefs
                   13700: and hashrefs
1.191     harris41 13701: 
                   13702: =item *
                   13703: 
1.243     albertel 13704: str2hash($string) : convert string to hash using unescaping and
                   13705: splitting on '=' and '&', supports elements that are arrayrefs and
                   13706: hashrefs
1.191     harris41 13707: 
                   13708: =item *
                   13709: 
1.243     albertel 13710: str2array($string) : convert string to hash using unescaping and
                   13711: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13712: 
                   13713: =back
                   13714: 
                   13715: =head2 Logging Routines
                   13716: 
                   13717: 
                   13718: These routines allow one to make log messages in the lonnet.log and
                   13719: lonnet.perm logfiles.
1.191     harris41 13720: 
1.1119    foxr     13721: =over 4
                   13722: 
1.191     harris41 13723: =item *
                   13724: 
1.243     albertel 13725: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13726: 
                   13727: =item *
                   13728: 
1.243     albertel 13729: logthis() : append message to the normal lonnet.log file, it gets
                   13730: preiodically rolled over and deleted.
1.191     harris41 13731: 
                   13732: =item *
                   13733: 
1.243     albertel 13734: logperm() : append a permanent message to lonnet.perm.log, this log
                   13735: file never gets deleted by any automated portion of the system, only
                   13736: messages of critical importance should go in here.
                   13737: 
1.1119    foxr     13738: 
1.243     albertel 13739: =back
                   13740: 
                   13741: =head2 General File Helper Routines
                   13742: 
                   13743: =over 4
1.191     harris41 13744: 
                   13745: =item *
                   13746: 
1.481     raeburn  13747: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13748: (a) files in /uploaded
                   13749:   (i) If a local copy of the file exists - 
                   13750:       compares modification date of local copy with last-modified date for 
                   13751:       definitive version stored on home server for course. If local copy is 
                   13752:       stale, requests a new version from the home server and stores it. 
                   13753:       If the original has been removed from the home server, then local copy 
                   13754:       is unlinked.
                   13755:   (ii) If local copy does not exist -
                   13756:       requests the file from the home server and stores it. 
                   13757:   
                   13758:   If $caller is 'uploadrep':  
                   13759:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13760:     for request for files originally uploaded via DOCS. 
                   13761:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13762:   
                   13763:   Otherwise:
                   13764:      This indicates a call from the content generation phase of the request.
                   13765:      -  returns the entire contents of the file or -1.
                   13766:      
                   13767: (b) files in /res
                   13768:    - returns the entire contents of a file or -1; 
                   13769:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13770: 
1.712     albertel 13771: 
                   13772: =item *
                   13773: 
                   13774: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13775:                   reference
                   13776: 
                   13777: returns either a stat() list of data about the file or an empty list
                   13778: if the file doesn't exist or couldn't find out about it (connection
                   13779: problems or user unknown)
                   13780: 
1.191     harris41 13781: =item *
                   13782: 
1.243     albertel 13783: filelocation($dir,$file) : returns file system location of a file
                   13784: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13785: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13786: and a file of ../bob will become /a/bob)
1.191     harris41 13787: 
                   13788: =item *
                   13789: 
                   13790: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13791: filelocation except for hrefs
                   13792: 
                   13793: =item *
                   13794: 
1.1261    raeburn  13795: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   13796: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 13797: 
1.243     albertel 13798: =back
                   13799: 
1.608     albertel 13800: =head2 Usererfile file routines (/uploaded*)
                   13801: 
                   13802: =over 4
                   13803: 
                   13804: =item *
                   13805: 
                   13806: userfileupload(): main rotine for putting a file in a user or course's
                   13807:                   filespace, arguments are,
                   13808: 
1.620     albertel 13809:  formname - required - this is the name of the element in $env where the
1.608     albertel 13810:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13811:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13812:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13813:  context - if coursedoc, store the file in the course of the active role
                   13814:              of the current user; 
                   13815:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13816:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13817:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13818:          if undefined, it will be placed in "unknown"
                   13819: 
                   13820:  (This routine calls clean_filename() to remove any dangerous
                   13821:  characters from the filename, and then calls finuserfileupload() to
                   13822:  complete the transaction)
                   13823: 
                   13824:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13825:  and /adm/notfound.html if unsuccessful
                   13826: 
                   13827: =item *
                   13828: 
                   13829: clean_filename(): routine for cleaing a filename up for storage in
                   13830:                  userfile space, argument is:
                   13831: 
                   13832:  filename - proposed filename
                   13833: 
                   13834: returns: the new clean filename
                   13835: 
                   13836: =item *
                   13837: 
1.1090    raeburn  13838: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13839: userspace, probably shouldn't be called directly
                   13840: 
                   13841:   docuname: username or courseid of destination for the file
                   13842:   docudom: domain of user/course of destination for the file
                   13843:   formname: same as for userfileupload()
1.1090    raeburn  13844:   fname: filename (including subdirectories) for the file
                   13845:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13846:   allfiles: reference to hash used to store objects found by parser
                   13847:   codebase: reference to hash used for codebases of java objects found by parser
                   13848:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13849:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13850:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13851:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13852:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13853:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13854:   mimetype: reference to scalar to accommodate mime type determined
                   13855:             from File::MMagic if $parser = parse.
1.608     albertel 13856: 
                   13857:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13858:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13859:  was 'overwrite').
                   13860:  
1.608     albertel 13861: 
                   13862: =item *
                   13863: 
                   13864: renameuserfile(): renames an existing userfile to a new name
                   13865: 
                   13866:   Args:
                   13867:    docuname: username or courseid of destination for the file
                   13868:    docudom: domain of user/course of destination for the file
                   13869:    old: current file name (including any subdirs under userfiles)
                   13870:    new: desired file name (including any subdirs under userfiles)
                   13871: 
                   13872: =item *
                   13873: 
                   13874: mkdiruserfile(): creates a directory is a userfiles dir
                   13875: 
                   13876:   Args:
                   13877:    docuname: username or courseid of destination for the file
                   13878:    docudom: domain of user/course of destination for the file
                   13879:    dir: dir to create (including any subdirs under userfiles)
                   13880: 
                   13881: =item *
                   13882: 
                   13883: removeuserfile(): removes a file that exists in userfiles
                   13884: 
                   13885:   Args:
                   13886:    docuname: username or courseid of destination for the file
                   13887:    docudom: domain of user/course of destination for the file
                   13888:    fname: filname to delete (including any subdirs under userfiles)
                   13889: 
                   13890: =item *
                   13891: 
                   13892: removeuploadedurl(): convience function for removeuserfile()
                   13893: 
                   13894:   Args:
                   13895:    url:  a full /uploaded/... url to delete
                   13896: 
1.747     albertel 13897: =item * 
                   13898: 
                   13899: get_portfile_permissions():
                   13900:   Args:
                   13901:     domain: domain of user or course contain the portfolio files
                   13902:     user: name of user or num of course contain the portfolio files
                   13903:   Returns:
                   13904:     hashref of a dump of the proper file_permissions.db
                   13905:    
                   13906: 
                   13907: =item * 
                   13908: 
                   13909: get_access_controls():
                   13910: 
                   13911: Args:
                   13912:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13913:   group: (optional) the group you want the files associated with
                   13914:   file: (optional) the file you want access info on
                   13915: 
                   13916: Returns:
1.749     raeburn  13917:     a hash (keys are file names) of hashes containing
                   13918:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13919:         values are XML containing access control settings (see below) 
1.747     albertel 13920: 
                   13921: Internal notes:
                   13922: 
1.749     raeburn  13923:  access controls are stored in file_permissions.db as key=value pairs.
                   13924:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13925:         where scope -> public,guest,course,group,domains or users.
                   13926:               end -> UNIX time for end of access (0 -> no end date)
                   13927:               start -> UNIX time for start of access
                   13928: 
                   13929:     value -> XML description of access control
                   13930:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13931:             <start></start>
                   13932:             <end></end>
                   13933: 
                   13934:             <password></password>  for scope type = guest
                   13935: 
                   13936:             <domain></domain>     for scope type = course or group
                   13937:             <number></number>
                   13938:             <roles id="">
                   13939:              <role></role>
                   13940:              <access></access>
                   13941:              <section></section>
                   13942:              <group></group>
                   13943:             </roles>
                   13944: 
                   13945:             <dom></dom>         for scope type = domains
                   13946: 
                   13947:             <users>             for scope type = users
                   13948:              <user>
                   13949:               <uname></uname>
                   13950:               <udom></udom>
                   13951:              </user>
                   13952:             </users>
                   13953:            </scope> 
                   13954:               
                   13955:  Access data is also aggregated for each file in an additional key=value pair:
                   13956:  key -> path to file/file_name\0accesscontrol 
                   13957:  value -> reference to hash
                   13958:           hash contains key = value pairs
                   13959:           where key = uniqueID:scope_end_start
                   13960:                 value = UNIX time record was last updated
                   13961: 
                   13962:           Used to improve speed of look-ups of access controls for each file.  
                   13963:  
                   13964:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13965: 
1.1198    raeburn  13966: =item *
                   13967: 
1.749     raeburn  13968: modify_access_controls():
                   13969: 
                   13970: Modifies access controls for a portfolio file
                   13971: Args
                   13972: 1. file name
                   13973: 2. reference to hash of required changes,
                   13974: 3. domain
                   13975: 4. username
                   13976:   where domain,username are the domain of the portfolio owner 
                   13977:   (either a user or a course) 
                   13978: 
                   13979: Returns:
                   13980: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13981: 2. result of deletions ('ok' or 'error', with error message).
                   13982: 3. reference to hash of any new or updated access controls.
                   13983: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13984:    key = integer (inbound ID)
1.1198    raeburn  13985:    value = uniqueID
                   13986: 
                   13987: =item *
                   13988: 
                   13989: get_timebased_id():
                   13990: 
                   13991: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   13992: course via the Course Editor (e.g., folders, composite pages, 
                   13993: group bulletin boards).
                   13994: 
                   13995: Args: (first three required; six others optional)
                   13996: 
                   13997: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13998:    docssequence, or name of group
                   13999: 
                   14000: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14001:    e.g., num, boardids
                   14002: 
                   14003: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   14004:    file will be named nohist_namespace.db
                   14005: 
                   14006: 4. cdom: domain of course; default is current course domain from %env
                   14007: 
                   14008: 5. cnum: course number; default is current course number from %env
                   14009: 
                   14010: 6. idtype: set to concat if an additional digit is to be appended to the 
                   14011:    unix timestamp to form the suffix, if the plain timestamp is already
                   14012:    in use.  Default is to not do this, but simply increment the unix 
                   14013:    timestamp by 1 until a unique key is obtained.
                   14014: 
                   14015: 7. who: holder of locking key; defaults to user:domain for user.
                   14016: 
                   14017: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   14018:    retrying); default is 3.
                   14019: 
                   14020: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   14021: 
                   14022: Returns:
                   14023: 
                   14024: 1. suffix obtained (numeric)
                   14025: 
                   14026: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14027: 
                   14028: 3. error: contains (localized) error message if an error occurred.
                   14029: 
1.747     albertel 14030: 
1.608     albertel 14031: =back
                   14032: 
1.243     albertel 14033: =head2 HTTP Helper Routines
                   14034: 
                   14035: =over 4
                   14036: 
1.191     harris41 14037: =item *
                   14038: 
                   14039: escape() : unpack non-word characters into CGI-compatible hex codes
                   14040: 
                   14041: =item *
                   14042: 
                   14043: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14044: 
1.243     albertel 14045: =back
                   14046: 
                   14047: =head1 PRIVATE SUBROUTINES
                   14048: 
                   14049: =head2 Underlying communication routines (Shouldn't call)
                   14050: 
                   14051: =over 4
                   14052: 
                   14053: =item *
                   14054: 
                   14055: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14056: 
                   14057: =item *
                   14058: 
                   14059: reply() : uses subreply to send a message to remote machine, logs all failures
                   14060: 
                   14061: =item *
                   14062: 
                   14063: critical() : passes a critical message to another server; if cannot
                   14064: get through then place message in connection buffer directory and
                   14065: returns con_delayed, if incapable of saving message, returns
                   14066: con_failed
                   14067: 
                   14068: =item *
                   14069: 
                   14070: reconlonc() : tries to reconnect lonc client processes.
                   14071: 
                   14072: =back
                   14073: 
                   14074: =head2 Resource Access Logging
                   14075: 
                   14076: =over 4
                   14077: 
                   14078: =item *
                   14079: 
                   14080: flushcourselogs() : flush (save) buffer logs and access logs
                   14081: 
                   14082: =item *
                   14083: 
                   14084: courselog($what) : save message for course in hash
                   14085: 
                   14086: =item *
                   14087: 
                   14088: courseacclog($what) : save message for course using &courselog().  Perform
                   14089: special processing for specific resource types (problems, exams, quizzes, etc).
                   14090: 
1.191     harris41 14091: =item *
                   14092: 
                   14093: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14094: as a PerlChildExitHandler
1.243     albertel 14095: 
                   14096: =back
                   14097: 
                   14098: =head2 Other
                   14099: 
                   14100: =over 4
                   14101: 
                   14102: =item *
                   14103: 
                   14104: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14105: 
                   14106: =back
                   14107: 
                   14108: =cut
1.877     foxr     14109: 

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