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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1276  ! raeburn     4: # $Id: lonnet.pm,v 1.1275 2014/12/16 19:57:56 musolffc 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.1272    droeschl 2726:       $request->content(join('&',map { 
                   2727:             my $name = escape($_);
                   2728:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   2729:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   2730:             : &escape($form{$_}) );    
                   2731:         } keys(%form)));
1.23      www      2732:     } else {
1.782     albertel 2733:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2734:     }
                   2735: 
1.15      www      2736:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2737:     my $response= $ua->request($request);
1.1182    foxr     2738:     my $content = $response->content;
                   2739: 
                   2740: 
1.944     foxr     2741:     if (wantarray) {
1.1173    foxr     2742: 	return ($content, $response);
1.944     foxr     2743:     } else {
1.1173    foxr     2744: 	return $content;
1.942     foxr     2745:     }
1.324     www      2746: }
                   2747: 
                   2748: sub externalssi {
                   2749:     my ($url)=@_;
                   2750:     my $ua=new LWP::UserAgent;
                   2751:     my $request=new HTTP::Request('GET',$url);
                   2752:     my $response=$ua->request($request);
1.954     raeburn  2753:     if (wantarray) {
                   2754:         return ($response->content, $response);
                   2755:     } else {
                   2756:         return $response->content;
                   2757:     }
1.15      www      2758: }
1.254     www      2759: 
1.492     albertel 2760: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2761: 
                   2762: sub allowuploaded {
                   2763:     my ($srcurl,$url)=@_;
                   2764:     $url=&clutter(&declutter($url));
                   2765:     my $dir=$url;
                   2766:     $dir=~s/\/[^\/]+$//;
                   2767:     my %httpref=();
                   2768:     my $httpurl=&hreflocation('',$url);
                   2769:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2770:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2771: }
1.477     raeburn  2772: 
1.1193    raeburn  2773: #
                   2774: # Determine if the current user should be able to edit a particular resource,
                   2775: # when viewing in course context.
                   2776: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2777: #     Functions.
                   2778: # (b) When displaying folder contents in course editor, used to determine if
                   2779: #     "Edit" link will be displayed alongside resource.
                   2780: #
1.1196    raeburn  2781: #  input: six args -- filename (decluttered), course number, course domain,
                   2782: #                   url, symb (if registered) and group (if this is a group
                   2783: #                   item -- e.g., bulletin board, group page etc.).
                   2784: #  output: array of five scalars -- 
1.1193    raeburn  2785: #          $cfile -- url for file editing if editable on current server
                   2786: #          $home -- homeserver of resource (i.e., for author if published,
                   2787: #                                           or course if uploaded.).
                   2788: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  2789: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   2790: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  2791: #
                   2792: 
                   2793: sub can_edit_resource {
1.1194    raeburn  2794:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2795:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2796: #
                   2797: # For aboutme pages user can only edit his/her own.
                   2798: #
1.1199    raeburn  2799:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  2800:         my ($sdom,$sname) = ($1,$2);
                   2801:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2802:             $home = $env{'user.home'};
                   2803:             $cfile = $resurl;
                   2804:             if ($env{'form.forceedit'}) {
                   2805:                 $forceview = 1;
                   2806:             } else {
                   2807:                 $forceedit = 1;
                   2808:             }
                   2809:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2810:         } else {
                   2811:             return;
                   2812:         }
                   2813:     }
                   2814: 
                   2815:     if ($env{'request.course.id'}) {
                   2816:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2817:         if ($group ne '') {
                   2818: # if this is a group homepage or group bulletin board, check group privs
                   2819:             my $allowed = 0;
1.1197    raeburn  2820:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2821:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  2822:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  2823:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2824:                     $allowed = 1;
                   2825:                 }
1.1197    raeburn  2826:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2827:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2828:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  2829:                     $allowed = 1;
                   2830:                 }
                   2831:             }
                   2832:             if ($allowed) {
                   2833:                 $home=&homeserver($cnum,$cdom);
                   2834:                 if ($env{'form.forceedit'}) {
                   2835:                     $forceview = 1;
                   2836:                 } else {
                   2837:                     $forceedit = 1;
                   2838:                 }
                   2839:                 $cfile = $resurl;
                   2840:             } else {
                   2841:                 return;
                   2842:             }
                   2843:         } else {
1.1208    raeburn  2844:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2845:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2846:                     return;
                   2847:                 }
                   2848:             } elsif (!$crsedit) {
1.1194    raeburn  2849: #
                   2850: # No edit allowed where CC has switched to student role.
                   2851: #
                   2852:                 return;
                   2853:             }
                   2854:         }
                   2855:     }
                   2856: 
1.1193    raeburn  2857:     if ($file ne '') {
                   2858:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  2859:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2860:                 $uploaded = 1;
                   2861:                 $incourse = 1;
1.1193    raeburn  2862:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2863:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  2864:                     if ($env{'form.forceedit'}) {
                   2865:                         $forceview = 1;
                   2866:                     } else {
                   2867:                         $forceedit = 1;
                   2868:                     }
1.1194    raeburn  2869:                 }
                   2870:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2871:                 $incourse = 1;
                   2872:                 if ($env{'form.forceedit'}) {
                   2873:                     $forceview = 1;
                   2874:                 } else {
                   2875:                     $forceedit = 1;
                   2876:                 }
                   2877:                 $cfile = $resurl;
                   2878:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   2879:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2880:                     $incourse = 1;
                   2881:                     if ($env{'form.forceedit'}) {
                   2882:                         $forceview = 1;
                   2883:                     } else {
                   2884:                         $forceedit = 1;
                   2885:                     }
                   2886:                     $cfile = $resurl;
1.1199    raeburn  2887:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  2888:                     $incourse = 1;
                   2889:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  2890:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  2891:                     $incourse = 1;
1.1199    raeburn  2892:                     if ($env{'form.forceedit'}) {
                   2893:                         $forceview = 1;
                   2894:                     } else {
                   2895:                         $forceedit = 1;
                   2896:                     }
                   2897:                     $cfile = $resurl;
1.1208    raeburn  2898:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2899:                     $incourse = 1;
                   2900:                     if ($env{'form.forceedit'}) {
                   2901:                         $forceview = 1;
                   2902:                     } else {
                   2903:                         $forceedit = 1;
                   2904:                     }
                   2905:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  2906:                 }
                   2907:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2908:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2909:                 if (&is_on_map($template)) { 
                   2910:                     $incourse = 1;
                   2911:                     $forceview = 1;
                   2912:                     $cfile = $template;
1.1193    raeburn  2913:                 }
1.1199    raeburn  2914:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2915:                     $incourse = 1;
                   2916:                     if ($env{'form.forceedit'}) {
                   2917:                         $forceview = 1;
                   2918:                     } else {
                   2919:                         $forceedit = 1;
                   2920:                     }
                   2921:                     $cfile = $resurl;
                   2922:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2923:                 $incourse = 1;
                   2924:                 $forceview = 1;
                   2925:                 if ($symb) {
                   2926:                     my ($map,$id,$res)=&decode_symb($symb);
                   2927:                     $env{'request.symb'} = $symb;
                   2928:                     $cfile = &clutter($res);
                   2929:                 } else {
                   2930:                     $cfile = $env{'form.suppurl'};
                   2931:                     $cfile =~ s{^http://}{};
                   2932:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2933:                 }
1.1234    raeburn  2934:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2935:                 if ($env{'form.forceedit'}) {
                   2936:                     $forceview = 1;
                   2937:                 } else {
                   2938:                     $forceedit = 1;
                   2939:                 }
                   2940:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  2941:             }
                   2942:         }
1.1194    raeburn  2943:         if ($uploaded || $incourse) {
                   2944:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  2945:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  2946:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2947:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2948:             # Check that the user has permission to edit this resource
                   2949:             my $setpriv = 1;
                   2950:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2951:             if (defined($cfudom)) {
                   2952:                 $home=&homeserver($cfuname,$cfudom);
                   2953:                 $cfile=$file;
                   2954:             }
                   2955:         }
1.1194    raeburn  2956:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   2957:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  2958:             my @ids=&current_machine_ids();
                   2959:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2960:                 $switchserver=1;
                   2961:             }
                   2962:         }
                   2963:     }
1.1194    raeburn  2964:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  2965: }
                   2966: 
                   2967: sub is_course_upload {
                   2968:     my ($file,$cnum,$cdom) = @_;
                   2969:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2970:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  2971:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2972:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  2973:         return 1;
                   2974:     }
                   2975:     return;
                   2976: }
                   2977: 
1.1194    raeburn  2978: sub in_course {
1.1195    raeburn  2979:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2980:     if ($hideprivileged) {
                   2981:         my $skipuser;
1.1219    raeburn  2982:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2983:         my @possdoms = ($cdom);  
                   2984:         if ($coursehash{'checkforpriv'}) { 
                   2985:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   2986:         }
                   2987:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  2988:             $skipuser = 1;
                   2989:             if ($coursehash{'nothideprivileged'}) {
                   2990:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2991:                     my $user;
                   2992:                     if ($item =~ /:/) {
                   2993:                         $user = $item;
                   2994:                     } else {
                   2995:                         $user = join(':',split(/[\@]/,$item));
                   2996:                     }
                   2997:                     if ($user eq $uname.':'.$udom) {
                   2998:                         undef($skipuser);
                   2999:                         last;
                   3000:                     }
                   3001:                 }
                   3002:             }
                   3003:             if ($skipuser) {
                   3004:                 return 0;
                   3005:             }
                   3006:         }
                   3007:     }
1.1194    raeburn  3008:     $type ||= 'any';
                   3009:     if (!defined($cdom) || !defined($cnum)) {
                   3010:         my $cid  = $env{'request.course.id'};
                   3011:         $cdom = $env{'course.'.$cid.'.domain'};
                   3012:         $cnum = $env{'course.'.$cid.'.num'};
                   3013:     }
                   3014:     my $typesref;
1.1195    raeburn  3015:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3016:         $typesref = ['active','previous','future'];
                   3017:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3018:         $typesref = [$type];
                   3019:     }
                   3020:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3021:                               $typesref,undef,[$cdom]);
                   3022:     my ($tmp) = keys(%roles);
                   3023:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3024:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3025:     if (@course_roles > 0) {
                   3026:         return 1;
                   3027:     }
                   3028:     return 0;
                   3029: }
                   3030: 
1.478     albertel 3031: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3032: # input: action, courseID, current domain, intended
1.637     raeburn  3033: #        path to file, source of file, instruction to parse file for objects,
                   3034: #        ref to hash for embedded objects,
                   3035: #        ref to hash for codebase of java objects.
1.1095    raeburn  3036: #        reference to scalar to accommodate mime type determined
                   3037: #          from File::MMagic if $parser = parse.
1.637     raeburn  3038: #
1.485     raeburn  3039: # output: url to file (if action was uploaddoc), 
                   3040: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3041: #
1.478     albertel 3042: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3043: # course.
1.477     raeburn  3044: #
1.478     albertel 3045: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3046: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3047: #          course's home server.
1.477     raeburn  3048: #
1.478     albertel 3049: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3050: #          be copied from $source (current location) to 
                   3051: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3052: #         and will then be copied to
                   3053: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3054: #         course's home server.
1.485     raeburn  3055: #
1.481     raeburn  3056: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3057: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3058: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3059: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3060: #         in course's home server.
1.637     raeburn  3061: #
1.477     raeburn  3062: 
                   3063: sub process_coursefile {
1.1095    raeburn  3064:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3065:         $mimetype)=@_;
1.477     raeburn  3066:     my $fetchresult;
1.638     albertel 3067:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3068:     if ($action eq 'propagate') {
1.638     albertel 3069:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3070: 			     $home);
1.481     raeburn  3071:     } else {
1.477     raeburn  3072:         my $fpath = '';
                   3073:         my $fname = $file;
1.478     albertel 3074:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3075:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3076:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3077:         if ($action eq 'copy') {
                   3078:             if ($source eq '') {
                   3079:                 $fetchresult = 'no source file';
                   3080:                 return $fetchresult;
                   3081:             } else {
                   3082:                 my $destination = $filepath.'/'.$fname;
                   3083:                 rename($source,$destination);
                   3084:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3085:                                  $home);
1.481     raeburn  3086:             }
                   3087:         } elsif ($action eq 'uploaddoc') {
                   3088:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3089:             print $fh $env{'form.'.$source};
1.481     raeburn  3090:             close($fh);
1.637     raeburn  3091:             if ($parser eq 'parse') {
1.1024    raeburn  3092:                 my $mm = new File::MMagic;
1.1095    raeburn  3093:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3094:                 if ($type eq 'text/html') {
1.1024    raeburn  3095:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3096:                     unless ($parse_result eq 'ok') {
                   3097:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3098:                     }
1.637     raeburn  3099:                 }
1.1095    raeburn  3100:                 if (ref($mimetype)) {
                   3101:                     $$mimetype = $type;
                   3102:                 } 
1.637     raeburn  3103:             }
1.477     raeburn  3104:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3105:                                  $home);
1.481     raeburn  3106:             if ($fetchresult eq 'ok') {
                   3107:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3108:             } else {
                   3109:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3110:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3111:                 return '/adm/notfound.html';
                   3112:             }
1.477     raeburn  3113:         }
                   3114:     }
1.485     raeburn  3115:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3116:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3117:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3118:     }
                   3119:     return $fetchresult;
                   3120: }
                   3121: 
1.637     raeburn  3122: sub build_filepath {
                   3123:     my ($fpath) = @_;
                   3124:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3125:     unless ($fpath eq '') {
                   3126:         my @parts=split('/',$fpath);
                   3127:         foreach my $part (@parts) {
                   3128:             $filepath.= '/'.$part;
                   3129:             if ((-e $filepath)!=1) {
                   3130:                 mkdir($filepath,0777);
                   3131:             }
                   3132:         }
                   3133:     }
                   3134:     return $filepath;
                   3135: }
                   3136: 
                   3137: sub store_edited_file {
1.638     albertel 3138:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3139:     my $file = $primary_url;
                   3140:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3141:     my $fpath = '';
                   3142:     my $fname = $file;
                   3143:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3144:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3145:     my $filepath = &build_filepath($fpath);
                   3146:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3147:     print $fh $content;
                   3148:     close($fh);
1.638     albertel 3149:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3150:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3151: 			  $home);
1.637     raeburn  3152:     if ($$fetchresult eq 'ok') {
                   3153:         return '/uploaded/'.$fpath.'/'.$fname;
                   3154:     } else {
1.638     albertel 3155:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3156: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3157:         return '/adm/notfound.html';
                   3158:     }
                   3159: }
                   3160: 
1.531     albertel 3161: sub clean_filename {
1.831     albertel 3162:     my ($fname,$args)=@_;
1.315     www      3163: # Replace Windows backslashes by forward slashes
1.257     www      3164:     $fname=~s/\\/\//g;
1.831     albertel 3165:     if (!$args->{'keep_path'}) {
                   3166:         # Get rid of everything but the actual filename
                   3167: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3168:     }
1.315     www      3169: # Replace spaces by underscores
                   3170:     $fname=~s/\s+/\_/g;
                   3171: # Replace all other weird characters by nothing
1.831     albertel 3172:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3173: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3174: # numbers
                   3175:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3176:     return $fname;
                   3177: }
1.1051    raeburn  3178: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3179: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3180: # image with the same aspect ratio as the original, but with dimensions which do 
                   3181: # not exceed $resizewidth and $resizeheight.
                   3182:  
1.984     neumanie 3183: sub resizeImage {
1.1051    raeburn  3184:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3185:     my $ima = Image::Magick->new;
                   3186:     my $resized;
                   3187:     if (-e $img_path) {
                   3188:         $ima->Read($img_path);
                   3189:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3190:             my $width = $ima->Get('width');
                   3191:             my $height = $ima->Get('height');
                   3192:             if ($width > $resizewidth) {
                   3193: 	        my $factor = $width/$resizewidth;
                   3194:                 my $newheight = $height/$factor;
                   3195:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3196:                 $resized = 1;
                   3197:             }
                   3198:         }
                   3199:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3200:             my $width = $ima->Get('width');
                   3201:             my $height = $ima->Get('height');
                   3202:             if ($height > $resizeheight) {
                   3203:                 my $factor = $height/$resizeheight;
                   3204:                 my $newwidth = $width/$factor;
                   3205:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3206:                 $resized = 1;
                   3207:             }
                   3208:         }
                   3209:         if ($resized) {
                   3210:             $ima->Write($img_path);
                   3211:         }
                   3212:     }
                   3213:     return;
1.977     amueller 3214: }
                   3215: 
1.608     albertel 3216: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3217: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3218: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3219: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3220: #                                    canceloverwrite, or ''. 
                   3221: #                   if 'coursedoc': upload to the current course
                   3222: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3223: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3224: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3225: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3226: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3227: #        $allfiles - reference to hash for embedded objects
                   3228: #        $codebase - reference to hash for codebase of java objects
                   3229: #        $desuname - username for permanent storage of uploaded file
                   3230: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3231: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3232: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3233: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3234: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3235: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3236: #                    from File::MMagic.
1.858     raeburn  3237: # 
1.686     albertel 3238: # output: url of file in userspace, or error: <message> 
                   3239: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3240: 
1.531     albertel 3241: sub userfileupload {
1.1090    raeburn  3242:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3243:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3244:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3245:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3246:     $fname=&clean_filename($fname);
1.1090    raeburn  3247:     # See if there is anything left
1.257     www      3248:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3249:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3250:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3251:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3252:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3253:         my $now = time;
1.1090    raeburn  3254:         my $filepath;
1.1095    raeburn  3255:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3256:              $filepath = 'tmp/helprequests/'.$now;
                   3257:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3258:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3259:                          '_'.$env{'user.domain'}.'/pending';
                   3260:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3261:             my ($docuname,$docudom);
                   3262:             if ($destudom) {
                   3263:                 $docudom = $destudom;
                   3264:             } else {
                   3265:                 $docudom = $env{'user.domain'};
                   3266:             }
                   3267:             if ($destuname) {
                   3268:                 $docuname = $destuname;
                   3269:             } else {
                   3270:                 $docuname = $env{'user.name'};
                   3271:             }
                   3272:             if (exists($env{'form.group'})) {
                   3273:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3274:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3275:             }
                   3276:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3277:             if ($context eq 'canceloverwrite') {
                   3278:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3279:                 if (-e  $tempfile) {
                   3280:                     my @info = stat($tempfile);
                   3281:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3282:                         unlink($tempfile);
                   3283:                     }
                   3284:                 }
                   3285:                 return;
1.523     raeburn  3286:             }
                   3287:         }
1.1090    raeburn  3288:         # Create the directory if not present
1.741     raeburn  3289:         my @parts=split(/\//,$filepath);
                   3290:         my $fullpath = $perlvar{'lonDaemons'};
                   3291:         for (my $i=0;$i<@parts;$i++) {
                   3292:             $fullpath .= '/'.$parts[$i];
                   3293:             if ((-e $fullpath)!=1) {
                   3294:                 mkdir($fullpath,0777);
                   3295:             }
                   3296:         }
                   3297:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3298:         print $fh $env{'form.'.$formname};
                   3299:         close($fh);
1.1090    raeburn  3300:         if ($context eq 'existingfile') {
                   3301:             my @info = stat($fullpath.'/'.$fname);
                   3302:             return ($fullpath.'/'.$fname,$info[9]);
                   3303:         } else {
                   3304:             return $fullpath.'/'.$fname;
                   3305:         }
1.523     raeburn  3306:     }
1.995     raeburn  3307:     if ($subdir eq 'scantron') {
                   3308:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3309:     } else {
1.995     raeburn  3310:         $fname="$subdir/$fname";
                   3311:     }
1.1090    raeburn  3312:     if ($context eq 'coursedoc') {
1.638     albertel 3313: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3314: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3315:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3316:             return &finishuserfileupload($docuname,$docudom,
                   3317: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3318: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3319:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3320:         } else {
1.1218    raeburn  3321:             if ($env{'form.folder'}) {
                   3322:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3323:             }
1.638     albertel 3324:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3325: 				       $fname,$formname,$parser,
1.1095    raeburn  3326: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3327:         }
1.719     banghart 3328:     } elsif (defined($destuname)) {
                   3329:         my $docuname=$destuname;
                   3330:         my $docudom=$destudom;
1.860     raeburn  3331: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3332: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3333:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3334:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3335:     } else {
1.638     albertel 3336:         my $docuname=$env{'user.name'};
                   3337:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3338:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3339:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3340:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3341:         }
1.860     raeburn  3342: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3343: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3344:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3345:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3346:     }
1.271     www      3347: }
                   3348: 
                   3349: sub finishuserfileupload {
1.860     raeburn  3350:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3351:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3352:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3353:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3354:   
1.860     raeburn  3355:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3356:     $file=$fname;
                   3357:     if ($fname=~m|/|) {
                   3358:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3359: 	$path.=$fnamepath.'/';
                   3360:     }
1.259     www      3361:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3362:     my $count;
                   3363:     for ($count=4;$count<=$#parts;$count++) {
                   3364:         $filepath.="/$parts[$count]";
                   3365:         if ((-e $filepath)!=1) {
                   3366: 	    mkdir($filepath,0777);
                   3367:         }
                   3368:     }
1.984     neumanie 3369: 
1.258     www      3370: # Save the file
                   3371:     {
1.701     albertel 3372: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3373: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3374: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3375: 	    return '/adm/notfound.html';
                   3376: 	}
1.1090    raeburn  3377:         if ($context eq 'overwrite') {
1.1117    foxr     3378:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3379:             my $target = $filepath.'/'.$file;
                   3380:             if (-e $source) {
                   3381:                 my @info = stat($source);
                   3382:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3383:                     unless (&File::Copy::move($source,$target)) {
                   3384:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3385:                         return "Moving from $source failed";
                   3386:                     }
                   3387:                 } else {
                   3388:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3389:                 }
                   3390:             } else {
                   3391:                 return "Temporary file: $source missing";
                   3392:             }
                   3393:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3394: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3395: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3396: 	    return '/adm/notfound.html';
                   3397: 	}
1.570     albertel 3398: 	close(FH);
1.1051    raeburn  3399:         if ($resizewidth && $resizeheight) {
                   3400:             my $mm = new File::MMagic;
                   3401:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3402:             if ($mime_type =~ m{^image/}) {
                   3403: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3404:             }  
1.977     amueller 3405: 	}
1.258     www      3406:     }
1.1152    raeburn  3407:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3408:         if (ref($mimetype)) {
                   3409:             if ($$mimetype eq '') {
                   3410:                 my $mm = new File::MMagic;
                   3411:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3412:                 $$mimetype = $type;
                   3413:             }
                   3414:         }
                   3415:     }
1.637     raeburn  3416:     if ($parser eq 'parse') {
1.1152    raeburn  3417:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3418:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3419:                                                        $allfiles,$codebase);
                   3420:             unless ($parse_result eq 'ok') {
                   3421:                 &logthis('Failed to parse '.$filepath.$file.
                   3422: 	   	         ' for embedded media: '.$parse_result); 
                   3423:             }
1.637     raeburn  3424:         }
                   3425:     }
1.860     raeburn  3426:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3427:         my $input = $filepath.'/'.$file;
                   3428:         my $output = $filepath.'/'.'tn-'.$file;
                   3429:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3430:         system("convert -sample $thumbsize $input $output");
                   3431:         if (-e $filepath.'/'.'tn-'.$file) {
                   3432:             $fetchthumb  = 1; 
                   3433:         }
                   3434:     }
1.858     raeburn  3435:  
1.259     www      3436: # Notify homeserver to grep it
                   3437: #
1.984     neumanie 3438:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3439:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3440:     if ($fetchresult eq 'ok') {
1.860     raeburn  3441:         if ($fetchthumb) {
                   3442:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3443:             if ($thumbresult ne 'ok') {
                   3444:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3445:                          $docuhome.': '.$thumbresult);
                   3446:             }
                   3447:         }
1.259     www      3448: #
1.258     www      3449: # Return the URL to it
1.494     albertel 3450:         return '/uploaded/'.$path.$file;
1.263     www      3451:     } else {
1.494     albertel 3452:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3453: 		 ': '.$fetchresult);
1.263     www      3454:         return '/adm/notfound.html';
1.858     raeburn  3455:     }
1.493     albertel 3456: }
                   3457: 
1.637     raeburn  3458: sub extract_embedded_items {
1.961     raeburn  3459:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3460:     my @state = ();
1.1164    raeburn  3461:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3462:     my %javafiles = (
                   3463:                       codebase => '',
                   3464:                       code => '',
                   3465:                       archive => ''
                   3466:                     );
                   3467:     my %mediafiles = (
                   3468:                       src => '',
                   3469:                       movie => '',
                   3470:                      );
1.648     raeburn  3471:     my $p;
                   3472:     if ($content) {
                   3473:         $p = HTML::LCParser->new($content);
                   3474:     } else {
1.961     raeburn  3475:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3476:     }
1.641     albertel 3477:     while (my $t=$p->get_token()) {
1.640     albertel 3478: 	if ($t->[0] eq 'S') {
                   3479: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3480: 	    push(@state, $tagname);
1.648     raeburn  3481:             if (lc($tagname) eq 'allow') {
                   3482:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3483:             }
1.640     albertel 3484: 	    if (lc($tagname) eq 'img') {
                   3485: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3486: 	    }
1.886     albertel 3487: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3488:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3489:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3490:                 }
1.886     albertel 3491: 	    }
1.645     raeburn  3492:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3493:                 my $src;
1.645     raeburn  3494:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3495:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3496:                 } else {
1.1164    raeburn  3497:                     if ($attr->{'src'} ne '') {
                   3498:                         $src = $attr->{'src'};
                   3499:                         &add_filetype($allfiles,$src,'src');
                   3500:                     }
                   3501:                 }
                   3502:                 my $text = $p->get_trimmed_text();
                   3503:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3504:                     my @swfargs = split(/,/,$1);
                   3505:                     foreach my $item (@swfargs) {
                   3506:                         $item =~ s/["']//g;
                   3507:                         $item =~ s/^\s+//;
                   3508:                         $item =~ s/\s+$//;
                   3509:                     }
                   3510:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3511:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3512:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3513:                         } else {
                   3514:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3515:                         }
                   3516:                     }
1.645     raeburn  3517:                 }
                   3518:             }
                   3519:             if (lc($tagname) eq 'link') {
                   3520:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3521:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3522:                 }
                   3523:             }
1.640     albertel 3524: 	    if (lc($tagname) eq 'object' ||
                   3525: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3526: 		foreach my $item (keys(%javafiles)) {
                   3527: 		    $javafiles{$item} = '';
                   3528: 		}
1.1164    raeburn  3529:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3530:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3531:                 }
1.640     albertel 3532: 	    }
                   3533: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3534: 		my $name = lc($attr->{'name'});
                   3535: 		foreach my $item (keys(%javafiles)) {
                   3536: 		    if ($name eq $item) {
                   3537: 			$javafiles{$item} = $attr->{'value'};
                   3538: 			last;
                   3539: 		    }
                   3540: 		}
1.1164    raeburn  3541:                 my $pathfrom;
1.640     albertel 3542: 		foreach my $item (keys(%mediafiles)) {
                   3543: 		    if ($name eq $item) {
1.1164    raeburn  3544:                         $pathfrom = $attr->{'value'};
                   3545:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3546: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3547: 			last;
                   3548: 		    }
                   3549: 		}
1.1164    raeburn  3550:                 if ($name eq 'flashvars') {
                   3551:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3552:                 }
                   3553:                 if ($pathfrom ne '') {
                   3554:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3555:                                          $pathfrom);
                   3556:                 }
1.640     albertel 3557: 	    }
                   3558: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3559: 		foreach my $item (keys(%javafiles)) {
                   3560: 		    if ($attr->{$item}) {
                   3561: 			$javafiles{$item} = $attr->{$item};
                   3562: 			last;
                   3563: 		    }
                   3564: 		}
                   3565: 		foreach my $item (keys(%mediafiles)) {
                   3566: 		    if ($attr->{$item}) {
                   3567: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3568: 			last;
                   3569: 		    }
                   3570: 		}
1.1164    raeburn  3571:                 if (lc($tagname) eq 'embed') {
                   3572:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3573:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3574:                                              $attr->{'src'});
                   3575:                     }
                   3576:                 }
1.640     albertel 3577: 	    }
1.1243    raeburn  3578:             if (lc($tagname) eq 'iframe') {
                   3579:                 my $src = $attr->{'src'} ;
                   3580:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3581:                     &add_filetype($allfiles,$src,'src');
                   3582:                 } elsif ($src =~ m{^/}) {
                   3583:                     if ($env{'request.course.id'}) {
                   3584:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3585:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3586:                         my $url = &hreflocation('',$fullpath);
                   3587:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3588:                             my $relpath = $1;
                   3589:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3590:                                 &add_filetype($allfiles,$1,'src');
                   3591:                             }
                   3592:                         }
                   3593:                     }
                   3594:                 }
                   3595:             }
1.1164    raeburn  3596:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3597:                 pop(@state);
1.1164    raeburn  3598:             }
1.640     albertel 3599: 	} elsif ($t->[0] eq 'E') {
                   3600: 	    my ($tagname) = ($t->[1]);
                   3601: 	    if ($javafiles{'codebase'} ne '') {
                   3602: 		$javafiles{'codebase'} .= '/';
                   3603: 	    }  
                   3604: 	    if (lc($tagname) eq 'applet' ||
                   3605: 		lc($tagname) eq 'object' ||
                   3606: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3607: 		) {
                   3608: 		foreach my $item (keys(%javafiles)) {
                   3609: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3610: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3611: 			&add_filetype($allfiles,$file,$item);
                   3612: 		    }
                   3613: 		}
                   3614: 	    } 
                   3615: 	    pop @state;
                   3616: 	}
                   3617:     }
1.1164    raeburn  3618:     foreach my $id (sort(keys(%flashvars))) {
                   3619:         if ($shockwave{$id} ne '') {
                   3620:             my @pairs = split(/\&/,$flashvars{$id});
                   3621:             foreach my $pair (@pairs) {
                   3622:                 my ($key,$value) = split(/\=/,$pair);
                   3623:                 if ($key eq 'thumb') {
                   3624:                     &add_filetype($allfiles,$value,$key);
                   3625:                 } elsif ($key eq 'content') {
                   3626:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3627:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3628:                     if ($ext ne '') {
                   3629:                         &add_filetype($allfiles,$path.$value,$ext);
                   3630:                     }
                   3631:                 }
                   3632:             }
                   3633:         }
                   3634:     }
1.637     raeburn  3635:     return 'ok';
                   3636: }
                   3637: 
1.639     albertel 3638: sub add_filetype {
                   3639:     my ($allfiles,$file,$type)=@_;
                   3640:     if (exists($allfiles->{$file})) {
                   3641: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3642: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3643: 	}
                   3644:     } else {
                   3645: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3646:     }
                   3647: }
                   3648: 
1.1164    raeburn  3649: sub embedded_dependency {
                   3650:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3651:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3652:         if (($identifier ne '') &&
                   3653:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3654:             ($pathfrom ne '')) {
                   3655:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3656:             foreach my $dep (@{$related->{$identifier}}) {
                   3657:                 &add_filetype($allfiles,$path.$dep,'object');
                   3658:             }
                   3659:         }
                   3660:     }
                   3661:     return;
                   3662: }
                   3663: 
1.493     albertel 3664: sub removeuploadedurl {
1.984     neumanie 3665:     my ($url)=@_;	
                   3666:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3667:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3668: }
                   3669: 
                   3670: sub removeuserfile {
                   3671:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3672:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3673:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3674:     if ($result eq 'ok') {	
1.798     raeburn  3675:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3676:             my $metafile = $fname.'.meta';
                   3677:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3678: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3679:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3680:             my $sqlresult = 
1.823     albertel 3681:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3682:                                         'portfolio_metadata',$group,
                   3683:                                         'delete');
1.798     raeburn  3684:         }
                   3685:     }
                   3686:     return $result;
1.257     www      3687: }
1.15      www      3688: 
1.530     albertel 3689: sub mkdiruserfile {
                   3690:     my ($docuname,$docudom,$dir)=@_;
                   3691:     my $home=&homeserver($docuname,$docudom);
                   3692:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3693: }
                   3694: 
1.531     albertel 3695: sub renameuserfile {
                   3696:     my ($docuname,$docudom,$old,$new)=@_;
                   3697:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3698:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3699:                         &escape("$old").':'.&escape("$new"),$home);
                   3700:     if ($result eq 'ok') {
                   3701:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3702:             my $oldmeta = $old.'.meta';
                   3703:             my $newmeta = $new.'.meta';
                   3704:             my $metaresult = 
                   3705:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3706: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3707:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3708:             my $sqlresult = 
1.823     albertel 3709:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3710:                                         'portfolio_metadata',$group,
                   3711:                                         'delete');
1.798     raeburn  3712:         }
                   3713:     }
                   3714:     return $result;
1.531     albertel 3715: }
                   3716: 
1.14      www      3717: # ------------------------------------------------------------------------- Log
                   3718: 
                   3719: sub log {
                   3720:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3721:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3722: }
                   3723: 
                   3724: # ------------------------------------------------------------------ Course Log
1.352     www      3725: #
                   3726: # This routine flushes several buffers of non-mission-critical nature
                   3727: #
1.157     www      3728: 
                   3729: sub flushcourselogs {
1.352     www      3730:     &logthis('Flushing log buffers');
                   3731: #
                   3732: # course logs
                   3733: # This is a log of all transactions in a course, which can be used
                   3734: # for data mining purposes
                   3735: #
                   3736: # It also collects the courseid database, which lists last transaction
                   3737: # times and course titles for all courseids
                   3738: #
                   3739:     my %courseidbuffer=();
1.921     raeburn  3740:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3741:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3742: 		          &escape($courselogs{$crsid}),
                   3743: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3744: 	    delete $courselogs{$crsid};
                   3745:         } else {
                   3746:             &logthis('Failed to flush log buffer for '.$crsid);
                   3747:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3748:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3749:                         " exceeded maximum size, deleting.</font>");
                   3750:                delete $courselogs{$crsid};
                   3751:             }
1.352     www      3752:         }
1.920     raeburn  3753:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3754:             'description' => $coursedescrbuf{$crsid},
                   3755:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3756:             'type'        => $coursetypebuf{$crsid},
                   3757:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3758:         };
1.191     harris41 3759:     }
1.352     www      3760: #
                   3761: # Write course id database (reverse lookup) to homeserver of courses 
                   3762: # Is used in pickcourse
                   3763: #
1.840     albertel 3764:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3765:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3766:                                     $courseidbuffer{$crs_home},
                   3767:                                     $crs_home,'timeonly');
1.352     www      3768:     }
                   3769: #
                   3770: # File accesses
                   3771: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3772: #
1.449     matthew  3773:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3774:         if ($entry =~ /___count$/) {
                   3775:             my ($dom,$name);
1.807     albertel 3776:             ($dom,$name,undef)=
1.811     albertel 3777: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3778:             if (! defined($dom) || $dom eq '' || 
                   3779:                 ! defined($name) || $name eq '') {
1.620     albertel 3780:                 my $cid = $env{'request.course.id'};
                   3781:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3782:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3783:             }
1.450     matthew  3784:             my $value = $accesshash{$entry};
                   3785:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3786:             my %temphash=($url => $value);
1.449     matthew  3787:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3788:             if ($result eq 'ok') {
                   3789:                 delete $accesshash{$entry};
                   3790:             }
                   3791:         } else {
1.811     albertel 3792:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3793:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3794:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3795:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3796:                 delete $accesshash{$entry};
                   3797:             }
1.185     www      3798:         }
1.191     harris41 3799:     }
1.352     www      3800: #
                   3801: # Roles
                   3802: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3803: #
1.800     albertel 3804:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3805:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3806: 	    split(/\:/,$entry);
                   3807:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3808:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3809:                 $rudom,$runame) eq 'ok') {
                   3810: 	    delete $userrolehash{$entry};
                   3811:         }
                   3812:     }
1.662     raeburn  3813: #
                   3814: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3815: #
                   3816:     my %domrolebuffer = ();
1.1000    raeburn  3817:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3818:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3819:         if ($domrolebuffer{$rudom}) {
                   3820:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3821:                       '='.&escape($domainrolehash{$entry});
                   3822:         } else {
                   3823:             $domrolebuffer{$rudom}.=&escape($entry).
                   3824:                       '='.&escape($domainrolehash{$entry});
                   3825:         }
                   3826:         delete $domainrolehash{$entry};
                   3827:     }
                   3828:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3829: 	my %servers = &get_servers($dom,'library');
                   3830: 	foreach my $tryserver (keys(%servers)) {
                   3831: 	    unless (&reply('domroleput:'.$dom.':'.
                   3832: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3833: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3834: 	    }
1.662     raeburn  3835:         }
                   3836:     }
1.186     www      3837:     $dumpcount++;
1.157     www      3838: }
                   3839: 
                   3840: sub courselog {
                   3841:     my $what=shift;
1.158     www      3842:     $what=time.':'.$what;
1.620     albertel 3843:     unless ($env{'request.course.id'}) { return ''; }
                   3844:     $coursedombuf{$env{'request.course.id'}}=
                   3845:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3846:     $coursenumbuf{$env{'request.course.id'}}=
                   3847:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3848:     $coursehombuf{$env{'request.course.id'}}=
                   3849:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3850:     $coursedescrbuf{$env{'request.course.id'}}=
                   3851:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3852:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3853:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3854:     $courseownerbuf{$env{'request.course.id'}}=
                   3855:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3856:     $coursetypebuf{$env{'request.course.id'}}=
                   3857:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3858:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3859: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3860:     } else {
1.620     albertel 3861: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3862:     }
1.620     albertel 3863:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3864: 	&flushcourselogs();
                   3865:     }
1.158     www      3866: }
                   3867: 
                   3868: sub courseacclog {
                   3869:     my $fnsymb=shift;
1.620     albertel 3870:     unless ($env{'request.course.id'}) { return ''; }
                   3871:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3872:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3873:         $what.=':POST';
1.583     matthew  3874:         # FIXME: Probably ought to escape things....
1.800     albertel 3875: 	foreach my $key (keys(%env)) {
                   3876:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3877:                 my $formitem = $1;
                   3878:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3879:                     $what.=':'.$formitem.'='.$env{$key};
                   3880:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3881:                     $what.=':'.$formitem.'='.$env{$key};
                   3882:                 }
1.158     www      3883:             }
1.191     harris41 3884:         }
1.583     matthew  3885:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3886:         # FIXME: We should not be depending on a form parameter that someone
                   3887:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3888:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3889:             $what.= ':POST';
                   3890:             # FIXME: Probably ought to escape things....
                   3891:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3892:                                  'crsdiscuss') {
1.620     albertel 3893:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3894:             }
                   3895:         }
1.158     www      3896:     }
                   3897:     &courselog($what);
1.149     www      3898: }
                   3899: 
1.185     www      3900: sub countacc {
                   3901:     my $url=&declutter(shift);
1.458     matthew  3902:     return if (! defined($url) || $url eq '');
1.620     albertel 3903:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3904: #
                   3905: # Mark that this url was used in this course
                   3906: #
1.620     albertel 3907:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3908: #
                   3909: # Increase the access count for this resource in this child process
                   3910: #
1.281     www      3911:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3912:     $accesshash{$key}++;
1.185     www      3913: }
1.349     www      3914: 
1.361     www      3915: sub linklog {
                   3916:     my ($from,$to)=@_;
                   3917:     $from=&declutter($from);
                   3918:     $to=&declutter($to);
                   3919:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3920:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3921: }
1.1160    www      3922: 
                   3923: sub statslog {
                   3924:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3925:     if ($users<2) { return; }
                   3926:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3927:             'course'       => $env{'request.course.id'},
                   3928:             'sections'     => '"all"',
                   3929:             'num_students' => $users,
                   3930:             'part'         => $part,
                   3931:             'symb'         => $symb,
                   3932:             'mean_tries'   => $av_attempts,
                   3933:             'deg_of_diff'  => $degdiff});
                   3934:     foreach my $key (keys(%dynstore)) {
                   3935:         $accesshash{$key}=$dynstore{$key};
                   3936:     }
                   3937: }
1.361     www      3938:   
1.349     www      3939: sub userrolelog {
                   3940:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3941:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3942:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3943:        $userrolehash
                   3944:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3945:                     =$tend.':'.$tstart;
1.662     raeburn  3946:     }
1.1169    droeschl 3947:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3948:        $userrolehash
                   3949:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3950:                     =$tend.':'.$tstart;
                   3951:     }
1.1169    droeschl 3952:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3953:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3954:        $domainrolehash
                   3955:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3956:                     = $tend.':'.$tstart;
                   3957:     }
1.351     www      3958: }
                   3959: 
1.957     raeburn  3960: sub courserolelog {
                   3961:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  3962:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3963:         my $cdom = $1;
                   3964:         my $cnum = $2;
                   3965:         my $sec = $3;
                   3966:         my $namespace = 'rolelog';
                   3967:         my %storehash = (
                   3968:                            role    => $trole,
                   3969:                            start   => $tstart,
                   3970:                            end     => $tend,
                   3971:                            selfenroll => $selfenroll,
                   3972:                            context    => $context,
                   3973:                         );
                   3974:         if ($trole eq 'gr') {
                   3975:             $namespace = 'groupslog';
                   3976:             $storehash{'group'} = $sec;
                   3977:         } else {
                   3978:             $storehash{'section'} = $sec;
                   3979:         }
1.1188    raeburn  3980:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3981:                    $domain,$cnum,$cdom);
1.1184    raeburn  3982:         if (($trole ne 'st') || ($sec ne '')) {
                   3983:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3984:         }
                   3985:     }
                   3986:     return;
                   3987: }
                   3988: 
1.1184    raeburn  3989: sub domainrolelog {
                   3990:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3991:     if ($area =~ m{^/($match_domain)/$}) {
                   3992:         my $cdom = $1;
                   3993:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3994:         my $namespace = 'rolelog';
                   3995:         my %storehash = (
                   3996:                            role    => $trole,
                   3997:                            start   => $tstart,
                   3998:                            end     => $tend,
                   3999:                            context => $context,
                   4000:                         );
1.1188    raeburn  4001:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4002:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4003:     }
                   4004:     return;
                   4005: 
                   4006: }
                   4007: 
                   4008: sub coauthorrolelog {
                   4009:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4010:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4011:         my $audom = $1;
                   4012:         my $auname = $2;
                   4013:         my $namespace = 'rolelog';
                   4014:         my %storehash = (
                   4015:                            role    => $trole,
                   4016:                            start   => $tstart,
                   4017:                            end     => $tend,
                   4018:                            context => $context,
                   4019:                         );
1.1188    raeburn  4020:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4021:                    $domain,$auname,$audom);
1.1184    raeburn  4022:     }
                   4023:     return;
                   4024: }
                   4025: 
1.351     www      4026: sub get_course_adv_roles {
1.948     raeburn  4027:     my ($cid,$codes) = @_;
1.620     albertel 4028:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4029:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4030:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4031:     my %nothide=();
1.800     albertel 4032:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4033:         if ($user !~ /:/) {
                   4034: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4035:         } else {
                   4036:             $nothide{$user}=1;
                   4037:         }
1.470     www      4038:     }
1.1219    raeburn  4039:     my @possdoms = ($coursehash{'domain'});
                   4040:     if ($coursehash{'checkforpriv'}) {
                   4041:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4042:     }
1.351     www      4043:     my %returnhash=();
                   4044:     my %dumphash=
                   4045:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4046:     my $now=time;
1.997     raeburn  4047:     my %privileged;
1.1000    raeburn  4048:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4049: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4050:         if (($tstart) && ($tstart<0)) { next; }
                   4051:         if (($tend) && ($tend<$now)) { next; }
                   4052:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4053:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4054: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4055:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4056:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4057: 	if ($role eq 'cr') { next; }
1.948     raeburn  4058:         if ($codes) {
                   4059:             if ($section) { $role .= ':'.$section; }
                   4060:             if ($returnhash{$role}) {
                   4061:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4062:             } else {
                   4063:                 $returnhash{$role}=$username.':'.$domain;
                   4064:             }
1.351     www      4065:         } else {
1.988     raeburn  4066:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4067:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4068:             if ($returnhash{$key}) {
                   4069: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4070:             } else {
                   4071:                 $returnhash{$key}=$username.':'.$domain;
                   4072:             }
1.351     www      4073:         }
1.948     raeburn  4074:     }
1.400     www      4075:     return %returnhash;
                   4076: }
                   4077: 
                   4078: sub get_my_roles {
1.937     raeburn  4079:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4080:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4081:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4082:     my (%dumphash,%nothide);
1.1086    raeburn  4083:     if ($context eq 'userroles') {
1.1166    raeburn  4084:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4085:     } else {
1.1219    raeburn  4086:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4087:         if ($hidepriv) {
                   4088:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4089:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4090:                 if ($user !~ /:/) {
                   4091:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4092:                 } else {
                   4093:                     $nothide{$user} = 1;
                   4094:                 }
                   4095:             }
                   4096:         }
1.858     raeburn  4097:     }
1.400     www      4098:     my %returnhash=();
                   4099:     my $now=time;
1.999     raeburn  4100:     my %privileged;
1.800     albertel 4101:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4102:         my ($role,$tend,$tstart);
                   4103:         if ($context eq 'userroles') {
1.1149    raeburn  4104:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4105: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4106:         } else {
                   4107:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4108:         }
1.400     www      4109:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4110:         my $status = 'active';
1.939     raeburn  4111:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4112:             $status = 'previous';
                   4113:         } 
                   4114:         if (($tstart) && ($now<$tstart)) {
                   4115:             $status = 'future';
                   4116:         }
                   4117:         if (ref($types) eq 'ARRAY') {
                   4118:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4119:                 next;
                   4120:             } 
                   4121:         } else {
                   4122:             if ($status ne 'active') {
                   4123:                 next;
                   4124:             }
                   4125:         }
1.867     raeburn  4126:         my ($rolecode,$username,$domain,$section,$area);
                   4127:         if ($context eq 'userroles') {
1.1186    raeburn  4128:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4129:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4130:         } else {
                   4131:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4132:         }
1.832     raeburn  4133:         if (ref($roledoms) eq 'ARRAY') {
                   4134:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4135:                 next;
                   4136:             }
                   4137:         }
                   4138:         if (ref($roles) eq 'ARRAY') {
                   4139:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4140:                 if ($role =~ /^cr\//) {
                   4141:                     if (!grep(/^cr$/,@{$roles})) {
                   4142:                         next;
                   4143:                     }
1.1104    raeburn  4144:                 } elsif ($role =~ /^gr\//) {
                   4145:                     if (!grep(/^gr$/,@{$roles})) {
                   4146:                         next;
                   4147:                     }
1.922     raeburn  4148:                 } else {
                   4149:                     next;
                   4150:                 }
1.832     raeburn  4151:             }
1.867     raeburn  4152:         }
1.937     raeburn  4153:         if ($hidepriv) {
1.1219    raeburn  4154:             my @privroles = ('dc','su');
1.999     raeburn  4155:             if ($context eq 'userroles') {
1.1219    raeburn  4156:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4157:             } else {
1.1219    raeburn  4158:                 my $possdoms = [$domain];
                   4159:                 if (ref($roledoms) eq 'ARRAY') {
                   4160:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4161:                 }
1.1219    raeburn  4162:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4163:                     if (!$nothide{$username.':'.$domain}) {
                   4164:                         next;
                   4165:                     }
                   4166:                 }
1.937     raeburn  4167:             }
                   4168:         }
1.933     raeburn  4169:         if ($withsec) {
                   4170:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4171:                 $tstart.':'.$tend;
                   4172:         } else {
                   4173:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4174:         }
1.832     raeburn  4175:     }
1.373     www      4176:     return %returnhash;
1.399     www      4177: }
                   4178: 
                   4179: # ----------------------------------------------------- Frontpage Announcements
                   4180: #
                   4181: #
                   4182: 
                   4183: sub postannounce {
                   4184:     my ($server,$text)=@_;
1.844     albertel 4185:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4186:     unless ($text=~/\w/) { $text=''; }
                   4187:     return &reply('setannounce:'.&escape($text),$server);
                   4188: }
                   4189: 
                   4190: sub getannounce {
1.448     albertel 4191: 
                   4192:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4193: 	my $announcement='';
1.800     albertel 4194: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4195: 	close($fh);
1.399     www      4196: 	if ($announcement=~/\w/) { 
                   4197: 	    return 
                   4198:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4199:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4200: 	} else {
                   4201: 	    return '';
                   4202: 	}
                   4203:     } else {
                   4204: 	return '';
                   4205:     }
1.351     www      4206: }
1.353     www      4207: 
                   4208: # ---------------------------------------------------------- Course ID routines
                   4209: # Deal with domain's nohist_courseid.db files
                   4210: #
                   4211: 
                   4212: sub courseidput {
1.921     raeburn  4213:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4214:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4215:     my $outcome;
                   4216:     if ($caller eq 'timeonly') {
                   4217:         my $cids = '';
                   4218:         foreach my $item (keys(%$storehash)) {
                   4219:             $cids.=&escape($item).'&';
                   4220:         }
                   4221:         $cids=~s/\&$//;
                   4222:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4223:                           $coursehome);       
                   4224:     } else {
                   4225:         my $items = '';
                   4226:         foreach my $item (keys(%$storehash)) {
                   4227:             $items.= &escape($item).'='.
                   4228:                      &freeze_escape($$storehash{$item}).'&';
                   4229:         }
                   4230:         $items=~s/\&$//;
                   4231:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4232:                           $coursehome);
1.918     raeburn  4233:     }
                   4234:     if ($outcome eq 'unknown_cmd') {
                   4235:         my $what;
                   4236:         foreach my $cid (keys(%$storehash)) {
                   4237:             $what .= &escape($cid).'=';
1.921     raeburn  4238:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4239:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4240:             }
                   4241:             $what =~ s/\:$/&/;
                   4242:         }
                   4243:         $what =~ s/\&$//;  
                   4244:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4245:     } else {
                   4246:         return $outcome;
                   4247:     }
1.353     www      4248: }
                   4249: 
                   4250: sub courseiddump {
1.921     raeburn  4251:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4252:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4253:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4254:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
                   4255:         $hasuniquecode)=@_;
1.918     raeburn  4256:     my $as_hash = 1;
                   4257:     my %returnhash;
                   4258:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4259:     my %libserv = &all_library();
                   4260:     foreach my $tryserver (keys(%libserv)) {
                   4261:         if ( (  $hostidflag == 1 
                   4262: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4263: 	     || (!defined($hostidflag)) ) {
                   4264: 
1.918     raeburn  4265: 	    if (($domfilter eq '') ||
                   4266: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4267:                 my $rep;
                   4268:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4269:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4270:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4271:                                 &escape($descfilter), &escape($instcodefilter), 
                   4272:                                 &escape($ownerfilter), &escape($coursefilter),
                   4273:                                 &escape($typefilter), &escape($regexp_ok), 
                   4274:                                 $as_hash, &escape($selfenrollonly), 
                   4275:                                 &escape($catfilter), $showhidden, $caller, 
                   4276:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4277:                                 &escape($createdbefore), &escape($createdafter), 
1.1247    raeburn  4278:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1180    droeschl 4279:                 } else {
                   4280:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4281:                              $sincefilter.':'.&escape($descfilter).':'.
                   4282:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4283:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4284:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4285:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4286:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4287:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4288:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1247    raeburn  4289:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1180    droeschl 4290:                              $tryserver);
                   4291:                 }
                   4292:                      
1.918     raeburn  4293:                 my @pairs=split(/\&/,$rep);
                   4294:                 foreach my $item (@pairs) {
                   4295:                     my ($key,$value)=split(/\=/,$item,2);
                   4296:                     $key = &unescape($key);
                   4297:                     next if ($key =~ /^error: 2 /);
                   4298:                     my $result = &thaw_unescape($value);
                   4299:                     if (ref($result) eq 'HASH') {
                   4300:                         $returnhash{$key}=$result;
                   4301:                     } else {
1.921     raeburn  4302:                         my @responses = split(/:/,$value);
                   4303:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4304:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4305:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4306:                         }
1.1008    raeburn  4307:                     }
1.353     www      4308:                 }
                   4309:             }
                   4310:         }
                   4311:     }
                   4312:     return %returnhash;
                   4313: }
                   4314: 
1.1055    raeburn  4315: sub courselastaccess {
                   4316:     my ($cdom,$cnum,$hostidref) = @_;
                   4317:     my %returnhash;
                   4318:     if ($cdom && $cnum) {
                   4319:         my $chome = &homeserver($cnum,$cdom);
                   4320:         if ($chome ne 'no_host') {
                   4321:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4322:             &extract_lastaccess(\%returnhash,$rep);
                   4323:         }
                   4324:     } else {
                   4325:         if (!$cdom) { $cdom=''; }
                   4326:         my %libserv = &all_library();
                   4327:         foreach my $tryserver (keys(%libserv)) {
                   4328:             if (ref($hostidref) eq 'ARRAY') {
                   4329:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4330:             } 
                   4331:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4332:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4333:                 &extract_lastaccess(\%returnhash,$rep);
                   4334:             }
                   4335:         }
                   4336:     }
                   4337:     return %returnhash;
                   4338: }
                   4339: 
                   4340: sub extract_lastaccess {
                   4341:     my ($returnhash,$rep) = @_;
                   4342:     if (ref($returnhash) eq 'HASH') {
                   4343:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4344:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4345:                  $rep eq '') {
                   4346:             my @pairs=split(/\&/,$rep);
                   4347:             foreach my $item (@pairs) {
                   4348:                 my ($key,$value)=split(/\=/,$item,2);
                   4349:                 $key = &unescape($key);
                   4350:                 next if ($key =~ /^error: 2 /);
                   4351:                 $returnhash->{$key} = &thaw_unescape($value);
                   4352:             }
                   4353:         }
                   4354:     }
                   4355:     return;
                   4356: }
                   4357: 
1.658     raeburn  4358: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4359: 
                   4360: sub dcmailput {
1.685     raeburn  4361:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4362:     my $status = &Apache::lonnet::critical(
1.740     www      4363:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4364:        &escape($message),$server);
1.662     raeburn  4365:     return $status;
                   4366: }
                   4367: 
1.658     raeburn  4368: sub dcmaildump {
                   4369:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4370:     my %returnhash=();
1.846     albertel 4371: 
                   4372:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4373:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4374:                                                          &escape($enddate).':';
                   4375: 	my @esc_senders=map { &escape($_)} @$senders;
                   4376: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4377: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4378:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4379:             if (($key) && ($value)) {
                   4380:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4381:             }
                   4382:         }
                   4383:     }
                   4384:     return %returnhash;
                   4385: }
1.662     raeburn  4386: # ---------------------------------------------------------- Domain roles
                   4387: 
                   4388: sub get_domain_roles {
                   4389:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4390:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4391:         $startdate = '.';
                   4392:     }
1.1018    raeburn  4393:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4394:         $enddate = '.';
                   4395:     }
1.922     raeburn  4396:     my $rolelist;
                   4397:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4398:         $rolelist = join('&',@{$roles});
1.922     raeburn  4399:     }
1.662     raeburn  4400:     my %personnel = ();
1.841     albertel 4401: 
                   4402:     my %servers = &get_servers($dom,'library');
                   4403:     foreach my $tryserver (keys(%servers)) {
                   4404: 	%{$personnel{$tryserver}}=();
                   4405: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4406: 					    &escape($startdate).':'.
                   4407: 					    &escape($enddate).':'.
                   4408: 					    &escape($rolelist), $tryserver))) {
                   4409: 	    my ($key,$value) = split(/\=/,$line,2);
                   4410: 	    if (($key) && ($value)) {
                   4411: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4412: 	    }
                   4413: 	}
1.662     raeburn  4414:     }
                   4415:     return %personnel;
                   4416: }
1.658     raeburn  4417: 
1.1057    www      4418: # ----------------------------------------------------------- Interval timing 
1.149     www      4419: 
1.1153    www      4420: {
                   4421: # Caches needed for speedup of navmaps
                   4422: # We don't want to cache this for very long at all (5 seconds at most)
                   4423: # 
                   4424: # The user for whom we cache
                   4425: my $cachedkey='';
                   4426: # The cached times for this user
                   4427: my %cachedtimes=();
                   4428: # When this was last done
                   4429: my $cachedtime=();
                   4430: 
                   4431: sub load_all_first_access {
1.1154    raeburn  4432:     my ($uname,$udom)=@_;
1.1156    www      4433:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4434:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4435:         return;
                   4436:     }
                   4437:     $cachedtime=time;
                   4438:     $cachedkey=$uname.':'.$udom;
                   4439:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4440: }
                   4441: 
1.504     albertel 4442: sub get_first_access {
1.1162    raeburn  4443:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4444:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4445:     if ($argsymb) { $symb=$argsymb; }
                   4446:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4447:     if ($argmap) { $map = $argmap; }
1.926     albertel 4448:     if ($type eq 'course') {
                   4449: 	$res='course';
                   4450:     } elsif ($type eq 'map') {
1.588     albertel 4451: 	$res=&symbread($map);
                   4452:     } else {
                   4453: 	$res=$symb;
                   4454:     }
1.1153    www      4455:     &load_all_first_access($uname,$udom);
                   4456:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4457: }
                   4458: 
                   4459: sub set_first_access {
1.1162    raeburn  4460:     my ($type,$interval)=@_;
1.790     albertel 4461:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4462:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4463:     if ($type eq 'course') {
                   4464: 	$res='course';
                   4465:     } elsif ($type eq 'map') {
1.588     albertel 4466: 	$res=&symbread($map);
                   4467:     } else {
                   4468: 	$res=$symb;
                   4469:     }
1.1153    www      4470:     $cachedkey='';
1.1162    raeburn  4471:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4472:     if (!$firstaccess) {
1.1162    raeburn  4473:         my $start = time;
                   4474: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4475:                           $udom,$uname);
                   4476:         if ($putres eq 'ok') {
                   4477:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4478:                  $udom,$uname); 
                   4479:             &appenv(
                   4480:                      {
                   4481:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4482:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4483:                      }
                   4484:                   );
                   4485:         }
                   4486:         return $putres;
1.505     albertel 4487:     }
                   4488:     return 'already_set';
1.504     albertel 4489: }
1.1153    www      4490: }
1.110     www      4491: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4492: 
                   4493: sub expirespread {
                   4494:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4495:     my $cid=$env{'request.course.id'}; 
1.110     www      4496:     if ($cid) {
                   4497:        my $now=time;
                   4498:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4499:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4500:                             $env{'course.'.$cid.'.num'}.
1.110     www      4501: 	        	    ':nohist_expirationdates:'.
                   4502:                             &escape($key).'='.$now,
1.620     albertel 4503:                             $env{'course.'.$cid.'.home'})
1.110     www      4504:     }
                   4505:     return 'ok';
1.14      www      4506: }
                   4507: 
1.109     www      4508: # ----------------------------------------------------- Devalidate Spreadsheets
                   4509: 
                   4510: sub devalidate {
1.325     www      4511:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4512:     my $cid=$env{'request.course.id'}; 
1.109     www      4513:     if ($cid) {
1.391     matthew  4514:         # delete the stored spreadsheets for
                   4515:         # - the student level sheet of this user in course's homespace
                   4516:         # - the assessment level sheet for this resource 
                   4517:         #   for this user in user's homespace
1.553     albertel 4518: 	# - current conditional state info
1.325     www      4519: 	my $key=$uname.':'.$udom.':';
1.109     www      4520:         my $status=
1.299     matthew  4521: 	    &del('nohist_calculatedsheets',
1.391     matthew  4522: 		 [$key.'studentcalc:'],
1.620     albertel 4523: 		 $env{'course.'.$cid.'.domain'},
                   4524: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4525: 		.' '.
                   4526: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4527: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4528:         unless ($status eq 'ok ok') {
                   4529:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4530:                     $uname.' at '.$udom.' for '.
1.109     www      4531: 		    $symb.': '.$status);
1.133     albertel 4532:         }
1.553     albertel 4533: 	&delenv('user.state.'.$cid);
1.109     www      4534:     }
                   4535: }
                   4536: 
1.265     albertel 4537: sub get_scalar {
                   4538:     my ($string,$end) = @_;
                   4539:     my $value;
                   4540:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4541: 	$value = $1;
                   4542:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4543: 	$value = $1;
                   4544:     }
                   4545:     return &unescape($value);
                   4546: }
                   4547: 
                   4548: sub array2str {
                   4549:   my (@array) = @_;
                   4550:   my $result=&arrayref2str(\@array);
                   4551:   $result=~s/^__ARRAY_REF__//;
                   4552:   $result=~s/__END_ARRAY_REF__$//;
                   4553:   return $result;
                   4554: }
                   4555: 
1.204     albertel 4556: sub arrayref2str {
                   4557:   my ($arrayref) = @_;
1.265     albertel 4558:   my $result='__ARRAY_REF__';
1.204     albertel 4559:   foreach my $elem (@$arrayref) {
1.265     albertel 4560:     if(ref($elem) eq 'ARRAY') {
                   4561:       $result.=&arrayref2str($elem).'&';
                   4562:     } elsif(ref($elem) eq 'HASH') {
                   4563:       $result.=&hashref2str($elem).'&';
                   4564:     } elsif(ref($elem)) {
                   4565:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4566:     } else {
                   4567:       $result.=&escape($elem).'&';
                   4568:     }
                   4569:   }
                   4570:   $result=~s/\&$//;
1.265     albertel 4571:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4572:   return $result;
                   4573: }
                   4574: 
1.168     albertel 4575: sub hash2str {
1.204     albertel 4576:   my (%hash) = @_;
                   4577:   my $result=&hashref2str(\%hash);
1.265     albertel 4578:   $result=~s/^__HASH_REF__//;
                   4579:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4580:   return $result;
                   4581: }
                   4582: 
                   4583: sub hashref2str {
                   4584:   my ($hashref)=@_;
1.265     albertel 4585:   my $result='__HASH_REF__';
1.800     albertel 4586:   foreach my $key (sort(keys(%$hashref))) {
                   4587:     if (ref($key) eq 'ARRAY') {
                   4588:       $result.=&arrayref2str($key).'=';
                   4589:     } elsif (ref($key) eq 'HASH') {
                   4590:       $result.=&hashref2str($key).'=';
                   4591:     } elsif (ref($key)) {
1.265     albertel 4592:       $result.='=';
1.800     albertel 4593:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4594:     } else {
1.1132    raeburn  4595: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4596:     }
                   4597: 
1.800     albertel 4598:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4599:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4600:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4601:       $result.=&hashref2str($hashref->{$key}).'&';
                   4602:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4603:        $result.='&';
1.800     albertel 4604:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4605:     } else {
1.800     albertel 4606:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4607:     }
                   4608:   }
1.168     albertel 4609:   $result=~s/\&$//;
1.265     albertel 4610:   $result .= '__END_HASH_REF__';
1.168     albertel 4611:   return $result;
                   4612: }
                   4613: 
                   4614: sub str2hash {
1.265     albertel 4615:     my ($string)=@_;
                   4616:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4617:     return %$hash;
                   4618: }
                   4619: 
                   4620: sub str2hashref {
1.168     albertel 4621:   my ($string) = @_;
1.265     albertel 4622: 
                   4623:   my %hash;
                   4624: 
                   4625:   if($string !~ /^__HASH_REF__/) {
                   4626:       if (! ($string eq '' || !defined($string))) {
                   4627: 	  $hash{'error'}='Not hash reference';
                   4628:       }
                   4629:       return (\%hash, $string);
                   4630:   }
                   4631: 
                   4632:   $string =~ s/^__HASH_REF__//;
                   4633: 
                   4634:   while($string !~ /^__END_HASH_REF__/) {
                   4635:       #key
                   4636:       my $key='';
                   4637:       if($string =~ /^__HASH_REF__/) {
                   4638:           ($key, $string)=&str2hashref($string);
                   4639:           if(defined($key->{'error'})) {
                   4640:               $hash{'error'}='Bad data';
                   4641:               return (\%hash, $string);
                   4642:           }
                   4643:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4644:           ($key, $string)=&str2arrayref($string);
                   4645:           if($key->[0] eq 'Array reference error') {
                   4646:               $hash{'error'}='Bad data';
                   4647:               return (\%hash, $string);
                   4648:           }
                   4649:       } else {
                   4650:           $string =~ s/^(.*?)=//;
1.267     albertel 4651: 	  $key=&unescape($1);
1.265     albertel 4652:       }
                   4653:       $string =~ s/^=//;
                   4654: 
                   4655:       #value
                   4656:       my $value='';
                   4657:       if($string =~ /^__HASH_REF__/) {
                   4658:           ($value, $string)=&str2hashref($string);
                   4659:           if(defined($value->{'error'})) {
                   4660:               $hash{'error'}='Bad data';
                   4661:               return (\%hash, $string);
                   4662:           }
                   4663:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4664:           ($value, $string)=&str2arrayref($string);
                   4665:           if($value->[0] eq 'Array reference error') {
                   4666:               $hash{'error'}='Bad data';
                   4667:               return (\%hash, $string);
                   4668:           }
                   4669:       } else {
                   4670: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4671:       }
                   4672:       $string =~ s/^&//;
                   4673: 
                   4674:       $hash{$key}=$value;
1.204     albertel 4675:   }
1.265     albertel 4676: 
                   4677:   $string =~ s/^__END_HASH_REF__//;
                   4678: 
                   4679:   return (\%hash, $string);
1.204     albertel 4680: }
                   4681: 
                   4682: sub str2array {
1.265     albertel 4683:     my ($string)=@_;
                   4684:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4685:     return @$array;
                   4686: }
                   4687: 
                   4688: sub str2arrayref {
1.204     albertel 4689:   my ($string) = @_;
1.265     albertel 4690:   my @array;
                   4691: 
                   4692:   if($string !~ /^__ARRAY_REF__/) {
                   4693:       if (! ($string eq '' || !defined($string))) {
                   4694: 	  $array[0]='Array reference error';
                   4695:       }
                   4696:       return (\@array, $string);
                   4697:   }
                   4698: 
                   4699:   $string =~ s/^__ARRAY_REF__//;
                   4700: 
                   4701:   while($string !~ /^__END_ARRAY_REF__/) {
                   4702:       my $value='';
                   4703:       if($string =~ /^__HASH_REF__/) {
                   4704:           ($value, $string)=&str2hashref($string);
                   4705:           if(defined($value->{'error'})) {
                   4706:               $array[0] ='Array reference error';
                   4707:               return (\@array, $string);
                   4708:           }
                   4709:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4710:           ($value, $string)=&str2arrayref($string);
                   4711:           if($value->[0] eq 'Array reference error') {
                   4712:               $array[0] ='Array reference error';
                   4713:               return (\@array, $string);
                   4714:           }
                   4715:       } else {
                   4716: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4717:       }
                   4718:       $string =~ s/^&//;
                   4719: 
                   4720:       push(@array, $value);
1.191     harris41 4721:   }
1.265     albertel 4722: 
                   4723:   $string =~ s/^__END_ARRAY_REF__//;
                   4724: 
                   4725:   return (\@array, $string);
1.168     albertel 4726: }
                   4727: 
1.167     albertel 4728: # -------------------------------------------------------------------Temp Store
                   4729: 
1.168     albertel 4730: sub tmpreset {
                   4731:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4732:   if (!$symb) {
                   4733:     $symb=&symbread();
1.620     albertel 4734:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4735:   }
                   4736:   $symb=escape($symb);
                   4737: 
1.620     albertel 4738:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4739:   $namespace=~s/\//\_/g;
                   4740:   $namespace=~s/\W//g;
                   4741: 
1.620     albertel 4742:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4743:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4744:   if ($domain eq 'public' && $stuname eq 'public') {
                   4745:       $stuname=$ENV{'REMOTE_ADDR'};
                   4746:   }
1.1117    foxr     4747:   my $path=LONCAPA::tempdir();
1.168     albertel 4748:   my %hash;
                   4749:   if (tie(%hash,'GDBM_File',
                   4750: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4751: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4752:     foreach my $key (keys(%hash)) {
1.180     albertel 4753:       if ($key=~ /:$symb/) {
1.168     albertel 4754: 	delete($hash{$key});
                   4755:       }
                   4756:     }
                   4757:   }
                   4758: }
                   4759: 
1.167     albertel 4760: sub tmpstore {
1.168     albertel 4761:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4762: 
                   4763:   if (!$symb) {
                   4764:     $symb=&symbread();
1.620     albertel 4765:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4766:   }
                   4767:   $symb=escape($symb);
                   4768: 
                   4769:   if (!$namespace) {
                   4770:     # I don't think we would ever want to store this for a course.
                   4771:     # it seems this will only be used if we don't have a course.
1.620     albertel 4772:     #$namespace=$env{'request.course.id'};
1.168     albertel 4773:     #if (!$namespace) {
1.620     albertel 4774:       $namespace=$env{'request.state'};
1.168     albertel 4775:     #}
                   4776:   }
                   4777:   $namespace=~s/\//\_/g;
                   4778:   $namespace=~s/\W//g;
1.620     albertel 4779:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4780:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4781:   if ($domain eq 'public' && $stuname eq 'public') {
                   4782:       $stuname=$ENV{'REMOTE_ADDR'};
                   4783:   }
1.168     albertel 4784:   my $now=time;
                   4785:   my %hash;
1.1117    foxr     4786:   my $path=LONCAPA::tempdir();
1.168     albertel 4787:   if (tie(%hash,'GDBM_File',
                   4788: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4789: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4790:     $hash{"version:$symb"}++;
                   4791:     my $version=$hash{"version:$symb"};
                   4792:     my $allkeys=''; 
                   4793:     foreach my $key (keys(%$storehash)) {
                   4794:       $allkeys.=$key.':';
1.591     albertel 4795:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4796:     }
                   4797:     $hash{"$version:$symb:timestamp"}=$now;
                   4798:     $allkeys.='timestamp';
                   4799:     $hash{"$version:keys:$symb"}=$allkeys;
                   4800:     if (untie(%hash)) {
                   4801:       return 'ok';
                   4802:     } else {
                   4803:       return "error:$!";
                   4804:     }
                   4805:   } else {
                   4806:     return "error:$!";
                   4807:   }
                   4808: }
1.167     albertel 4809: 
1.168     albertel 4810: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4811: 
1.168     albertel 4812: sub tmprestore {
                   4813:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4814: 
1.168     albertel 4815:   if (!$symb) {
                   4816:     $symb=&symbread();
1.620     albertel 4817:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4818:   }
                   4819:   $symb=escape($symb);
                   4820: 
1.620     albertel 4821:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4822: 
1.620     albertel 4823:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4824:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4825:   if ($domain eq 'public' && $stuname eq 'public') {
                   4826:       $stuname=$ENV{'REMOTE_ADDR'};
                   4827:   }
1.168     albertel 4828:   my %returnhash;
                   4829:   $namespace=~s/\//\_/g;
                   4830:   $namespace=~s/\W//g;
                   4831:   my %hash;
1.1117    foxr     4832:   my $path=LONCAPA::tempdir();
1.168     albertel 4833:   if (tie(%hash,'GDBM_File',
                   4834: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4835: 	  &GDBM_READER(),0640)) {
1.168     albertel 4836:     my $version=$hash{"version:$symb"};
                   4837:     $returnhash{'version'}=$version;
                   4838:     my $scope;
                   4839:     for ($scope=1;$scope<=$version;$scope++) {
                   4840:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4841:       my @keys=split(/:/,$vkeys);
                   4842:       my $key;
                   4843:       $returnhash{"$scope:keys"}=$vkeys;
                   4844:       foreach $key (@keys) {
1.591     albertel 4845: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4846: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4847:       }
                   4848:     }
1.168     albertel 4849:     if (!(untie(%hash))) {
                   4850:       return "error:$!";
                   4851:     }
                   4852:   } else {
                   4853:     return "error:$!";
                   4854:   }
                   4855:   return %returnhash;
1.167     albertel 4856: }
                   4857: 
1.9       www      4858: # ----------------------------------------------------------------------- Store
                   4859: 
                   4860: sub store {
1.1269    raeburn  4861:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      4862:     my $home='';
                   4863: 
1.168     albertel 4864:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4865: 
1.213     www      4866:     $symb=&symbclean($symb);
1.122     albertel 4867:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4868: 
1.620     albertel 4869:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4870:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4871: 
                   4872:     &devalidate($symb,$stuname,$domain);
1.109     www      4873: 
                   4874:     $symb=escape($symb);
1.187     www      4875:     if (!$namespace) { 
1.620     albertel 4876:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4877:           return ''; 
                   4878:        } 
                   4879:     }
1.620     albertel 4880:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4881: 
                   4882:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4883:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4884: 
1.12      www      4885:     my $namevalue='';
1.800     albertel 4886:     foreach my $key (keys(%$storehash)) {
                   4887:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4888:     }
1.12      www      4889:     $namevalue=~s/\&$//;
1.187     www      4890:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  4891:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      4892: }
                   4893: 
1.47      www      4894: # -------------------------------------------------------------- Critical Store
                   4895: 
                   4896: sub cstore {
1.1269    raeburn  4897:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      4898:     my $home='';
                   4899: 
1.168     albertel 4900:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4901: 
1.213     www      4902:     $symb=&symbclean($symb);
1.122     albertel 4903:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4904: 
1.620     albertel 4905:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4906:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4907: 
                   4908:     &devalidate($symb,$stuname,$domain);
1.109     www      4909: 
                   4910:     $symb=escape($symb);
1.187     www      4911:     if (!$namespace) { 
1.620     albertel 4912:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4913:           return ''; 
                   4914:        } 
                   4915:     }
1.620     albertel 4916:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4917: 
                   4918:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4919:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4920: 
1.47      www      4921:     my $namevalue='';
1.800     albertel 4922:     foreach my $key (keys(%$storehash)) {
                   4923:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4924:     }
1.47      www      4925:     $namevalue=~s/\&$//;
1.187     www      4926:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4927:     return critical
1.1269    raeburn  4928:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      4929: }
                   4930: 
1.9       www      4931: # --------------------------------------------------------------------- Restore
                   4932: 
                   4933: sub restore {
1.124     www      4934:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4935:     my $home='';
                   4936: 
1.168     albertel 4937:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4938: 
1.122     albertel 4939:     if (!$symb) {
1.1224    raeburn  4940:         return if ($namespace eq 'courserequests');
                   4941:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 4942:     } else {
1.1224    raeburn  4943:         unless ($namespace eq 'courserequests') {
                   4944:             $symb=&escape(&symbclean($symb));
                   4945:         }
1.122     albertel 4946:     }
1.188     www      4947:     if (!$namespace) { 
1.620     albertel 4948:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4949:           return ''; 
                   4950:        } 
                   4951:     }
1.620     albertel 4952:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4953:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4954:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4955:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4956: 
1.12      www      4957:     my %returnhash=();
1.800     albertel 4958:     foreach my $line (split(/\&/,$answer)) {
                   4959: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4960:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4961:     }
1.75      www      4962:     my $version;
                   4963:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4964:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4965:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4966:        }
1.75      www      4967:     }
1.13      www      4968:     return %returnhash;
1.34      www      4969: }
                   4970: 
                   4971: # ---------------------------------------------------------- Course Description
1.1118    foxr     4972: #
                   4973: #  
1.34      www      4974: 
                   4975: sub coursedescription {
1.731     albertel 4976:     my ($courseid,$args)=@_;
1.34      www      4977:     $courseid=~s/^\///;
1.49      www      4978:     $courseid=~s/\_/\//g;
1.34      www      4979:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4980:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4981:     my $normalid=$cdomain.'_'.$cnum;
                   4982:     # need to always cache even if we get errors otherwise we keep 
                   4983:     # trying and trying and trying to get the course description.
                   4984:     my %envhash=();
                   4985:     my %returnhash=();
1.731     albertel 4986:     
                   4987:     my $expiretime=600;
                   4988:     if ($env{'request.course.id'} eq $normalid) {
                   4989: 	$expiretime=120;
                   4990:     }
                   4991: 
                   4992:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4993:     if (!$args->{'freshen_cache'}
                   4994: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4995: 	foreach my $key (keys(%env)) {
                   4996: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4997: 	    my ($setting) = $1;
                   4998: 	    $returnhash{$setting} = $env{$key};
                   4999: 	}
                   5000: 	return %returnhash;
                   5001:     }
                   5002: 
1.1118    foxr     5003:     # get the data again
                   5004: 
1.731     albertel 5005:     if (!$args->{'one_time'}) {
                   5006: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5007:     }
1.811     albertel 5008: 
1.34      www      5009:     if ($chome ne 'no_host') {
1.302     albertel 5010:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5011:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5012: 	   my $username = $env{'user.name'}; # Defult username
                   5013: 	   if(defined $args->{'user'}) {
                   5014: 	       $username = $args->{'user'};
                   5015: 	   }
1.129     albertel 5016:            $returnhash{'home'}= $chome;
                   5017: 	   $returnhash{'domain'} = $cdomain;
                   5018: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5019:            if (!defined($returnhash{'type'})) {
                   5020:                $returnhash{'type'} = 'Course';
                   5021:            }
1.130     albertel 5022:            while (my ($name,$value) = each %returnhash) {
1.53      www      5023:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5024:            }
1.270     www      5025:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5026:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5027: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5028:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5029:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5030:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5031:        }
                   5032:     }
1.731     albertel 5033:     if (!$args->{'one_time'}) {
1.949     raeburn  5034: 	&appenv(\%envhash);
1.731     albertel 5035:     }
1.302     albertel 5036:     return %returnhash;
1.461     www      5037: }
                   5038: 
1.1080    raeburn  5039: sub update_released_required {
                   5040:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5041:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5042:         $cid = $env{'request.course.id'};
                   5043:         $cdom = $env{'course.'.$cid.'.domain'};
                   5044:         $cnum = $env{'course.'.$cid.'.num'};
                   5045:         $chome = $env{'course.'.$cid.'.home'};
                   5046:     }
                   5047:     if ($needsrelease) {
                   5048:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5049:         my $needsupdate;
                   5050:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5051:             $needsupdate = 1;
                   5052:         } else {
                   5053:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5054:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5055:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5056:                 $needsupdate = 1;
                   5057:             }
                   5058:         }
                   5059:         if ($needsupdate) {
                   5060:             my %needshash = (
                   5061:                              'internal.releaserequired' => $needsrelease,
                   5062:                             );
                   5063:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5064:             if ($putresult eq 'ok') {
                   5065:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5066:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5067:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5068:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5069:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5070:                 }
                   5071:             }
                   5072:         }
                   5073:     }
                   5074:     return;
                   5075: }
                   5076: 
1.461     www      5077: # -------------------------------------------------See if a user is privileged
                   5078: 
                   5079: sub privileged {
1.1219    raeburn  5080:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5081:     my $now = time;
1.1219    raeburn  5082:     my $roles;
                   5083:     if (ref($possroles) eq 'ARRAY') {
                   5084:         $roles = $possroles; 
                   5085:     } else {
                   5086:         $roles = ['dc','su'];
                   5087:     }
                   5088:     if (ref($possdomains) eq 'ARRAY') {
                   5089:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5090:         foreach my $dom (@{$possdomains}) {
                   5091:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5092:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5093:                 foreach my $role (@{$roles}) {
                   5094:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5095:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5096:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5097:                             return 1 unless (($end && $end < $now) ||
                   5098:                                              ($start && $start > $now));
                   5099:                         }
                   5100:                     }
                   5101:                 }
                   5102:             }
                   5103:         }
                   5104:     } else {
                   5105:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5106:         my $now = time;
1.1170    droeschl 5107: 
1.1275    musolffc 5108:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5109:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5110:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5111:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5112:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5113:             }
1.1219    raeburn  5114:         }
                   5115:     }
                   5116:     return 0;
                   5117: }
1.1170    droeschl 5118: 
1.1219    raeburn  5119: sub privileged_by_domain {
                   5120:     my ($domains,$roles) = @_;
                   5121:     my %privileged = ();
                   5122:     my $cachetime = 60*60*24;
                   5123:     my $now = time;
                   5124:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5125:         return %privileged;
                   5126:     }
                   5127:     foreach my $dom (@{$domains}) {
                   5128:         next if (ref($privileged{$dom}) eq 'HASH');
                   5129:         my $needroles;
                   5130:         foreach my $role (@{$roles}) {
                   5131:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5132:             if (defined($cached)) {
                   5133:                 if (ref($result) eq 'HASH') {
                   5134:                     $privileged{$dom}{$role} = $result;
                   5135:                 }
                   5136:             } else {
                   5137:                 $needroles = 1;
                   5138:             }
                   5139:         }
                   5140:         if ($needroles) {
                   5141:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5142:             $privileged{$dom} = {};
                   5143:             foreach my $server (keys(%dompersonnel)) {
                   5144:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5145:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5146:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5147:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5148:                         next if ($end && $end < $now);
                   5149:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5150:                             $dompersonnel{$server}{$item};
                   5151:                     }
                   5152:                 }
                   5153:             }
                   5154:             if (ref($privileged{$dom}) eq 'HASH') {
                   5155:                 foreach my $role (@{$roles}) {
                   5156:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5157:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5158:                     } else {
                   5159:                         my %hash = ();
                   5160:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5161:                     }
                   5162:                 }
                   5163:             }
                   5164:         }
                   5165:     }
                   5166:     return %privileged;
1.9       www      5167: }
1.1       albertel 5168: 
1.103     harris41 5169: # -------------------------------------------------------- Get user privileges
1.11      www      5170: 
                   5171: sub rolesinit {
1.1169    droeschl 5172:     my ($domain, $username) = @_;
                   5173:     my %userroles = ('user.login.time' => time);
                   5174:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5175: 
                   5176:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5177:     # also, blocking can be triggered by an activating timer
                   5178:     # it's saved in the user's %env.
                   5179:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5180:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5181:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5182:         %timerintchk, %timerintenv);
                   5183: 
1.1162    raeburn  5184:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5185:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5186:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5187:     }
1.1169    droeschl 5188: 
1.1162    raeburn  5189:     foreach my $key (keys(%timerinterval)) {
                   5190:         my ($cid,$rest) = split(/\0/,$key);
                   5191:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5192:     }
1.1169    droeschl 5193: 
1.11      www      5194:     my %allroles=();
1.1162    raeburn  5195:     my %allgroups=();
1.11      www      5196: 
1.1274    raeburn  5197:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5198:         my $role = $rolesdump{$area};
                   5199:         $area =~ s/\_\w\w$//;
                   5200: 
                   5201:         my ($trole, $tend, $tstart, $group_privs);
                   5202: 
                   5203:         if ($role =~ /^cr/) {
                   5204:         # Custom role, defined by a user 
                   5205:         # e.g., user.role.cr/msu/smith/mynewrole
                   5206:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5207:                 $trole = $1;
                   5208:                 ($tend, $tstart) = split('_', $2);
                   5209:             } else {
                   5210:                 $trole = $role;
                   5211:             }
                   5212:         } elsif ($role =~ m|^gr/|) {
                   5213:         # Role of member in a group, defined within a course/community
                   5214:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5215:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5216:             next if $tstart eq '-1';
                   5217:             ($trole, $group_privs) = split(/\//, $trole);
                   5218:             $group_privs = &unescape($group_privs);
                   5219:         } else {
                   5220:         # Just a normal role, defined in roles.tab
                   5221:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5222:         }
                   5223: 
                   5224:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5225:                  $username);
                   5226:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5227: 
                   5228:         # role expired or not available yet?
                   5229:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5230:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5231: 
                   5232:         next if $area eq '' or $trole eq '';
                   5233: 
                   5234:         my $spec = "$trole.$area";
                   5235:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5236: 
                   5237:         if ($trole =~ /^cr\//) {
                   5238:         # Custom role, defined by a user
                   5239:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5240:         } elsif ($trole eq 'gr') {
                   5241:         # Role of a member in a group, defined within a course/community
                   5242:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5243:             next;
                   5244:         } else {
                   5245:         # Normal role, defined in roles.tab
                   5246:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5247:         }
                   5248: 
                   5249:         my $cid = $tdomain.'_'.$trest;
                   5250:         unless ($firstaccchk{$cid}) {
                   5251:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5252:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5253:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5254:                         $coursetimerstarts{$cid}{$item}; 
                   5255:                 }
                   5256:             }
                   5257:             $firstaccchk{$cid} = 1;
                   5258:         }
                   5259:         unless ($timerintchk{$cid}) {
                   5260:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5261:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5262:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5263:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5264:                 }
1.12      www      5265:             }
1.1169    droeschl 5266:             $timerintchk{$cid} = 1;
1.191     harris41 5267:         }
1.11      www      5268:     }
1.1169    droeschl 5269: 
                   5270:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5271:         \%allroles, \%allgroups);
                   5272:     $env{'user.adv'} = $userroles{'user.adv'};
                   5273: 
1.1162    raeburn  5274:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5275: }
                   5276: 
1.567     raeburn  5277: sub set_arearole {
1.1215    raeburn  5278:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5279:     unless ($nolog) {
1.567     raeburn  5280: # log the associated role with the area
1.1215    raeburn  5281:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5282:     }
1.743     albertel 5283:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5284: }
                   5285: 
                   5286: sub custom_roleprivs {
                   5287:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5288:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5289:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5290:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5291:         my ($rdummy,$roledef)=
                   5292:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5293:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5294:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5295:             if (defined($syspriv)) {
1.1043    raeburn  5296:                 if ($trest =~ /^$match_community$/) {
                   5297:                     $syspriv =~ s/bre\&S//; 
                   5298:                 }
1.567     raeburn  5299:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5300:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5301:             }
                   5302:             if ($tdomain ne '') {
                   5303:                 if (defined($dompriv)) {
                   5304:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5305:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5306:                 }
                   5307:                 if (($trest ne '') && (defined($coursepriv))) {
                   5308:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5309:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5310:                 }
                   5311:             }
                   5312:         }
                   5313:     }
                   5314: }
                   5315: 
1.678     raeburn  5316: sub group_roleprivs {
                   5317:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5318:     my $access = 1;
                   5319:     my $now = time;
                   5320:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5321:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5322:     if ($access) {
1.811     albertel 5323:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5324:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5325:     }
                   5326: }
1.567     raeburn  5327: 
                   5328: sub standard_roleprivs {
                   5329:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5330:     if (defined($pr{$trole.':s'})) {
                   5331:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5332:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5333:     }
                   5334:     if ($tdomain ne '') {
                   5335:         if (defined($pr{$trole.':d'})) {
                   5336:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5337:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5338:         }
                   5339:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5340:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5341:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5342:         }
                   5343:     }
                   5344: }
                   5345: 
                   5346: sub set_userprivs {
1.1064    raeburn  5347:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5348:     my $author=0;
                   5349:     my $adv=0;
1.678     raeburn  5350:     my %grouproles = ();
                   5351:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5352:         my @groupkeys; 
1.1000    raeburn  5353:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5354:             push(@groupkeys,$role);
                   5355:         }
                   5356:         if (ref($groups_roles) eq 'HASH') {
                   5357:             foreach my $key (keys(%{$groups_roles})) {
                   5358:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5359:                     push(@groupkeys,$key);
                   5360:                 }
                   5361:             }
                   5362:         }
                   5363:         if (@groupkeys > 0) {
                   5364:             foreach my $role (@groupkeys) {
                   5365:                 my ($trole,$area,$sec,$extendedarea);
                   5366:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5367:                     $trole = $1;
                   5368:                     $area = $2;
                   5369:                     $sec = $3;
                   5370:                     $extendedarea = $area.$sec;
                   5371:                     if (exists($$allgroups{$area})) {
                   5372:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5373:                             my $spec = $trole.'.'.$extendedarea;
                   5374:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5375:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5376:                         }
1.678     raeburn  5377:                     }
                   5378:                 }
                   5379:             }
                   5380:         }
                   5381:     }
1.800     albertel 5382:     foreach my $group (keys(%grouproles)) {
                   5383:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5384:     }
1.800     albertel 5385:     foreach my $role (keys(%{$allroles})) {
                   5386:         my %thesepriv;
1.941     raeburn  5387:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5388:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5389:             if ($item ne '') {
                   5390:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5391:                 if ($restrictions eq '') {
                   5392:                     $thesepriv{$privilege}='F';
                   5393:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5394:                     $thesepriv{$privilege}.=$restrictions;
                   5395:                 }
                   5396:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5397:             }
                   5398:         }
                   5399:         my $thesestr='';
1.1104    raeburn  5400:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5401: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5402: 	}
                   5403:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5404:     }
                   5405:     return ($author,$adv);
                   5406: }
                   5407: 
1.994     raeburn  5408: sub role_status {
1.1104    raeburn  5409:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5410:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5411:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5412:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5413:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5414:             $$where = '/'.$two;
1.994     raeburn  5415:             $$trolecode=$$role.'.'.$$where;
                   5416:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5417:             $$tstatus='is';
1.1104    raeburn  5418:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5419:                 $$tstatus='future';
1.1034    raeburn  5420:                 if ($$tstart<$now) {
                   5421:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5422:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5423:                             my (%allroles,%allgroups,$group_privs,
                   5424:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5425:                             my %userroles = (
                   5426:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5427:                             );
1.1064    raeburn  5428:                             @rolecodes = ('cm'); 
1.1002    raeburn  5429:                             my $spec=$$role.'.'.$$where;
                   5430:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5431:                             if ($$role =~ /^cr\//) {
                   5432:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5433:                                 push(@rolecodes,'cr');
1.1002    raeburn  5434:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5435:                                 push(@rolecodes,$$role);
1.1002    raeburn  5436:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5437:                                                     $env{'user.name'});
1.1064    raeburn  5438:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5439:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5440:                                 $group_privs = &unescape($group_privs);
                   5441:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5442:                                 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  5443:                                 &get_groups_roles($tdomain,$trest,
                   5444:                                                   \%course_roles,\@rolecodes,
                   5445:                                                   \%groups_roles);
1.1002    raeburn  5446:                             } else {
1.1064    raeburn  5447:                                 push(@rolecodes,$$role);
1.1002    raeburn  5448:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5449:                             }
1.1064    raeburn  5450:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5451:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5452:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5453:                         }
                   5454:                     }
1.1034    raeburn  5455:                     $$tstatus = 'is';
1.1002    raeburn  5456:                 }
1.994     raeburn  5457:             }
                   5458:             if ($$tend) {
1.1104    raeburn  5459:                 if ($$tend<$update) {
1.994     raeburn  5460:                     $$tstatus='expired';
                   5461:                 } elsif ($$tend<$now) {
                   5462:                     $$tstatus='will_not';
                   5463:                 }
                   5464:             }
                   5465:         }
                   5466:     }
                   5467: }
                   5468: 
1.1104    raeburn  5469: sub get_groups_roles {
                   5470:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5471:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5472:                   (ref($rolecodes) eq 'ARRAY') && 
                   5473:                   (ref($groups_roles) eq 'HASH')); 
                   5474:     if (keys(%{$cdom_courseroles}) > 0) {
                   5475:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5476:         if ($cdom ne '' && $cnum ne '') {
                   5477:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5478:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5479:                     my $crsrole = $1;
                   5480:                     my $crssec = $2;
                   5481:                     if ($crsrole =~ /^cr/) {
                   5482:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5483:                             push(@{$rolecodes},'cr');
                   5484:                         }
                   5485:                     } else {
                   5486:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5487:                             push(@{$rolecodes},$crsrole);
                   5488:                         }
                   5489:                     }
                   5490:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5491:                     if ($crssec ne '') {
                   5492:                         $rolekey .= "/$crssec";
                   5493:                     }
                   5494:                     $rolekey .= './';
                   5495:                     $groups_roles->{$rolekey} = $rolecodes;
                   5496:                 }
                   5497:             }
                   5498:         }
                   5499:     }
                   5500:     return;
                   5501: }
                   5502: 
                   5503: sub delete_env_groupprivs {
                   5504:     my ($where,$courseroles,$possroles) = @_;
                   5505:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5506:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5507:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5508:         %{$courseroles->{$udom}} =
                   5509:             &get_my_roles('','','userroles',['active'],
                   5510:                           $possroles,[$udom],1);
                   5511:     }
                   5512:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5513:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5514:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5515:             my $area = '/'.$cdom.'/'.$cnum;
                   5516:             my $privkey = "user.priv.$crsrole.$area";
                   5517:             if ($crssec ne '') {
                   5518:                 $privkey .= '/'.$crssec;
                   5519:             }
                   5520:             $privkey .= ".$area/$group";
                   5521:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5522:         }
                   5523:     }
                   5524:     return;
                   5525: }
                   5526: 
1.994     raeburn  5527: sub check_adhoc_privs {
1.1104    raeburn  5528:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5529:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5530:     my $setprivs;
1.994     raeburn  5531:     if ($env{$cckey}) {
                   5532:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5533:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5534:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5535:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5536:             $setprivs = 1;
1.994     raeburn  5537:         }
                   5538:     } else {
1.1088    raeburn  5539:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5540:         $setprivs = 1;
1.994     raeburn  5541:     }
1.1185    raeburn  5542:     return $setprivs;
1.994     raeburn  5543: }
                   5544: 
                   5545: sub set_adhoc_privileges {
                   5546: # role can be cc or ca
1.1088    raeburn  5547:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5548:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5549:     my $spec = $role.'.'.$area;
                   5550:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5551:                                   $env{'user.name'},1);
1.994     raeburn  5552:     my %ccrole = ();
                   5553:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5554:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5555:     &appenv(\%userroles,[$role,'cm']);
                   5556:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5557:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5558:         &appenv( {'request.role'        => $spec,
                   5559:                   'request.role.domain' => $dcdom,
                   5560:                   'request.course.sec'  => ''
                   5561:                  }
                   5562:                );
                   5563:         my $tadv=0;
                   5564:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5565:         &appenv({'request.role.adv'    => $tadv});
                   5566:     }
1.994     raeburn  5567: }
                   5568: 
1.12      www      5569: # --------------------------------------------------------------- get interface
                   5570: 
                   5571: sub get {
1.131     albertel 5572:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5573:    my $items='';
1.800     albertel 5574:    foreach my $item (@$storearr) {
                   5575:        $items.=&escape($item).'&';
1.191     harris41 5576:    }
1.12      www      5577:    $items=~s/\&$//;
1.620     albertel 5578:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5579:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5580:    my $uhome=&homeserver($uname,$udomain);
                   5581: 
1.133     albertel 5582:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5583:    my @pairs=split(/\&/,$rep);
1.273     albertel 5584:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5585:      return @pairs;
                   5586:    }
1.15      www      5587:    my %returnhash=();
1.42      www      5588:    my $i=0;
1.800     albertel 5589:    foreach my $item (@$storearr) {
                   5590:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5591:       $i++;
1.191     harris41 5592:    }
1.15      www      5593:    return %returnhash;
1.27      www      5594: }
                   5595: 
                   5596: # --------------------------------------------------------------- del interface
                   5597: 
                   5598: sub del {
1.133     albertel 5599:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5600:    my $items='';
1.800     albertel 5601:    foreach my $item (@$storearr) {
                   5602:        $items.=&escape($item).'&';
1.191     harris41 5603:    }
1.984     neumanie 5604: 
1.27      www      5605:    $items=~s/\&$//;
1.620     albertel 5606:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5607:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5608:    my $uhome=&homeserver($uname,$udomain);
                   5609:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5610: }
                   5611: 
                   5612: # -------------------------------------------------------------- dump interface
                   5613: 
1.1180    droeschl 5614: sub unserialize {
                   5615:     my ($rep, $escapedkeys) = @_;
                   5616: 
                   5617:     return {} if $rep =~ /^error/;
                   5618: 
                   5619:     my %returnhash=();
1.1252    raeburn  5620: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 5621: 	    my ($key, $value) = split(/=/, $item, 2);
                   5622: 	    $key = unescape($key) unless $escapedkeys;
                   5623: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  5624: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 5625: 	}
                   5626:     #return %returnhash;
                   5627:     return \%returnhash;
                   5628: }        
                   5629: 
                   5630: # see Lond::dump_with_regexp
                   5631: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5632: sub dump {
1.1180    droeschl 5633:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5634:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5635:     if (!$uname) { $uname=$env{'user.name'}; }
                   5636:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5637: 
1.1266    raeburn  5638:     if ($regexp) {
                   5639:         $regexp=&escape($regexp);
                   5640:     } else {
                   5641:         $regexp='.';
                   5642:     }
1.1180    droeschl 5643:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5644:         # user is hosted on this machine
1.1266    raeburn  5645:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5646:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5647:         return %{unserialize($reply, $escapedkeys)};
                   5648:     }
1.1166    raeburn  5649:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5650:     my @pairs=split(/\&/,$rep);
                   5651:     my %returnhash=();
1.1098    foxr     5652:     if (!($rep =~ /^error/ )) {
                   5653: 	foreach my $item (@pairs) {
                   5654: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5655:         $key = unescape($key) unless $escapedkeys;
                   5656:         #$key = &unescape($key);
1.1098    foxr     5657: 	    next if ($key =~ /^error: 2 /);
                   5658: 	    $returnhash{$key}=&thaw_unescape($value);
                   5659: 	}
1.755     albertel 5660:     }
                   5661:     return %returnhash;
1.407     www      5662: }
                   5663: 
1.1098    foxr     5664: 
1.717     albertel 5665: # --------------------------------------------------------- dumpstore interface
                   5666: 
                   5667: sub dumpstore {
                   5668:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5669:    # same as dump but keys must be escaped. They may contain colon separated
                   5670:    # lists of values that may themself contain colons (e.g. symbs).
                   5671:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5672: }
                   5673: 
1.407     www      5674: # -------------------------------------------------------------- keys interface
                   5675: 
                   5676: sub getkeys {
                   5677:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5678:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5679:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5680:    my $uhome=&homeserver($uname,$udomain);
                   5681:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5682:    my @keyarray=();
1.800     albertel 5683:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5684:       next if ($key =~ /^error: 2 /);
1.800     albertel 5685:       push(@keyarray,&unescape($key));
1.407     www      5686:    }
                   5687:    return @keyarray;
1.318     matthew  5688: }
                   5689: 
1.319     matthew  5690: # --------------------------------------------------------------- currentdump
                   5691: sub currentdump {
1.328     matthew  5692:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5693:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5694:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5695:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5696:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5697:    my $rep;
                   5698: 
                   5699:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5700:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5701:                    $courseid)));
                   5702:    } else {
                   5703:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5704:    }
                   5705: 
1.318     matthew  5706:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5707:    #
1.318     matthew  5708:    my %returnhash=();
1.319     matthew  5709:    #
                   5710:    if ($rep eq "unknown_cmd") { 
                   5711:        # an old lond will not know currentdump
                   5712:        # Do a dump and make it look like a currentdump
1.822     albertel 5713:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5714:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5715:        my %hash = @tmp;
                   5716:        @tmp=();
1.424     matthew  5717:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5718:    } else {
                   5719:        my @pairs=split(/\&/,$rep);
1.800     albertel 5720:        foreach my $pair (@pairs) {
                   5721:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5722:            my ($symb,$param) = split(/:/,$key);
                   5723:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5724:                                                         &thaw_unescape($value);
1.319     matthew  5725:        }
1.191     harris41 5726:    }
1.12      www      5727:    return %returnhash;
1.424     matthew  5728: }
                   5729: 
                   5730: sub convert_dump_to_currentdump{
                   5731:     my %hash = %{shift()};
                   5732:     my %returnhash;
                   5733:     # Code ripped from lond, essentially.  The only difference
                   5734:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5735:     # we might run in to problems with parameter names =~ /^v\./
                   5736:     while (my ($key,$value) = each(%hash)) {
                   5737:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5738: 	$symb  = &unescape($symb);
                   5739: 	$param = &unescape($param);
1.424     matthew  5740:         next if ($v eq 'version' || $symb eq 'keys');
                   5741:         next if (exists($returnhash{$symb}) &&
                   5742:                  exists($returnhash{$symb}->{$param}) &&
                   5743:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5744:         $returnhash{$symb}->{$param}=$value;
                   5745:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5746:     }
                   5747:     #
                   5748:     # Remove all of the keys in the hashes which keep track of
                   5749:     # the version of the parameter.
                   5750:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5751:         # use a foreach because we are going to delete from the hash.
                   5752:         foreach my $key (keys(%$param_hash)) {
                   5753:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5754:         }
                   5755:     }
                   5756:     return \%returnhash;
1.12      www      5757: }
                   5758: 
1.627     albertel 5759: # ------------------------------------------------------ critical inc interface
                   5760: 
                   5761: sub cinc {
                   5762:     return &inc(@_,'critical');
                   5763: }
                   5764: 
1.449     matthew  5765: # --------------------------------------------------------------- inc interface
                   5766: 
                   5767: sub inc {
1.627     albertel 5768:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5769:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5770:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5771:     my $uhome=&homeserver($uname,$udomain);
                   5772:     my $items='';
                   5773:     if (! ref($store)) {
                   5774:         # got a single value, so use that instead
                   5775:         $items = &escape($store).'=&';
                   5776:     } elsif (ref($store) eq 'SCALAR') {
                   5777:         $items = &escape($$store).'=&';        
                   5778:     } elsif (ref($store) eq 'ARRAY') {
                   5779:         $items = join('=&',map {&escape($_);} @{$store});
                   5780:     } elsif (ref($store) eq 'HASH') {
                   5781:         while (my($key,$value) = each(%{$store})) {
                   5782:             $items.= &escape($key).'='.&escape($value).'&';
                   5783:         }
                   5784:     }
                   5785:     $items=~s/\&$//;
1.627     albertel 5786:     if ($critical) {
                   5787: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5788:     } else {
                   5789: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5790:     }
1.449     matthew  5791: }
                   5792: 
1.12      www      5793: # --------------------------------------------------------------- put interface
                   5794: 
                   5795: sub put {
1.134     albertel 5796:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5797:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5798:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5799:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5800:    my $items='';
1.800     albertel 5801:    foreach my $item (keys(%$storehash)) {
                   5802:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5803:    }
1.12      www      5804:    $items=~s/\&$//;
1.134     albertel 5805:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5806: }
                   5807: 
1.631     albertel 5808: # ------------------------------------------------------------ newput interface
                   5809: 
                   5810: sub newput {
                   5811:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5812:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5813:    if (!$uname) { $uname=$env{'user.name'}; }
                   5814:    my $uhome=&homeserver($uname,$udomain);
                   5815:    my $items='';
                   5816:    foreach my $key (keys(%$storehash)) {
                   5817:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5818:    }
                   5819:    $items=~s/\&$//;
                   5820:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5821: }
                   5822: 
                   5823: # ---------------------------------------------------------  putstore interface
                   5824: 
1.524     raeburn  5825: sub putstore {
1.1269    raeburn  5826:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 5827:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5828:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5829:    my $uhome=&homeserver($uname,$udomain);
                   5830:    my $items='';
1.715     albertel 5831:    foreach my $key (keys(%$storehash)) {
                   5832:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5833:    }
1.715     albertel 5834:    $items=~s/\&$//;
1.716     albertel 5835:    my $esc_symb=&escape($symb);
                   5836:    my $esc_v=&escape($version);
1.715     albertel 5837:    my $reply =
1.716     albertel 5838:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5839: 	      $uhome);
1.1269    raeburn  5840:    if (($tolog) && ($reply eq 'ok')) {
                   5841:        my $namevalue='';
                   5842:        foreach my $key (keys(%{$storehash})) {
                   5843:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   5844:        }
                   5845:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   5846:                      '&host='.&escape($perlvar{'lonHostID'}).
                   5847:                      '&version='.$esc_v.
                   5848:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   5849:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   5850:    }
1.715     albertel 5851:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5852:        # gfall back to way things use to be done
1.715     albertel 5853:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5854: 			    $uname);
1.524     raeburn  5855:    }
1.715     albertel 5856:    return $reply;
                   5857: }
                   5858: 
                   5859: sub old_putstore {
1.716     albertel 5860:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5861:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5862:     if (!$uname) { $uname=$env{'user.name'}; }
                   5863:     my $uhome=&homeserver($uname,$udomain);
                   5864:     my %newstorehash;
1.800     albertel 5865:     foreach my $item (keys(%$storehash)) {
                   5866: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5867: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5868:     }
                   5869:     my $items='';
                   5870:     my %allitems = ();
1.800     albertel 5871:     foreach my $item (keys(%newstorehash)) {
                   5872: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5873: 	    my $key = $1.':keys:'.$2;
                   5874: 	    $allitems{$key} .= $3.':';
                   5875: 	}
1.800     albertel 5876: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5877:     }
1.800     albertel 5878:     foreach my $item (keys(%allitems)) {
                   5879: 	$allitems{$item} =~ s/\:$//;
                   5880: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5881:     }
                   5882:     $items=~s/\&$//;
                   5883:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5884: }
                   5885: 
1.47      www      5886: # ------------------------------------------------------ critical put interface
                   5887: 
                   5888: sub cput {
1.134     albertel 5889:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5890:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5891:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5892:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5893:    my $items='';
1.800     albertel 5894:    foreach my $item (keys(%$storehash)) {
                   5895:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5896:    }
1.47      www      5897:    $items=~s/\&$//;
1.134     albertel 5898:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5899: }
                   5900: 
                   5901: # -------------------------------------------------------------- eget interface
                   5902: 
                   5903: sub eget {
1.133     albertel 5904:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5905:    my $items='';
1.800     albertel 5906:    foreach my $item (@$storearr) {
                   5907:        $items.=&escape($item).'&';
1.191     harris41 5908:    }
1.12      www      5909:    $items=~s/\&$//;
1.620     albertel 5910:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5911:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5912:    my $uhome=&homeserver($uname,$udomain);
                   5913:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5914:    my @pairs=split(/\&/,$rep);
                   5915:    my %returnhash=();
1.42      www      5916:    my $i=0;
1.800     albertel 5917:    foreach my $item (@$storearr) {
                   5918:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5919:       $i++;
1.191     harris41 5920:    }
1.12      www      5921:    return %returnhash;
                   5922: }
                   5923: 
1.667     albertel 5924: # ------------------------------------------------------------ tmpput interface
                   5925: sub tmpput {
1.802     raeburn  5926:     my ($storehash,$server,$context)=@_;
1.667     albertel 5927:     my $items='';
1.800     albertel 5928:     foreach my $item (keys(%$storehash)) {
                   5929: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5930:     }
                   5931:     $items=~s/\&$//;
1.802     raeburn  5932:     if (defined($context)) {
                   5933:         $items .= ':'.&escape($context);
                   5934:     }
1.667     albertel 5935:     return &reply("tmpput:$items",$server);
                   5936: }
                   5937: 
                   5938: # ------------------------------------------------------------ tmpget interface
                   5939: sub tmpget {
1.688     albertel 5940:     my ($token,$server)=@_;
                   5941:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5942:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5943:     my %returnhash;
                   5944:     foreach my $item (split(/\&/,$rep)) {
                   5945: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5946:         next if ($key =~ /^error: 2 /);
1.667     albertel 5947: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5948:     }
                   5949:     return %returnhash;
                   5950: }
                   5951: 
1.1113    raeburn  5952: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5953: sub tmpdel {
                   5954:     my ($token,$server)=@_;
                   5955:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5956:     return &reply("tmpdel:$token",$server);
                   5957: }
                   5958: 
1.1198    raeburn  5959: # ------------------------------------------------------------ get_timebased_id 
                   5960: 
                   5961: sub get_timebased_id {
                   5962:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5963:         $maxtries) = @_;
                   5964:     my ($newid,$error,$dellock);
                   5965:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   5966:         return ('','ok','invalid call to get suffix');
                   5967:     }
                   5968: 
                   5969: # set defaults for any optional args for which values were not supplied
                   5970:     if ($who eq '') {
                   5971:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5972:     }
                   5973:     if (!$locktries) {
                   5974:         $locktries = 3;
                   5975:     }
                   5976:     if (!$maxtries) {
                   5977:         $maxtries = 10;
                   5978:     }
                   5979:     
                   5980:     if (($cdom eq '') || ($cnum eq '')) {
                   5981:         if ($env{'request.course.id'}) {
                   5982:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5983:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5984:         }
                   5985:         if (($cdom eq '') || ($cnum eq '')) {
                   5986:             return ('','ok','call to get suffix not in course context');
                   5987:         }
                   5988:     }
                   5989: 
                   5990: # construct locking item
                   5991:     my $lockhash = {
                   5992:                       $prefix."\0".'locked_'.$keyid => $who,
                   5993:                    };
                   5994:     my $tries = 0;
                   5995: 
                   5996: # attempt to get lock on nohist_$namespace file
                   5997:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5998:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5999:         $tries ++;
                   6000:         sleep 1;
                   6001:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6002:     }
                   6003: 
                   6004: # attempt to get unique identifier, based on current timestamp
                   6005:     if ($gotlock eq 'ok') {
                   6006:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6007:         my $id = time;
                   6008:         $newid = $id;
1.1268    raeburn  6009:         if ($idtype eq 'addcode') {
                   6010:             $newid .= &sixnum_code();
                   6011:         }
1.1198    raeburn  6012:         my $idtries = 0;
                   6013:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6014:             if ($idtype eq 'concat') {
                   6015:                 $newid = $id.$idtries;
1.1268    raeburn  6016:             } elsif ($idtype eq 'addcode') {
                   6017:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6018:             } else {
                   6019:                 $newid ++;
                   6020:             }
                   6021:             $idtries ++;
                   6022:         }
                   6023:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6024:             my %new_item =  (
                   6025:                               $prefix."\0".$newid => $who,
                   6026:                             );
                   6027:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6028:                                                  $cdom,$cnum);
                   6029:             if ($putresult ne 'ok') {
                   6030:                 undef($newid);
                   6031:                 $error = 'error saving new item: '.$putresult;
                   6032:             }
                   6033:         } else {
1.1268    raeburn  6034:              undef($newid);
1.1198    raeburn  6035:              $error = ('error: no unique suffix available for the new item ');
                   6036:         }
                   6037: #  remove lock
                   6038:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6039:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6040:     } else {
                   6041:         $error = "error: could not obtain lockfile\n";
                   6042:         $dellock = 'ok';
1.1276  ! raeburn  6043:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
        !          6044:             $dellock = 'nolock';
        !          6045:         }
1.1198    raeburn  6046:     }
                   6047:     return ($newid,$dellock,$error);
                   6048: }
                   6049: 
1.1268    raeburn  6050: sub sixnum_code {
                   6051:     my $code;
                   6052:     for (0..6) {
                   6053:         $code .= int( rand(9) );
                   6054:     }
                   6055:     return $code;
                   6056: }
                   6057: 
1.765     albertel 6058: # -------------------------------------------------- portfolio access checking
                   6059: 
                   6060: sub portfolio_access {
1.1270    raeburn  6061:     my ($requrl,$clientip) = @_;
1.765     albertel 6062:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6063:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6064:     if ($result) {
                   6065:         my %setters;
                   6066:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6067:             my ($startblock,$endblock) =
                   6068:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6069:             if ($startblock && $endblock) {
                   6070:                 return 'B';
                   6071:             }
                   6072:         } else {
                   6073:             my ($startblock,$endblock) =
                   6074:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6075:             if ($startblock && $endblock) {
                   6076:                 return 'B';
                   6077:             }
                   6078:         }
                   6079:     }
1.765     albertel 6080:     if ($result eq 'ok') {
1.766     albertel 6081:        return 'F';
1.765     albertel 6082:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6083:        return 'A';
1.765     albertel 6084:     }
1.766     albertel 6085:     return '';
1.765     albertel 6086: }
                   6087: 
                   6088: sub get_portfolio_access {
1.1270    raeburn  6089:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6090: 
                   6091:     if (!ref($access_hash)) {
                   6092: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6093: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6094: 						   $file_name);
                   6095: 	$access_hash = $access_controls{$file_name};
                   6096:     }
                   6097: 
1.1270    raeburn  6098:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6099:     my $now = time;
                   6100:     if (ref($access_hash) eq 'HASH') {
                   6101:         foreach my $key (keys(%{$access_hash})) {
                   6102:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6103:             if ($start > $now) {
                   6104:                 next;
                   6105:             }
                   6106:             if ($end && $end<$now) {
                   6107:                 next;
                   6108:             }
                   6109:             if ($scope eq 'public') {
                   6110:                 $public = $key;
                   6111:                 last;
                   6112:             } elsif ($scope eq 'guest') {
                   6113:                 $guest = $key;
                   6114:             } elsif ($scope eq 'domains') {
                   6115:                 push(@domains,$key);
                   6116:             } elsif ($scope eq 'users') {
                   6117:                 push(@users,$key);
                   6118:             } elsif ($scope eq 'course') {
                   6119:                 push(@courses,$key);
                   6120:             } elsif ($scope eq 'group') {
                   6121:                 push(@groups,$key);
1.1270    raeburn  6122:             } elsif ($scope eq 'ip') {
                   6123:                 push(@ips,$key);
1.765     albertel 6124:             }
                   6125:         }
                   6126:         if ($public) {
                   6127:             return 'ok';
1.1270    raeburn  6128:         } elsif (@ips > 0) {
                   6129:             my $allowed;
                   6130:             foreach my $ipkey (@ips) {
                   6131:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6132:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6133:                         $allowed = 1;
                   6134:                         last; 
                   6135:                     }
                   6136:                 }
                   6137:             }
                   6138:             if ($allowed) {
                   6139:                 return 'ok';
                   6140:             }
1.765     albertel 6141:         }
                   6142:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6143:             if ($guest) {
                   6144:                 return $guest;
                   6145:             }
                   6146:         } else {
                   6147:             if (@domains > 0) {
                   6148:                 foreach my $domkey (@domains) {
                   6149:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6150:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6151:                             return 'ok';
                   6152:                         }
                   6153:                     }
                   6154:                 }
                   6155:             }
                   6156:             if (@users > 0) {
                   6157:                 foreach my $userkey (@users) {
1.865     raeburn  6158:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6159:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6160:                             if (ref($item) eq 'HASH') {
                   6161:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6162:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6163:                                     return 'ok';
                   6164:                                 }
                   6165:                             }
                   6166:                         }
                   6167:                     } 
1.765     albertel 6168:                 }
                   6169:             }
                   6170:             my %roleshash;
                   6171:             my @courses_and_groups = @courses;
                   6172:             push(@courses_and_groups,@groups); 
                   6173:             if (@courses_and_groups > 0) {
                   6174:                 my (%allgroups,%allroles); 
                   6175:                 my ($start,$end,$role,$sec,$group);
                   6176:                 foreach my $envkey (%env) {
1.1060    raeburn  6177:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6178:                         my $cid = $2.'_'.$3; 
                   6179:                         if ($1 eq 'gr') {
                   6180:                             $group = $4;
                   6181:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6182:                         } else {
                   6183:                             if ($4 eq '') {
                   6184:                                 $sec = 'none';
                   6185:                             } else {
                   6186:                                 $sec = $4;
                   6187:                             }
                   6188:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6189:                         }
1.811     albertel 6190:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6191:                         my $cid = $2.'_'.$3;
                   6192:                         if ($4 eq '') {
                   6193:                             $sec = 'none';
                   6194:                         } else {
                   6195:                             $sec = $4;
                   6196:                         }
                   6197:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6198:                     }
                   6199:                 }
                   6200:                 if (keys(%allroles) == 0) {
                   6201:                     return;
                   6202:                 }
                   6203:                 foreach my $key (@courses_and_groups) {
                   6204:                     my %content = %{$$access_hash{$key}};
                   6205:                     my $cnum = $content{'number'};
                   6206:                     my $cdom = $content{'domain'};
                   6207:                     my $cid = $cdom.'_'.$cnum;
                   6208:                     if (!exists($allroles{$cid})) {
                   6209:                         next;
                   6210:                     }    
                   6211:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6212:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6213:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6214:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6215:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6216:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6217:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6218:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6219:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6220:                                         if (grep/^all$/,@sections) {
                   6221:                                             return 'ok';
                   6222:                                         } else {
                   6223:                                             if (grep/^$sec$/,@sections) {
                   6224:                                                 return 'ok';
                   6225:                                             }
                   6226:                                         }
                   6227:                                     }
                   6228:                                 }
                   6229:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6230:                                     if (grep/^none$/,@groups) {
                   6231:                                         return 'ok';
                   6232:                                     }
                   6233:                                 } else {
                   6234:                                     if (grep/^all$/,@groups) {
                   6235:                                         return 'ok';
                   6236:                                     } 
                   6237:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6238:                                         if (grep/^$group$/,@groups) {
                   6239:                                             return 'ok';
                   6240:                                         }
                   6241:                                     }
                   6242:                                 } 
                   6243:                             }
                   6244:                         }
                   6245:                     }
                   6246:                 }
                   6247:             }
                   6248:             if ($guest) {
                   6249:                 return $guest;
                   6250:             }
                   6251:         }
                   6252:     }
                   6253:     return;
                   6254: }
                   6255: 
                   6256: sub course_group_datechecker {
                   6257:     my ($dates,$now,$status) = @_;
                   6258:     my ($start,$end) = split(/\./,$dates);
                   6259:     if (!$start && !$end) {
                   6260:         return 'ok';
                   6261:     }
                   6262:     if (grep/^active$/,@{$status}) {
                   6263:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6264:             return 'ok';
                   6265:         }
                   6266:     }
                   6267:     if (grep/^previous$/,@{$status}) {
                   6268:         if ($end > $now ) {
                   6269:             return 'ok';
                   6270:         }
                   6271:     }
                   6272:     if (grep/^future$/,@{$status}) {
                   6273:         if ($start > $now) {
                   6274:             return 'ok';
                   6275:         }
                   6276:     }
                   6277:     return; 
                   6278: }
                   6279: 
                   6280: sub parse_portfolio_url {
                   6281:     my ($url) = @_;
                   6282: 
                   6283:     my ($type,$udom,$unum,$group,$file_name);
                   6284:     
1.823     albertel 6285:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6286: 	$type = 1;
                   6287:         $udom = $1;
                   6288:         $unum = $2;
                   6289:         $file_name = $3;
1.823     albertel 6290:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6291: 	$type = 2;
                   6292:         $udom = $1;
                   6293:         $unum = $2;
                   6294:         $group = $3;
                   6295:         $file_name = $3.'/'.$4;
                   6296:     }
                   6297:     if (wantarray) {
                   6298: 	return ($type,$udom,$unum,$file_name,$group);
                   6299:     }
                   6300:     return $type;
                   6301: }
                   6302: 
                   6303: sub is_portfolio_url {
                   6304:     my ($url) = @_;
                   6305:     return scalar(&parse_portfolio_url($url));
                   6306: }
                   6307: 
1.798     raeburn  6308: sub is_portfolio_file {
                   6309:     my ($file) = @_;
1.820     raeburn  6310:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6311:         return 1;
                   6312:     }
                   6313:     return;
                   6314: }
                   6315: 
1.976     raeburn  6316: sub usertools_access {
1.1084    raeburn  6317:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6318:     my ($access,%tools);
                   6319:     if ($context eq '') {
                   6320:         $context = 'tools';
                   6321:     }
                   6322:     if ($context eq 'requestcourses') {
                   6323:         %tools = (
                   6324:                       official   => 1,
                   6325:                       unofficial => 1,
1.1006    raeburn  6326:                       community  => 1,
1.1246    raeburn  6327:                       textbook   => 1,
1.985     raeburn  6328:                  );
1.1183    raeburn  6329:     } elsif ($context eq 'requestauthor') {
                   6330:         %tools = (
                   6331:                       requestauthor => 1,
                   6332:                  );
1.985     raeburn  6333:     } else {
                   6334:         %tools = (
                   6335:                       aboutme   => 1,
                   6336:                       blog      => 1,
1.1177    raeburn  6337:                       webdav    => 1,
1.985     raeburn  6338:                       portfolio => 1,
                   6339:                  );
                   6340:     }
1.976     raeburn  6341:     return if (!defined($tools{$tool}));
                   6342: 
1.1242    raeburn  6343:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6344:         $udom = $env{'user.domain'};
                   6345:         $uname = $env{'user.name'};
                   6346:     }
                   6347: 
1.978     raeburn  6348:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6349:         if ($action ne 'reload') {
1.985     raeburn  6350:             if ($context eq 'requestcourses') {
                   6351:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6352:             } elsif ($context eq 'requestauthor') {
                   6353:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6354:             } else {
                   6355:                 return $env{'environment.availabletools.'.$tool};
                   6356:             }
                   6357:         }
1.976     raeburn  6358:     }
                   6359: 
1.1183    raeburn  6360:     my ($toolstatus,$inststatus,$envkey);
                   6361:     if ($context eq 'requestauthor') {
                   6362:         $envkey = $context; 
                   6363:     } else {
                   6364:         $envkey = $context.'.'.$tool;
                   6365:     }
1.976     raeburn  6366: 
1.985     raeburn  6367:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6368:          ($action ne 'reload')) {
1.1183    raeburn  6369:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6370:         $inststatus = $env{'environment.inststatus'};
                   6371:     } else {
1.1084    raeburn  6372:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6373:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6374:             $inststatus = $userenvref->{'inststatus'};
                   6375:         } else {
1.1183    raeburn  6376:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6377:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6378:             $inststatus = $userenv{'inststatus'};
                   6379:         }
1.976     raeburn  6380:     }
                   6381: 
                   6382:     if ($toolstatus ne '') {
                   6383:         if ($toolstatus) {
                   6384:             $access = 1;
                   6385:         } else {
                   6386:             $access = 0;
                   6387:         }
                   6388:         return $access;
                   6389:     }
                   6390: 
1.1084    raeburn  6391:     my ($is_adv,%domdef);
                   6392:     if (ref($is_advref) eq 'HASH') {
                   6393:         $is_adv = $is_advref->{'is_adv'};
                   6394:     } else {
                   6395:         $is_adv = &is_advanced_user($udom,$uname);
                   6396:     }
                   6397:     if (ref($domdefref) eq 'HASH') {
                   6398:         %domdef = %{$domdefref};
                   6399:     } else {
                   6400:         %domdef = &get_domain_defaults($udom);
                   6401:     }
1.976     raeburn  6402:     if (ref($domdef{$tool}) eq 'HASH') {
                   6403:         if ($is_adv) {
                   6404:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6405:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6406:                     $access = 1;
                   6407:                 } else {
                   6408:                     $access = 0;
                   6409:                 }
                   6410:                 return $access;
                   6411:             }
                   6412:         }
                   6413:         if ($inststatus ne '') {
                   6414:             my ($hasaccess,$hasnoaccess);
                   6415:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6416:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6417:                     if ($domdef{$tool}{$affiliation}) {
                   6418:                         $hasaccess = 1;
                   6419:                     } else {
                   6420:                         $hasnoaccess = 1;
                   6421:                     }
                   6422:                 }
                   6423:             }
                   6424:             if ($hasaccess || $hasnoaccess) {
                   6425:                 if ($hasaccess) {
                   6426:                     $access = 1;
                   6427:                 } elsif ($hasnoaccess) {
                   6428:                     $access = 0; 
                   6429:                 }
                   6430:                 return $access;
                   6431:             }
                   6432:         } else {
                   6433:             if ($domdef{$tool}{'default'} ne '') {
                   6434:                 if ($domdef{$tool}{'default'}) {
                   6435:                     $access = 1;
                   6436:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6437:                     $access = 0;
                   6438:                 }
                   6439:                 return $access;
                   6440:             }
                   6441:         }
                   6442:     } else {
1.1177    raeburn  6443:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6444:             $access = 1;
                   6445:         } else {
                   6446:             $access = 0;
                   6447:         }
1.976     raeburn  6448:         return $access;
                   6449:     }
                   6450: }
                   6451: 
1.1050    raeburn  6452: sub is_course_owner {
                   6453:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6454:     if (($udom eq '') || ($uname eq '')) {
                   6455:         $udom = $env{'user.domain'};
                   6456:         $uname = $env{'user.name'};
                   6457:     }
                   6458:     unless (($udom eq '') || ($uname eq '')) {
                   6459:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6460:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6461:                 return 1;
                   6462:             } else {
                   6463:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6464:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6465:                     return 1;
                   6466:                 }
                   6467:             }
                   6468:         }
                   6469:     }
                   6470:     return;
                   6471: }
                   6472: 
1.976     raeburn  6473: sub is_advanced_user {
                   6474:     my ($udom,$uname) = @_;
1.1085    raeburn  6475:     if ($udom ne '' && $uname ne '') {
                   6476:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6477:             if (wantarray) {
                   6478:                 return ($env{'user.adv'},$env{'user.author'});
                   6479:             } else {
                   6480:                 return $env{'user.adv'};
                   6481:             }
1.1085    raeburn  6482:         }
                   6483:     }
1.976     raeburn  6484:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6485:     my %allroles;
1.1128    raeburn  6486:     my ($is_adv,$is_author);
1.976     raeburn  6487:     foreach my $role (keys(%roleshash)) {
                   6488:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6489:         my $area = '/'.$tdomain.'/'.$trest;
                   6490:         if ($sec ne '') {
                   6491:             $area .= '/'.$sec;
                   6492:         }
                   6493:         if (($area ne '') && ($trole ne '')) {
                   6494:             my $spec=$trole.'.'.$area;
                   6495:             if ($trole =~ /^cr\//) {
                   6496:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6497:             } elsif ($trole ne 'gr') {
                   6498:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6499:             }
1.1128    raeburn  6500:             if ($trole eq 'au') {
                   6501:                 $is_author = 1;
                   6502:             }
1.976     raeburn  6503:         }
                   6504:     }
                   6505:     foreach my $role (keys(%allroles)) {
                   6506:         last if ($is_adv);
                   6507:         foreach my $item (split(/:/,$allroles{$role})) {
                   6508:             if ($item ne '') {
                   6509:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6510:                 if ($privilege eq 'adv') {
                   6511:                     $is_adv = 1;
                   6512:                     last;
                   6513:                 }
                   6514:             }
                   6515:         }
                   6516:     }
1.1128    raeburn  6517:     if (wantarray) {
                   6518:         return ($is_adv,$is_author);
                   6519:     }
1.976     raeburn  6520:     return $is_adv;
                   6521: }
1.798     raeburn  6522: 
1.1035    raeburn  6523: sub check_can_request {
1.1036    raeburn  6524:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6525:     my $canreq = 0;
                   6526:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6527:     my @options = ('approval','validate','autolimit');
                   6528:     my $optregex = join('|',@options);
                   6529:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6530:         foreach my $type (@{$types}) {
                   6531:             if (&usertools_access($env{'user.name'},
                   6532:                                   $env{'user.domain'},
                   6533:                                   $type,undef,'requestcourses')) {
                   6534:                 $canreq ++;
1.1036    raeburn  6535:                 if (ref($request_domains) eq 'HASH') {
                   6536:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6537:                 }
1.1035    raeburn  6538:                 if ($dom eq $env{'user.domain'}) {
                   6539:                     $can_request->{$type} = 1;
                   6540:                 }
                   6541:             }
                   6542:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6543:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6544:                 if (@curr > 0) {
1.1036    raeburn  6545:                     foreach my $item (@curr) {
                   6546:                         if (ref($request_domains) eq 'HASH') {
                   6547:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6548:                             if ($otherdom ne '') {
                   6549:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6550:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6551:                                         push(@{$request_domains->{$type}},$otherdom);
                   6552:                                     }
                   6553:                                 } else {
                   6554:                                     push(@{$request_domains->{$type}},$otherdom);
                   6555:                                 }
                   6556:                             }
                   6557:                         }
                   6558:                     }
                   6559:                     unless($dom eq $env{'user.domain'}) {
                   6560:                         $canreq ++;
1.1035    raeburn  6561:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6562:                             $can_request->{$type} = 1;
                   6563:                         }
                   6564:                     }
                   6565:                 }
                   6566:             }
                   6567:         }
                   6568:     }
                   6569:     return $canreq;
                   6570: }
                   6571: 
1.341     www      6572: # ---------------------------------------------- Custom access rule evaluation
                   6573: 
                   6574: sub customaccess {
                   6575:     my ($priv,$uri)=@_;
1.807     albertel 6576:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6577:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6578:     $udom = &LONCAPA::clean_domain($udom);
                   6579:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6580:     my $access=0;
1.800     albertel 6581:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6582: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6583: 	if ($type eq 'user') {
                   6584: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6585: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6586: 		if ($tdom) {
                   6587: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6588: 		}
1.896     albertel 6589: 		if ($tuname) {
                   6590: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6591: 		}
                   6592: 		$access=($effect eq 'allow');
                   6593: 		last;
                   6594: 	    }
                   6595: 	} else {
                   6596: 	    if ($role) {
                   6597: 		if ($role ne $urole) { next; }
                   6598: 	    }
                   6599: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6600: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6601: 		if ($tdom) {
                   6602: 		    if ($tdom ne $udom) { next; }
                   6603: 		}
                   6604: 		if ($tcrs) {
                   6605: 		    if ($tcrs ne $ucrs) { next; }
                   6606: 		}
                   6607: 		if ($tsec) {
                   6608: 		    if ($tsec ne $usec) { next; }
                   6609: 		}
                   6610: 		$access=($effect eq 'allow');
                   6611: 		last;
                   6612: 	    }
                   6613: 	    if ($realm eq '' && $role eq '') {
                   6614: 		$access=($effect eq 'allow');
                   6615: 	    }
1.402     bowersj2 6616: 	}
1.341     www      6617:     }
                   6618:     return $access;
                   6619: }
                   6620: 
1.103     harris41 6621: # ------------------------------------------------- Check for a user privilege
1.12      www      6622: 
                   6623: sub allowed {
1.1270    raeburn  6624:     my ($priv,$uri,$symb,$role,$clientip)=@_;
1.705     albertel 6625:     my $ver_orguri=$uri;
1.439     www      6626:     $uri=&deversion($uri);
1.152     www      6627:     my $orguri=$uri;
1.52      www      6628:     $uri=&declutter($uri);
1.809     raeburn  6629: 
1.810     raeburn  6630:     if ($priv eq 'evb') {
                   6631: # Evade communication block restrictions for specified role in a course
                   6632:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6633:             return $1;
                   6634:         } else {
                   6635:             return;
                   6636:         }
                   6637:     }
                   6638: 
1.620     albertel 6639:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6640: # Free bre access to adm and meta resources
1.775     albertel 6641:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6642: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6643: 	&& ($priv eq 'bre')) {
1.14      www      6644: 	return 'F';
1.159     www      6645:     }
                   6646: 
1.545     banghart 6647: # Free bre access to user's own portfolio contents
1.714     raeburn  6648:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6649:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6650: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6651:         my %setters;
                   6652:         my ($startblock,$endblock) = 
                   6653:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6654:         if ($startblock && $endblock) {
                   6655:             return 'B';
                   6656:         } else {
                   6657:             return 'F';
                   6658:         }
1.545     banghart 6659:     }
                   6660: 
1.762     raeburn  6661: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6662:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6663:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6664:         if (exists($env{'request.course.id'})) {
                   6665:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6666:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6667:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6668:                 my $courseprivid=$env{'request.course.id'};
                   6669:                 $courseprivid=~s/\_/\//;
                   6670:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6671:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6672:                     return $1; 
1.762     raeburn  6673:                 } else {
                   6674:                     if ($env{'request.course.sec'}) {
                   6675:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6676:                     }
                   6677:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6678:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6679:                         return $2;
                   6680:                     }
1.714     raeburn  6681:                 }
                   6682:             }
                   6683:         }
                   6684:     }
                   6685: 
1.159     www      6686: # Free bre to public access
                   6687: 
                   6688:     if ($priv eq 'bre') {
1.238     www      6689:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6690: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6691:            return 'F'; 
                   6692:         }
1.238     www      6693:         if ($copyright eq 'priv') {
                   6694:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6695: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6696: 		return '';
                   6697:             }
                   6698:         }
                   6699:         if ($copyright eq 'domain') {
                   6700:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6701: 	    unless (($env{'user.domain'} eq $1) ||
                   6702:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6703: 		return '';
                   6704:             }
1.262     matthew  6705:         }
1.620     albertel 6706:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6707:             # Library role, so allow browsing of resources in this domain.
                   6708:             return 'F';
1.238     www      6709:         }
1.341     www      6710:         if ($copyright eq 'custom') {
                   6711: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6712:         }
1.14      www      6713:     }
1.264     matthew  6714:     # Domain coordinator is trying to create a course
1.620     albertel 6715:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6716:         # uri is the requested domain in this case.
                   6717:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6718:         # a role of dc for the domain in question.
1.620     albertel 6719:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6720:     }
1.29      www      6721: 
1.52      www      6722:     my $thisallowed='';
                   6723:     my $statecond=0;
                   6724:     my $courseprivid='';
                   6725: 
1.1039    raeburn  6726:     my $ownaccess;
1.1043    raeburn  6727:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6728:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6729:         if ($uri eq '') {
                   6730:             $ownaccess = 1;
                   6731:         } else {
                   6732:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6733:                 my $udom = $env{'user.domain'};
                   6734:                 my $uname = $env{'user.name'};
                   6735:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6736:                     $ownaccess = 1;
1.1040    raeburn  6737:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6738:                     unless ($uri =~ m{\.\./}) {
                   6739:                         $ownaccess = 1;
                   6740:                     }
                   6741:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6742:                     my $now = time;
                   6743:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6744:                         my $adom = $1;
                   6745:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6746:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6747:                                 my ($start,$end) = split('.',$env{$key});
                   6748:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6749:                                     $ownaccess = 1;
                   6750:                                     last;
                   6751:                                 }
                   6752:                             }
                   6753:                         }
                   6754:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6755:                         my $adom = $1;
                   6756:                         my $aname = $2;
1.1042    raeburn  6757:                         foreach my $role ('ca','aa') { 
                   6758:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6759:                                 my ($start,$end) =
                   6760:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6761:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6762:                                     $ownaccess = 1;
                   6763:                                     last;
                   6764:                                 }
1.1039    raeburn  6765:                             }
                   6766:                         }
                   6767:                     }
                   6768:                 }
                   6769:             }
                   6770:         }
                   6771:     }
                   6772: 
1.52      www      6773: # Course
                   6774: 
1.620     albertel 6775:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6776:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6777:             $thisallowed.=$1;
                   6778:         }
1.52      www      6779:     }
1.29      www      6780: 
1.52      www      6781: # Domain
                   6782: 
1.620     albertel 6783:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6784:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6785:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6786:             $thisallowed.=$1;
                   6787:         }
1.12      www      6788:     }
1.52      www      6789: 
1.1141    raeburn  6790: # User who is not author or co-author might still be able to edit
                   6791: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6792:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6793:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6794:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6795:             $thisallowed.=$1;
                   6796:         }
                   6797:     }
                   6798: 
1.52      www      6799: # Course: uri itself is a course
1.66      www      6800:     my $courseuri=$uri;
                   6801:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6802:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6803: 
1.620     albertel 6804:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6805:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6806:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6807:             $thisallowed.=$1;
                   6808:         }
1.12      www      6809:     }
1.29      www      6810: 
1.665     albertel 6811: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6812: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6813:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6814: 	$thisallowed='';
1.671     raeburn  6815:         my ($match)=&is_on_map($uri);
                   6816:         if ($match) {
                   6817:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6818:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6819:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6820:                 if (@blockers > 0) {
                   6821:                     $thisallowed = 'B';
                   6822:                 } else {
                   6823:                     $thisallowed.=$1;
                   6824:                 }
1.671     raeburn  6825:             }
                   6826:         } else {
1.705     albertel 6827:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6828:             if ($refuri) {
                   6829:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6830:                     $thisallowed='F';
1.671     raeburn  6831:                 } else {
                   6832:                     $refuri=&declutter($refuri);
                   6833:                     my ($match) = &is_on_map($refuri);
                   6834:                     if ($match) {
1.1162    raeburn  6835:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6836:                         if (@blockers > 0) {
                   6837:                             $thisallowed = 'B';
                   6838:                         } else {
                   6839:                             $thisallowed='F';
                   6840:                         }
1.671     raeburn  6841:                     }
1.669     raeburn  6842:                 }
1.671     raeburn  6843:             }
                   6844:         }
1.314     www      6845:     }
1.492     albertel 6846: 
1.766     albertel 6847:     if ($priv eq 'bre'
                   6848: 	&& $thisallowed ne 'F' 
                   6849: 	&& $thisallowed ne '2'
                   6850: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  6851: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 6852:     }
1.1250    raeburn  6853: 
1.52      www      6854: # Full access at system, domain or course-wide level? Exit.
1.29      www      6855:     if ($thisallowed=~/F/) {
                   6856: 	return 'F';
                   6857:     }
                   6858: 
1.52      www      6859: # If this is generating or modifying users, exit with special codes
1.29      www      6860: 
1.643     www      6861:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6862: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6863: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6864: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6865: 	    unless ($auname) { return $thisallowed; }
                   6866: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6867: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6868: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6869: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6870: 	}
1.52      www      6871: 	return $thisallowed;
                   6872:     }
                   6873: #
1.103     harris41 6874: # Gathered so far: system, domain and course wide privileges
1.52      www      6875: #
                   6876: # Course: See if uri or referer is an individual resource that is part of 
                   6877: # the course
                   6878: 
1.620     albertel 6879:     if ($env{'request.course.id'}) {
1.232     www      6880: 
1.620     albertel 6881:        $courseprivid=$env{'request.course.id'};
                   6882:        if ($env{'request.course.sec'}) {
                   6883:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6884:        }
                   6885:        $courseprivid=~s/\_/\//;
                   6886:        my $checkreferer=1;
1.232     www      6887:        my ($match,$cond)=&is_on_map($uri);
                   6888:        if ($match) {
                   6889:            $statecond=$cond;
1.620     albertel 6890:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6891:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6892:                my $value = $1;
                   6893:                if ($priv eq 'bre') {
                   6894:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6895:                    if (@blockers > 0) {
                   6896:                        $thisallowed = 'B';
                   6897:                    } else {
                   6898:                        $thisallowed.=$value;
                   6899:                    }
                   6900:                } else {
                   6901:                    $thisallowed.=$value;
                   6902:                }
1.52      www      6903:                $checkreferer=0;
                   6904:            }
1.29      www      6905:        }
1.83      www      6906:        
1.148     www      6907:        if ($checkreferer) {
1.620     albertel 6908: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6909:             unless ($refuri) {
1.800     albertel 6910:                 foreach my $key (keys(%env)) {
                   6911: 		    if ($key=~/^httpref\..*\*/) {
                   6912: 			my $pattern=$key;
1.156     www      6913:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6914:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6915:                         $pattern=~s/\//\\\//g;
1.152     www      6916:                         if ($orguri=~/$pattern/) {
1.800     albertel 6917: 			    $refuri=$env{$key};
1.148     www      6918:                         }
                   6919:                     }
1.191     harris41 6920:                 }
1.148     www      6921:             }
1.232     www      6922: 
1.148     www      6923:          if ($refuri) { 
1.152     www      6924: 	  $refuri=&declutter($refuri);
1.232     www      6925:           my ($match,$cond)=&is_on_map($refuri);
                   6926:             if ($match) {
                   6927:               my $refstatecond=$cond;
1.620     albertel 6928:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6929:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6930:                   my $value = $1;
                   6931:                   if ($priv eq 'bre') {
                   6932:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6933:                       if (@blockers > 0) {
                   6934:                           $thisallowed = 'B';
                   6935:                       } else {
                   6936:                           $thisallowed.=$value;
                   6937:                       }
                   6938:                   } else {
                   6939:                       $thisallowed.=$value;
                   6940:                   }
1.53      www      6941:                   $uri=$refuri;
                   6942:                   $statecond=$refstatecond;
1.52      www      6943:               }
                   6944:           }
1.148     www      6945:         }
1.29      www      6946:        }
1.52      www      6947:    }
1.29      www      6948: 
1.52      www      6949: #
1.103     harris41 6950: # Gathered now: all privileges that could apply, and condition number
1.52      www      6951: # 
                   6952: #
                   6953: # Full or no access?
                   6954: #
1.29      www      6955: 
1.52      www      6956:     if ($thisallowed=~/F/) {
                   6957: 	return 'F';
                   6958:     }
1.29      www      6959: 
1.52      www      6960:     unless ($thisallowed) {
                   6961:         return '';
                   6962:     }
1.29      www      6963: 
1.52      www      6964: # Restrictions exist, deal with them
                   6965: #
                   6966: #   C:according to course preferences
                   6967: #   R:according to resource settings
                   6968: #   L:unless locked
                   6969: #   X:according to user session state
                   6970: #
                   6971: 
                   6972: # Possibly locked functionality, check all courses
1.54      www      6973: # Locks might take effect only after 10 minutes cache expiration for other
                   6974: # courses, and 2 minutes for current course
1.52      www      6975: 
                   6976:     my $envkey;
                   6977:     if ($thisallowed=~/L/) {
1.1000    raeburn  6978:         foreach $envkey (keys(%env)) {
1.54      www      6979:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6980:                my $courseid=$2;
                   6981:                my $roleid=$1.'.'.$2;
1.92      www      6982:                $courseid=~s/^\///;
1.54      www      6983:                my $expiretime=600;
1.620     albertel 6984:                if ($env{'request.role'} eq $roleid) {
1.54      www      6985: 		  $expiretime=120;
                   6986:                }
                   6987: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6988:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6989:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6990: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6991:                }
1.620     albertel 6992:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6993:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6994: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6995:                        &log($env{'user.domain'},$env{'user.name'},
                   6996:                             $env{'user.home'},
1.57      www      6997:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6998:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6999:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7000: 		       return '';
                   7001:                    }
                   7002:                }
1.620     albertel 7003:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7004:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7005: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7006:                        &log($env{'user.domain'},$env{'user.name'},
                   7007:                             $env{'user.home'},
1.57      www      7008:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7009:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7010:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7011: 		       return '';
                   7012:                    }
                   7013:                }
                   7014: 	   }
1.29      www      7015:        }
1.52      www      7016:     }
                   7017:    
                   7018: #
                   7019: # Rest of the restrictions depend on selected course
                   7020: #
                   7021: 
1.620     albertel 7022:     unless ($env{'request.course.id'}) {
1.766     albertel 7023: 	if ($thisallowed eq 'A') {
                   7024: 	    return 'A';
1.814     raeburn  7025:         } elsif ($thisallowed eq 'B') {
                   7026:             return 'B';
1.766     albertel 7027: 	} else {
                   7028: 	    return '1';
                   7029: 	}
1.52      www      7030:     }
1.29      www      7031: 
1.52      www      7032: #
                   7033: # Now user is definitely in a course
                   7034: #
1.53      www      7035: 
                   7036: 
                   7037: # Course preferences
                   7038: 
                   7039:    if ($thisallowed=~/C/) {
1.620     albertel 7040:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7041:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7042:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7043: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7044: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7045: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7046: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7047: 			$env{'request.course.id'});
                   7048: 	   }
1.237     www      7049:            return '';
                   7050:        }
                   7051: 
1.620     albertel 7052:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7053: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7054: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7055: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7056: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7057: 			$env{'request.course.id'});
                   7058: 	   }
1.54      www      7059:            return '';
                   7060:        }
1.53      www      7061:    }
                   7062: 
                   7063: # Resource preferences
                   7064: 
                   7065:    if ($thisallowed=~/R/) {
1.620     albertel 7066:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7067:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7068: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7069: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7070: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7071: 	   }
                   7072: 	   return '';
1.54      www      7073:        }
1.53      www      7074:    }
1.30      www      7075: 
1.246     www      7076: # Restricted by state or randomout?
1.30      www      7077: 
1.52      www      7078:    if ($thisallowed=~/X/) {
1.620     albertel 7079:       if ($env{'acc.randomout'}) {
1.579     albertel 7080: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7081:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7082:             return ''; 
                   7083:          }
1.247     www      7084:       }
                   7085:       if (&condval($statecond)) {
1.52      www      7086: 	 return '2';
                   7087:       } else {
                   7088:          return '';
                   7089:       }
                   7090:    }
1.30      www      7091: 
1.766     albertel 7092:     if ($thisallowed eq 'A') {
                   7093: 	return 'A';
1.814     raeburn  7094:     } elsif ($thisallowed eq 'B') {
                   7095:         return 'B';
1.766     albertel 7096:     }
1.52      www      7097:    return 'F';
1.232     www      7098: }
1.1162    raeburn  7099: 
1.1192    raeburn  7100: # ------------------------------------------- Check construction space access
                   7101: 
                   7102: sub constructaccess {
                   7103:     my ($url,$setpriv)=@_;
                   7104: 
                   7105: # We do not allow editing of previous versions of files
                   7106:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7107: 
                   7108: # Get username and domain from URL
                   7109:     my ($ownername,$ownerdomain,$ownerhome);
                   7110: 
                   7111:     ($ownerdomain,$ownername) =
                   7112:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   7113: 
                   7114: # The URL does not really point to any authorspace, forget it
                   7115:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7116: 
                   7117: # Now we need to see if the user has access to the authorspace of
                   7118: # $ownername at $ownerdomain
                   7119: 
                   7120:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7121: # Real author for this?
                   7122:        $ownerhome = $env{'user.home'};
                   7123:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7124:           return ($ownername,$ownerdomain,$ownerhome);
                   7125:        }
                   7126:     } else {
                   7127: # Co-author for this?
                   7128:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7129:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7130:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7131:             return ($ownername,$ownerdomain,$ownerhome);
                   7132:         }
                   7133:     }
                   7134: 
                   7135: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7136: # we might as well leave
                   7137:    unless ($setpriv) { return ''; }
                   7138: 
                   7139: # Backdoor access?
                   7140:     my $allowed=&allowed('eco',$ownerdomain);
                   7141: # Nope
                   7142:     unless ($allowed) { return ''; }
                   7143: # Looks like we may have access, but could be locked by the owner of the construction space
                   7144:     if ($allowed eq 'U') {
                   7145:         my %blocked=&get('environment',['domcoord.author'],
                   7146:                          $ownerdomain,$ownername);
                   7147: # Is blocked by owner
                   7148:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7149:     }
                   7150:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7151: # Grant temporary access
                   7152:         my $then=$env{'user.login.time'};
1.1209    raeburn  7153:         my $update=$env{'user.update.time'};
1.1192    raeburn  7154:         if (!$update) { $update = $then; }
                   7155:         my $refresh=$env{'user.refresh.time'};
                   7156:         if (!$refresh) { $refresh = $update; }
                   7157:         my $now = time;
                   7158:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7159:                            $now,'ca','constructaccess');
                   7160:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7161:         return($ownername,$ownerdomain,$ownerhome);
                   7162:     }
                   7163: # No business here
                   7164:     return '';
                   7165: }
                   7166: 
1.1162    raeburn  7167: sub get_comm_blocks {
                   7168:     my ($cdom,$cnum) = @_;
                   7169:     if ($cdom eq '' || $cnum eq '') {
                   7170:         return unless ($env{'request.course.id'});
                   7171:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7172:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7173:     }
                   7174:     my %commblocks;
                   7175:     my $hashid=$cdom.'_'.$cnum;
                   7176:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7177:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7178:         %commblocks = %{$blocksref};
                   7179:     } else {
                   7180:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7181:         my $cachetime = 600;
                   7182:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7183:     }
                   7184:     return %commblocks;
                   7185: }
                   7186: 
                   7187: sub has_comm_blocking {
                   7188:     my ($priv,$symb,$uri,$blocks) = @_;
                   7189:     return unless ($env{'request.course.id'});
                   7190:     return unless ($priv eq 'bre');
                   7191:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7192:     my %commblocks;
                   7193:     if (ref($blocks) eq 'HASH') {
                   7194:         %commblocks = %{$blocks};
                   7195:     } else {
                   7196:         %commblocks = &get_comm_blocks();
                   7197:     }
                   7198:     return unless (keys(%commblocks) > 0);
                   7199:     if (!$symb) { $symb=&symbread($uri,1); }
                   7200:     my ($map,$resid,undef)=&decode_symb($symb);
                   7201:     my %tocheck = (
                   7202:                     maps      => $map,
                   7203:                     resources => $symb,
                   7204:                   );
                   7205:     my @blockers;
                   7206:     my $now = time;
1.1163    raeburn  7207:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7208:     foreach my $block (keys(%commblocks)) {
                   7209:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7210:             my ($start,$end) = ($1,$2);
                   7211:             if ($start <= $now && $end >= $now) {
                   7212:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7213:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7214:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7215:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7216:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7217:                                     push(@blockers,$block);
                   7218:                                 }
                   7219:                             }
                   7220:                         }
                   7221:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7222:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7223:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7224:                                     push(@blockers,$block);
                   7225:                                 }
                   7226:                             }
                   7227:                         }
                   7228:                     }
                   7229:                 }
                   7230:             }
                   7231:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7232:             my $item = $1;
1.1163    raeburn  7233:             my @to_test;
1.1162    raeburn  7234:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7235:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7236:                     my $check_interval;
                   7237:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7238:                         my @interval;
                   7239:                         my $type = 'map';
                   7240:                         if ($item eq 'course') {
                   7241:                             $type = 'course';
                   7242:                             @interval=&EXT("resource.0.interval");
                   7243:                         } else {
                   7244:                             if ($item =~ /___\d+___/) {
                   7245:                                 $type = 'resource';
                   7246:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7247:                                 if (ref($navmap)) {                        
                   7248:                                     my $res = $navmap->getBySymb($item); 
                   7249:                                     push(@to_test,$res);
                   7250:                                 }
1.1162    raeburn  7251:                             } else {
                   7252:                                 my $mapsymb = &symbread($item,1);
                   7253:                                 if ($mapsymb) {
                   7254:                                     if (ref($navmap)) {
                   7255:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7256:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7257:                                         foreach my $res (@to_test) {
1.1162    raeburn  7258:                                             my $symb = $res->symb();
                   7259:                                             next if ($symb eq $mapsymb);
                   7260:                                             if ($symb ne '') {
                   7261:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7262:                                                 last;
                   7263:                                             }
                   7264:                                         }
                   7265:                                     }
                   7266:                                 }
                   7267:                             }
                   7268:                         }
                   7269:                         if ($interval[0] =~ /\d+/) {
                   7270:                             my $first_access;
                   7271:                             if ($type eq 'resource') {
                   7272:                                 $first_access=&get_first_access($interval[1],$item);
                   7273:                             } elsif ($type eq 'map') {
                   7274:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7275:                             } else {
                   7276:                                 $first_access=&get_first_access($interval[1]);
                   7277:                             }
                   7278:                             if ($first_access) {
                   7279:                                 my $timesup = $first_access+$interval[0];
                   7280:                                 if ($timesup > $now) {
1.1163    raeburn  7281:                                     foreach my $res (@to_test) {
                   7282:                                         if ($res->is_problem()) {
                   7283:                                             if ($res->completable()) {
                   7284:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7285:                                                     push(@blockers,$block);
                   7286:                                                 }
                   7287:                                                 last;
                   7288:                                             }
                   7289:                                         }
1.1162    raeburn  7290:                                     }
                   7291:                                 }
                   7292:                             }
                   7293:                         }
                   7294:                     }
                   7295:                 }
                   7296:             }
                   7297:         }
                   7298:     }
                   7299:     return @blockers;
                   7300: }
                   7301: 
                   7302: sub check_docs_block {
                   7303:     my ($docsblock,$tocheck) =@_;
                   7304:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7305:         return;
                   7306:     }
                   7307:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7308:         if ($tocheck->{'maps'}) {
                   7309:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7310:                 return 1;
                   7311:             }
                   7312:         }
                   7313:     }
                   7314:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7315:         if ($tocheck->{'resources'}) {
                   7316:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7317:                 return 1;
                   7318:             }
                   7319:         }
                   7320:     }
                   7321:     return;
                   7322: }
                   7323: 
1.1133    foxr     7324: #
                   7325: #   Removes the versino from a URI and
                   7326: #   splits it in to its filename and path to the filename.
                   7327: #   Seems like File::Basename could have done this more clearly.
                   7328: #   Parameters:
                   7329: #      $uri   - input URI
                   7330: #   Returns:
                   7331: #     Two element list consisting of 
                   7332: #     $pathname  - the URI up to and excluding the trailing /
                   7333: #     $filename  - The part of the URI following the last /
                   7334: #  NOTE:
                   7335: #    Another realization of this is simply:
                   7336: #    use File::Basename;
                   7337: #    ...
                   7338: #    $uri = shift;
                   7339: #    $filename = basename($uri);
                   7340: #    $path     = dirname($uri);
                   7341: #    return ($filename, $path);
                   7342: #
                   7343: #     The implementation below is probably faster however.
                   7344: #
1.710     albertel 7345: sub split_uri_for_cond {
                   7346:     my $uri=&deversion(&declutter(shift));
                   7347:     my @uriparts=split(/\//,$uri);
                   7348:     my $filename=pop(@uriparts);
                   7349:     my $pathname=join('/',@uriparts);
                   7350:     return ($pathname,$filename);
                   7351: }
1.232     www      7352: # --------------------------------------------------- Is a resource on the map?
                   7353: 
                   7354: sub is_on_map {
1.710     albertel 7355:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7356:     #Trying to find the conditional for the file
1.620     albertel 7357:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7358: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7359:     if ($match) {
1.289     bowersj2 7360: 	return (1,$1);
                   7361:     } else {
1.434     www      7362: 	return (0,0);
1.289     bowersj2 7363:     }
1.12      www      7364: }
                   7365: 
1.427     www      7366: # --------------------------------------------------------- Get symb from alias
                   7367: 
                   7368: sub get_symb_from_alias {
                   7369:     my $symb=shift;
                   7370:     my ($map,$resid,$url)=&decode_symb($symb);
                   7371: # Already is a symb
                   7372:     if ($url) { return $symb; }
                   7373: # Must be an alias
                   7374:     my $aliassymb='';
                   7375:     my %bighash;
1.620     albertel 7376:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7377:                             &GDBM_READER(),0640)) {
                   7378:         my $rid=$bighash{'mapalias_'.$symb};
                   7379: 	if ($rid) {
                   7380: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7381: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7382: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7383: 	}
                   7384:         untie %bighash;
                   7385:     }
                   7386:     return $aliassymb;
                   7387: }
                   7388: 
1.12      www      7389: # ----------------------------------------------------------------- Define Role
                   7390: 
                   7391: sub definerole {
                   7392:   if (allowed('mcr','/')) {
                   7393:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7394:     foreach my $role (split(':',$sysrole)) {
                   7395: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7396:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7397:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7398: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7399:                return "refused:s:$crole&$cqual"; 
                   7400:             }
                   7401:         }
1.191     harris41 7402:     }
1.800     albertel 7403:     foreach my $role (split(':',$domrole)) {
                   7404: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7405:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7406:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7407: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7408:                return "refused:d:$crole&$cqual"; 
                   7409:             }
                   7410:         }
1.191     harris41 7411:     }
1.800     albertel 7412:     foreach my $role (split(':',$courole)) {
                   7413: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7414:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7415:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7416: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7417:                return "refused:c:$crole&$cqual"; 
                   7418:             }
                   7419:         }
1.191     harris41 7420:     }
1.620     albertel 7421:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7422:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7423: 	        "rolesdef_$rolename=".
                   7424:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7425:     return reply($command,$env{'user.home'});
1.12      www      7426:   } else {
                   7427:     return 'refused';
                   7428:   }
1.105     harris41 7429: }
                   7430: 
                   7431: # ---------------- Make a metadata query against the network of library servers
                   7432: 
                   7433: sub metadata_query {
1.1237    raeburn  7434:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7435:     my %rhash;
1.845     albertel 7436:     my %libserv = &all_library();
1.244     matthew  7437:     my @server_list = (defined($server_array) ? @$server_array
                   7438:                                               : keys(%libserv) );
                   7439:     for my $server (@server_list) {
1.1237    raeburn  7440:         my $domains = ''; 
                   7441:         if (ref($domains_hash) eq 'HASH') {
                   7442:             $domains = $domains_hash->{$server}; 
                   7443:         }
1.118     harris41 7444: 	unless ($custom or $customshow) {
1.1237    raeburn  7445: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7446: 	    $rhash{$server}=$reply;
                   7447: 	}
                   7448: 	else {
                   7449: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7450: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7451: 			     $server);
                   7452: 	    $rhash{$server}=$reply;
                   7453: 	}
1.112     harris41 7454:     }
1.118     harris41 7455:     return \%rhash;
1.240     www      7456: }
                   7457: 
                   7458: # ----------------------------------------- Send log queries and wait for reply
                   7459: 
                   7460: sub log_query {
                   7461:     my ($uname,$udom,$query,%filters)=@_;
                   7462:     my $uhome=&homeserver($uname,$udom);
                   7463:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7464:     my $uhost=&hostname($uhome);
1.800     albertel 7465:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7466:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7467:                        $uhome);
1.479     albertel 7468:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7469:     return get_query_reply($queryid);
                   7470: }
                   7471: 
1.818     raeburn  7472: # -------------------------- Update MySQL table for portfolio file
                   7473: 
                   7474: sub update_portfolio_table {
1.821     raeburn  7475:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7476:     if ($group ne '') {
                   7477:         $file_name =~s /^\Q$group\E//;
                   7478:     }
1.818     raeburn  7479:     my $homeserver = &homeserver($uname,$udom);
                   7480:     my $queryid=
1.821     raeburn  7481:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7482:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7483:     my $reply = &get_query_reply($queryid);
                   7484:     return $reply;
                   7485: }
                   7486: 
1.899     raeburn  7487: # -------------------------- Update MySQL allusers table
                   7488: 
                   7489: sub update_allusers_table {
                   7490:     my ($uname,$udom,$names) = @_;
                   7491:     my $homeserver = &homeserver($uname,$udom);
                   7492:     my $queryid=
                   7493:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7494:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7495:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7496:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7497:                'generation='.&escape($names->{'generation'}).'%%'.
                   7498:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7499:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7500:     return;
1.899     raeburn  7501: }
                   7502: 
1.508     raeburn  7503: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7504: 
                   7505: sub fetch_enrollment_query {
1.511     raeburn  7506:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7507:     my $homeserver;
1.547     raeburn  7508:     my $maxtries = 1;
1.508     raeburn  7509:     if ($context eq 'automated') {
                   7510:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7511:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7512:     } else {
                   7513:         $homeserver = &homeserver($cnum,$dom);
                   7514:     }
1.838     albertel 7515:     my $host=&hostname($homeserver);
1.506     raeburn  7516:     my $cmd = '';
1.1000    raeburn  7517:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7518:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7519:     }
                   7520:     $cmd =~ s/%%$//;
                   7521:     $cmd = &escape($cmd);
                   7522:     my $query = 'fetchenrollment';
1.620     albertel 7523:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7524:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7525:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7526:         return 'error: '.$queryid;
                   7527:     }
1.506     raeburn  7528:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7529:     my $tries = 1;
                   7530:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7531:         $reply = &get_query_reply($queryid);
                   7532:         $tries ++;
                   7533:     }
1.526     raeburn  7534:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7535:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7536:     } else {
1.901     albertel 7537:         my @responses = split(/:/,$reply);
1.515     raeburn  7538:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7539:             foreach my $line (@responses) {
                   7540:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7541:                 $$replyref{$key} = $value;
                   7542:             }
                   7543:         } else {
1.1117    foxr     7544:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7545:             foreach my $line (@responses) {
                   7546:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7547:                 $$replyref{$key} = $value;
                   7548:                 if ($value > 0) {
1.800     albertel 7549:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7550:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7551:                         my $destname = $pathname.'/'.$filename;
                   7552:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7553:                         if ($xml_classlist =~ /^error/) {
                   7554:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7555:                         } else {
1.506     raeburn  7556:                             if ( open(FILE,">$destname") ) {
                   7557:                                 print FILE &unescape($xml_classlist);
                   7558:                                 close(FILE);
1.526     raeburn  7559:                             } else {
                   7560:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7561:                             }
                   7562:                         }
                   7563:                     }
                   7564:                 }
                   7565:             }
                   7566:         }
                   7567:         return 'ok';
                   7568:     }
                   7569:     return 'error';
                   7570: }
                   7571: 
1.242     www      7572: sub get_query_reply {
                   7573:     my $queryid=shift;
1.1117    foxr     7574:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7575:     my $reply='';
                   7576:     for (1..100) {
                   7577: 	sleep 2;
                   7578:         if (-e $replyfile.'.end') {
1.448     albertel 7579: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7580: 		$reply = join('',<$fh>);
                   7581: 		close($fh);
1.240     www      7582: 	   } else { return 'error: reply_file_error'; }
1.242     www      7583:            return &unescape($reply);
                   7584: 	}
1.240     www      7585:     }
1.242     www      7586:     return 'timeout:'.$queryid;
1.240     www      7587: }
                   7588: 
                   7589: sub courselog_query {
1.241     www      7590: #
                   7591: # possible filters:
                   7592: # url: url or symb
                   7593: # username
                   7594: # domain
                   7595: # action: view, submit, grade
                   7596: # start: timestamp
                   7597: # end: timestamp
                   7598: #
1.240     www      7599:     my (%filters)=@_;
1.620     albertel 7600:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7601:     if ($filters{'url'}) {
                   7602: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7603:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7604:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7605:     }
1.620     albertel 7606:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7607:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7608:     return &log_query($cname,$cdom,'courselog',%filters);
                   7609: }
                   7610: 
                   7611: sub userlog_query {
1.858     raeburn  7612: #
                   7613: # possible filters:
                   7614: # action: log check role
                   7615: # start: timestamp
                   7616: # end: timestamp
                   7617: #
1.240     www      7618:     my ($uname,$udom,%filters)=@_;
                   7619:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7620: }
                   7621: 
1.506     raeburn  7622: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7623: 
                   7624: sub auto_run {
1.508     raeburn  7625:     my ($cnum,$cdom) = @_;
1.876     raeburn  7626:     my $response = 0;
                   7627:     my $settings;
                   7628:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7629:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7630:         $settings = $domconfig{'autoenroll'};
                   7631:         if ($settings->{'run'} eq '1') {
                   7632:             $response = 1;
                   7633:         }
                   7634:     } else {
1.934     raeburn  7635:         my $homeserver;
                   7636:         if (&is_course($cdom,$cnum)) {
                   7637:             $homeserver = &homeserver($cnum,$cdom);
                   7638:         } else {
                   7639:             $homeserver = &domain($cdom,'primary');
                   7640:         }
                   7641:         if ($homeserver ne 'no_host') {
                   7642:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7643:         }
1.876     raeburn  7644:     }
1.506     raeburn  7645:     return $response;
                   7646: }
1.776     albertel 7647: 
1.506     raeburn  7648: sub auto_get_sections {
1.508     raeburn  7649:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7650:     my $homeserver;
                   7651:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7652:         $homeserver = &homeserver($cnum,$cdom);
                   7653:     }
                   7654:     if (!defined($homeserver)) { 
                   7655:         if ($cdom =~ /^$match_domain$/) {
                   7656:             $homeserver = &domain($cdom,'primary');
                   7657:         }
                   7658:     }
                   7659:     my @secs;
                   7660:     if (defined($homeserver)) {
                   7661:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7662:         unless ($response eq 'refused') {
                   7663:             @secs = split(/:/,$response);
                   7664:         }
1.506     raeburn  7665:     }
                   7666:     return @secs;
                   7667: }
1.776     albertel 7668: 
1.506     raeburn  7669: sub auto_new_course {
1.1099    raeburn  7670:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7671:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7672:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7673:     return $response;
                   7674: }
1.776     albertel 7675: 
1.506     raeburn  7676: sub auto_validate_courseID {
1.508     raeburn  7677:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7678:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7679:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7680:     return $response;
                   7681: }
1.776     albertel 7682: 
1.1007    raeburn  7683: sub auto_validate_instcode {
1.1020    raeburn  7684:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7685:     my ($homeserver,$response);
                   7686:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7687:         $homeserver = &homeserver($cnum,$cdom);
                   7688:     }
                   7689:     if (!defined($homeserver)) {
                   7690:         if ($cdom =~ /^$match_domain$/) {
                   7691:             $homeserver = &domain($cdom,'primary');
                   7692:         }
                   7693:     }
1.1065    raeburn  7694:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7695:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  7696:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7697:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7698: }
                   7699: 
1.506     raeburn  7700: sub auto_create_password {
1.873     raeburn  7701:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7702:     my ($homeserver,$response);
1.506     raeburn  7703:     my $create_passwd = 0;
                   7704:     my $authchk = '';
1.873     raeburn  7705:     if ($udom =~ /^$match_domain$/) {
                   7706:         $homeserver = &domain($udom,'primary');
                   7707:     }
                   7708:     if ($homeserver eq '') {
                   7709:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7710:             $homeserver = &homeserver($cnum,$cdom);
                   7711:         }
                   7712:     }
                   7713:     if ($homeserver eq '') {
                   7714:         $authchk = 'nodomain';
1.506     raeburn  7715:     } else {
1.873     raeburn  7716:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7717:         if ($response eq 'refused') {
                   7718:             $authchk = 'refused';
                   7719:         } else {
1.901     albertel 7720:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7721:         }
1.506     raeburn  7722:     }
                   7723:     return ($authparam,$create_passwd,$authchk);
                   7724: }
                   7725: 
1.706     raeburn  7726: sub auto_photo_permission {
                   7727:     my ($cnum,$cdom,$students) = @_;
                   7728:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7729:     my ($outcome,$perm_reqd,$conditions) = 
                   7730: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7731:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7732: 	return (undef,undef);
                   7733:     }
1.706     raeburn  7734:     return ($outcome,$perm_reqd,$conditions);
                   7735: }
                   7736: 
                   7737: sub auto_checkphotos {
                   7738:     my ($uname,$udom,$pid) = @_;
                   7739:     my $homeserver = &homeserver($uname,$udom);
                   7740:     my ($result,$resulttype);
                   7741:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7742: 				   &escape($uname).':'.&escape($pid),
                   7743: 				   $homeserver));
1.709     albertel 7744:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7745: 	return (undef,undef);
                   7746:     }
1.706     raeburn  7747:     if ($outcome) {
                   7748:         ($result,$resulttype) = split(/:/,$outcome);
                   7749:     } 
                   7750:     return ($result,$resulttype);
                   7751: }
                   7752: 
                   7753: sub auto_photochoice {
                   7754:     my ($cnum,$cdom) = @_;
                   7755:     my $homeserver = &homeserver($cnum,$cdom);
                   7756:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7757: 						       &escape($cdom),
                   7758: 						       $homeserver)));
1.709     albertel 7759:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7760: 	return (undef,undef);
                   7761:     }
1.706     raeburn  7762:     return ($update,$comment);
                   7763: }
                   7764: 
                   7765: sub auto_photoupdate {
                   7766:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7767:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7768:     my $host=&hostname($homeserver);
1.706     raeburn  7769:     my $cmd = '';
                   7770:     my $maxtries = 1;
1.800     albertel 7771:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7772:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7773:     }
                   7774:     $cmd =~ s/%%$//;
                   7775:     $cmd = &escape($cmd);
                   7776:     my $query = 'institutionalphotos';
                   7777:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7778:     unless ($queryid=~/^\Q$host\E\_/) {
                   7779:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7780:         return 'error: '.$queryid;
                   7781:     }
                   7782:     my $reply = &get_query_reply($queryid);
                   7783:     my $tries = 1;
                   7784:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7785:         $reply = &get_query_reply($queryid);
                   7786:         $tries ++;
                   7787:     }
                   7788:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7789:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7790:     } else {
                   7791:         my @responses = split(/:/,$reply);
                   7792:         my $outcome = shift(@responses); 
                   7793:         foreach my $item (@responses) {
                   7794:             my ($key,$value) = split(/=/,$item);
                   7795:             $$photo{$key} = $value;
                   7796:         }
                   7797:         return $outcome;
                   7798:     }
                   7799:     return 'error';
                   7800: }
                   7801: 
1.521     raeburn  7802: sub auto_instcode_format {
1.793     albertel 7803:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7804: 	$cat_order) = @_;
1.521     raeburn  7805:     my $courses = '';
1.772     raeburn  7806:     my @homeservers;
1.521     raeburn  7807:     if ($caller eq 'global') {
1.841     albertel 7808: 	my %servers = &get_servers($codedom,'library');
                   7809: 	foreach my $tryserver (keys(%servers)) {
                   7810: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7811: 		push(@homeservers,$tryserver);
                   7812: 	    }
1.584     raeburn  7813:         }
1.1022    raeburn  7814:     } elsif ($caller eq 'requests') {
                   7815:         if ($codedom =~ /^$match_domain$/) {
                   7816:             my $chome = &domain($codedom,'primary');
                   7817:             unless ($chome eq 'no_host') {
                   7818:                 push(@homeservers,$chome);
                   7819:             }
                   7820:         }
1.521     raeburn  7821:     } else {
1.772     raeburn  7822:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7823:     }
1.793     albertel 7824:     foreach my $code (keys(%{$instcodes})) {
                   7825:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7826:     }
                   7827:     chop($courses);
1.772     raeburn  7828:     my $ok_response = 0;
                   7829:     my $response;
                   7830:     while (@homeservers > 0 && $ok_response == 0) {
                   7831:         my $server = shift(@homeservers); 
                   7832:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7833:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7834:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7835: 		split(/:/,$response);
1.772     raeburn  7836:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7837:             push(@{$codetitles},&str2array($codetitles_str));
                   7838:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7839:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7840:             $ok_response = 1;
                   7841:         }
                   7842:     }
                   7843:     if ($ok_response) {
1.521     raeburn  7844:         return 'ok';
1.772     raeburn  7845:     } else {
                   7846:         return $response;
1.521     raeburn  7847:     }
                   7848: }
                   7849: 
1.792     raeburn  7850: sub auto_instcode_defaults {
                   7851:     my ($domain,$returnhash,$code_order) = @_;
                   7852:     my @homeservers;
1.841     albertel 7853: 
                   7854:     my %servers = &get_servers($domain,'library');
                   7855:     foreach my $tryserver (keys(%servers)) {
                   7856: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7857: 	    push(@homeservers,$tryserver);
                   7858: 	}
1.792     raeburn  7859:     }
1.841     albertel 7860: 
1.792     raeburn  7861:     my $response;
1.841     albertel 7862:     foreach my $server (@homeservers) {
1.792     raeburn  7863:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7864:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7865: 	
                   7866: 	foreach my $pair (split(/\&/,$response)) {
                   7867: 	    my ($name,$value)=split(/\=/,$pair);
                   7868: 	    if ($name eq 'code_order') {
                   7869: 		@{$code_order} = split(/\&/,&unescape($value));
                   7870: 	    } else {
                   7871: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7872: 	    }
                   7873: 	}
                   7874: 	return 'ok';
1.792     raeburn  7875:     }
1.841     albertel 7876: 
                   7877:     return $response;
1.1003    raeburn  7878: }
                   7879: 
                   7880: sub auto_possible_instcodes {
1.1007    raeburn  7881:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7882:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7883:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7884:         return;
                   7885:     }
1.1003    raeburn  7886:     my (@homeservers,$uhome);
                   7887:     if (defined(&domain($domain,'primary'))) {
                   7888:         $uhome=&domain($domain,'primary');
                   7889:         push(@homeservers,&domain($domain,'primary'));
                   7890:     } else {
                   7891:         my %servers = &get_servers($domain,'library');
                   7892:         foreach my $tryserver (keys(%servers)) {
                   7893:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7894:                 push(@homeservers,$tryserver);
                   7895:             }
                   7896:         }
                   7897:     }
                   7898:     my $response;
                   7899:     foreach my $server (@homeservers) {
                   7900:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7901:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7902:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7903:             split(':',$response);
                   7904:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7905:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7906:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7907:             my ($name,$value)=split('=',$item);
                   7908:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7909:         }
                   7910:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7911:             my ($name,$value)=split('=',$item);
                   7912:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7913:         }
                   7914:         return 'ok';
                   7915:     }
                   7916:     return $response;
                   7917: }
1.792     raeburn  7918: 
1.1010    raeburn  7919: sub auto_courserequest_checks {
                   7920:     my ($dom) = @_;
1.1020    raeburn  7921:     my ($homeserver,%validations);
                   7922:     if ($dom =~ /^$match_domain$/) {
                   7923:         $homeserver = &domain($dom,'primary');
                   7924:     }
                   7925:     unless ($homeserver eq 'no_host') {
                   7926:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7927:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7928:             my @items = split(/&/,$response);
                   7929:             foreach my $item (@items) {
                   7930:                 my ($key,$value) = split('=',$item);
                   7931:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7932:             }
                   7933:         }
                   7934:     }
1.1010    raeburn  7935:     return %validations; 
                   7936: }
                   7937: 
1.1020    raeburn  7938: sub auto_courserequest_validation {
1.1255    raeburn  7939:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  7940:     my ($homeserver,$response);
                   7941:     if ($dom =~ /^$match_domain$/) {
                   7942:         $homeserver = &domain($dom,'primary');
                   7943:     }
1.1255    raeburn  7944:     unless ($homeserver eq 'no_host') {
                   7945:         my $customdata;
                   7946:         if (ref($custominfo) eq 'HASH') {
                   7947:             $customdata = &freeze_escape($custominfo);
                   7948:         }
1.1020    raeburn  7949:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7950:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  7951:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   7952:                                     $customdata,$homeserver));
1.1020    raeburn  7953:     }
                   7954:     return $response;
                   7955: }
                   7956: 
1.777     albertel 7957: sub auto_validate_class_sec {
1.918     raeburn  7958:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7959:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7960:     my $ownerlist;
                   7961:     if (ref($owners) eq 'ARRAY') {
                   7962:         $ownerlist = join(',',@{$owners});
                   7963:     } else {
                   7964:         $ownerlist = $owners;
                   7965:     }
1.773     raeburn  7966:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7967:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7968:     return $response;
                   7969: }
                   7970: 
1.1248    raeburn  7971: sub auto_crsreq_update {
                   7972:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  7973:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  7974:     my ($homeserver,%crsreqresponse);
                   7975:     if ($cdom =~ /^$match_domain$/) {
                   7976:         $homeserver = &domain($cdom,'primary');
                   7977:     }
                   7978:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   7979:         my $info;
                   7980:         if (ref($inbound) eq 'HASH') {
                   7981:             $info = &freeze_escape($inbound);
                   7982:         }
                   7983:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   7984:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   7985:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  7986:                             &escape($title).':'.&escape($code).':'.
                   7987:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   7988:                             $homeserver);
1.1248    raeburn  7989:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7990:             my @items = split(/&/,$response);
                   7991:             foreach my $item (@items) {
                   7992:                 my ($key,$value) = split('=',$item);
                   7993:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   7994:             }
                   7995:         }
                   7996:     }
                   7997:     return \%crsreqresponse;
                   7998: }
                   7999: 
1.679     raeburn  8000: # ------------------------------------------------------- Course Group routines
                   8001: 
                   8002: sub get_coursegroups {
1.809     raeburn  8003:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8004:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8005: }
                   8006: 
1.679     raeburn  8007: sub modify_coursegroup {
                   8008:     my ($cdom,$cnum,$groupsettings) = @_;
                   8009:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8010: }
                   8011: 
1.809     raeburn  8012: sub toggle_coursegroup_status {
                   8013:     my ($cdom,$cnum,$group,$action) = @_;
                   8014:     my ($from_namespace,$to_namespace);
                   8015:     if ($action eq 'delete') {
                   8016:         $from_namespace = 'coursegroups';
                   8017:         $to_namespace = 'deleted_groups';
                   8018:     } else {
                   8019:         $from_namespace = 'deleted_groups';
                   8020:         $to_namespace = 'coursegroups';
                   8021:     }
                   8022:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8023:     if (my $tmp = &error(%curr_group)) {
                   8024:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8025:         return ('read error',$tmp);
                   8026:     } else {
                   8027:         my %savedsettings = %curr_group; 
1.809     raeburn  8028:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8029:         my $deloutcome;
                   8030:         if ($result eq 'ok') {
1.809     raeburn  8031:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8032:         } else {
                   8033:             return ('write error',$result);
                   8034:         }
                   8035:         if ($deloutcome eq 'ok') {
                   8036:             return 'ok';
                   8037:         } else {
                   8038:             return ('delete error',$deloutcome);
                   8039:         }
                   8040:     }
                   8041: }
                   8042: 
1.679     raeburn  8043: sub modify_group_roles {
1.957     raeburn  8044:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8045:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8046:     my $role = 'gr/'.&escape($userprivs);
                   8047:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8048:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8049:     if ($result eq 'ok') {
                   8050:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8051:     }
1.679     raeburn  8052:     return $result;
                   8053: }
                   8054: 
                   8055: sub modify_coursegroup_membership {
                   8056:     my ($cdom,$cnum,$membership) = @_;
                   8057:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8058:     return $result;
                   8059: }
                   8060: 
1.682     raeburn  8061: sub get_active_groups {
                   8062:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8063:     my $now = time;
                   8064:     my %groups = ();
                   8065:     foreach my $key (keys(%env)) {
1.811     albertel 8066:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8067:             my ($start,$end) = split(/\./,$env{$key});
                   8068:             if (($end!=0) && ($end<$now)) { next; }
                   8069:             if (($start!=0) && ($start>$now)) { next; }
                   8070:             if ($1 eq $cdom && $2 eq $cnum) {
                   8071:                 $groups{$3} = $env{$key} ;
                   8072:             }
                   8073:         }
                   8074:     }
                   8075:     return %groups;
                   8076: }
                   8077: 
1.683     raeburn  8078: sub get_group_membership {
                   8079:     my ($cdom,$cnum,$group) = @_;
                   8080:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8081: }
                   8082: 
                   8083: sub get_users_groups {
                   8084:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8085:     my @usersgroups;
1.683     raeburn  8086:     my $cachetime=1800;
                   8087: 
                   8088:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8089:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8090:     if (defined($cached)) {
1.734     albertel 8091:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8092:     } else {  
                   8093:         $grouplist = '';
1.816     raeburn  8094:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8095:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8096:         my $access_end = $env{'course.'.$courseid.
                   8097:                               '.default_enrollment_end_date'};
                   8098:         my $now = time;
                   8099:         foreach my $key (keys(%roleshash)) {
                   8100:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8101:                 my $group = $1;
                   8102:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8103:                     my $start = $2;
                   8104:                     my $end = $1;
                   8105:                     if ($start == -1) { next; } # deleted from group
                   8106:                     if (($start!=0) && ($start>$now)) { next; }
                   8107:                     if (($end!=0) && ($end<$now)) {
                   8108:                         if ($access_end && $access_end < $now) {
                   8109:                             if ($access_end - $end < 86400) {
                   8110:                                 push(@usersgroups,$group);
1.733     raeburn  8111:                             }
                   8112:                         }
1.817     raeburn  8113:                         next;
1.733     raeburn  8114:                     }
1.817     raeburn  8115:                     push(@usersgroups,$group);
1.683     raeburn  8116:                 }
                   8117:             }
                   8118:         }
1.817     raeburn  8119:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8120:         $grouplist = join(':',@usersgroups);
                   8121:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8122:     }
1.733     raeburn  8123:     return @usersgroups;
1.683     raeburn  8124: }
                   8125: 
                   8126: sub devalidate_getgroups_cache {
                   8127:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8128:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8129: 
1.683     raeburn  8130:     my $hashid="$udom:$uname:$courseid";
                   8131:     &devalidate_cache_new('getgroups',$hashid);
                   8132: }
                   8133: 
1.12      www      8134: # ------------------------------------------------------------------ Plain Text
                   8135: 
                   8136: sub plaintext {
1.988     raeburn  8137:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8138:     if ($short =~ m{^cr/}) {
1.758     albertel 8139: 	return (split('/',$short))[-1];
                   8140:     }
1.742     raeburn  8141:     if (!defined($cid)) {
                   8142:         $cid = $env{'request.course.id'};
                   8143:     }
                   8144:     my %rolenames = (
1.1008    raeburn  8145:                       Course    => 'std',
                   8146:                       Community => 'alt1',
1.742     raeburn  8147:                     );
1.1037    raeburn  8148:     if ($cid ne '') {
                   8149:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8150:             unless ($forcedefault) {
                   8151:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8152:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8153:                 return &Apache::lonlocal::mt($roletext);
                   8154:             }
                   8155:         }
                   8156:     }
                   8157:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8158:         (defined($rolenames{$type})) && 
                   8159:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8160:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8161:     } elsif ($cid ne '') {
                   8162:         my $crstype = $env{'course.'.$cid.'.type'};
                   8163:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8164:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8165:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8166:         }
1.742     raeburn  8167:     }
1.1037    raeburn  8168:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8169: }
                   8170: 
                   8171: # ----------------------------------------------------------------- Assign Role
                   8172: 
                   8173: sub assignrole {
1.957     raeburn  8174:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8175:         $context)=@_;
1.21      www      8176:     my $mrole;
                   8177:     if ($role =~ /^cr\//) {
1.393     www      8178:         my $cwosec=$url;
1.811     albertel 8179:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8180: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8181:            my $refused = 1;
                   8182:            if ($context eq 'requestcourses') {
                   8183:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8184:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8185:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8186:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8187:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8188:                            if ($crsenv{'internal.courseowner'} eq
                   8189:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8190:                                $refused = '';
                   8191:                            }
                   8192:                        }
                   8193:                    }
                   8194:                }
                   8195:            }
                   8196:            if ($refused) {
                   8197:                &logthis('Refused custom assignrole: '.
                   8198:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8199:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8200:                return 'refused';
                   8201:            }
1.104     www      8202:         }
1.21      www      8203:         $mrole='cr';
1.678     raeburn  8204:     } elsif ($role =~ /^gr\//) {
                   8205:         my $cwogrp=$url;
1.811     albertel 8206:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8207:         unless (&allowed('mdg',$cwogrp)) {
                   8208:             &logthis('Refused group assignrole: '.
                   8209:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8210:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8211:             return 'refused';
                   8212:         }
                   8213:         $mrole='gr';
1.21      www      8214:     } else {
1.82      www      8215:         my $cwosec=$url;
1.811     albertel 8216:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8217:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8218:             my $refused;
                   8219:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8220:                 if (!(&allowed('c'.$role,$url))) {
                   8221:                     $refused = 1;
                   8222:                 }
                   8223:             } else {
                   8224:                 $refused = 1;
                   8225:             }
1.947     raeburn  8226:             if ($refused) {
1.1045    raeburn  8227:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8228:                 if (!$selfenroll && $context eq 'course') {
                   8229:                     my %crsenv;
                   8230:                     if ($role eq 'cc' || $role eq 'co') {
                   8231:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8232:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8233:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8234:                                 if ($crsenv{'internal.courseowner'} eq 
                   8235:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8236:                                     $refused = '';
                   8237:                                 }
                   8238:                             }
                   8239:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8240:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8241:                                 if ($crsenv{'internal.courseowner'} eq 
                   8242:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8243:                                     $refused = '';
                   8244:                                 }
                   8245:                             }
                   8246:                         }
                   8247:                     }
                   8248:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8249:                     $refused = '';
1.1017    raeburn  8250:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8251:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8252:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8253:                         my $wrongcc;
                   8254:                         if ($cnum =~ /^$match_community$/) {
                   8255:                             $wrongcc = 1 if ($role eq 'cc');
                   8256:                         } else {
                   8257:                             $wrongcc = 1 if ($role eq 'co');
                   8258:                         }
                   8259:                         unless ($wrongcc) {
                   8260:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8261:                             if ($crsenv{'internal.courseowner'} eq 
                   8262:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8263:                                 $refused = '';
                   8264:                             }
1.1017    raeburn  8265:                         }
                   8266:                     }
1.1183    raeburn  8267:                 } elsif ($context eq 'requestauthor') {
                   8268:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8269:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8270:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8271:                             $refused = '';
                   8272:                         } else {
                   8273:                             my %domdefaults = &get_domain_defaults($udom);
                   8274:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8275:                                 my $checkbystatus;
                   8276:                                 if ($env{'user.adv'}) { 
                   8277:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8278:                                     if ($disposition eq 'automatic') {
                   8279:                                         $refused = '';
                   8280:                                     } elsif ($disposition eq '') {
                   8281:                                         $checkbystatus = 1;
                   8282:                                     } 
                   8283:                                 } else {
                   8284:                                     $checkbystatus = 1;
                   8285:                                 }
                   8286:                                 if ($checkbystatus) {
                   8287:                                     if ($env{'environment.inststatus'}) {
                   8288:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8289:                                         foreach my $type (@inststatuses) {
                   8290:                                             if (($type ne '') &&
                   8291:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8292:                                                 $refused = '';
                   8293:                                             }
                   8294:                                         }
                   8295:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8296:                                         $refused = '';
                   8297:                                     }
                   8298:                                 }
                   8299:                             }
                   8300:                         }
                   8301:                     }
1.1017    raeburn  8302:                 }
                   8303:                 if ($refused) {
1.947     raeburn  8304:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8305:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8306: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8307:                     return 'refused';
                   8308:                 }
1.932     raeburn  8309:             }
1.1131    raeburn  8310:         } elsif ($role eq 'au') {
                   8311:             if ($url ne '/'.$udom.'/') {
                   8312:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8313:                          ' to assign author role for '.$uname.':'.$udom.
                   8314:                          ' in domain: '.$url.' refused (wrong domain).');
                   8315:                 return 'refused';
                   8316:             }
1.104     www      8317:         }
1.21      www      8318:         $mrole=$role;
                   8319:     }
1.620     albertel 8320:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8321:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8322:     if ($end) { $command.='_'.$end; }
1.21      www      8323:     if ($start) {
                   8324: 	if ($end) { 
1.81      www      8325:            $command.='_'.$start; 
1.21      www      8326:         } else {
1.81      www      8327:            $command.='_0_'.$start;
1.21      www      8328:         }
                   8329:     }
1.739     raeburn  8330:     my $origstart = $start;
                   8331:     my $origend = $end;
1.957     raeburn  8332:     my $delflag;
1.357     www      8333: # actually delete
                   8334:     if ($deleteflag) {
1.373     www      8335: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8336: # modify command to delete the role
1.620     albertel 8337:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8338:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8339: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8340: # set start and finish to negative values for userrolelog
                   8341:            $start=-1;
                   8342:            $end=-1;
1.957     raeburn  8343:            $delflag = 1;
1.357     www      8344:         }
                   8345:     }
                   8346: # send command
1.349     www      8347:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8348: # log new user role if status is ok
1.349     www      8349:     if ($answer eq 'ok') {
1.663     raeburn  8350: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8351:         if (($role eq 'cc') || ($role eq 'in') ||
                   8352:             ($role eq 'ep') || ($role eq 'ad') ||
                   8353:             ($role eq 'ta') || ($role eq 'st') ||
                   8354:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8355:             ($role eq 'co')) {
1.1200    raeburn  8356: # for course roles, perform group memberships changes triggered by role change.
                   8357:             unless ($role =~ /^gr/) {
                   8358:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8359:                                                  $origstart,$selfenroll,$context);
                   8360:             }
1.1184    raeburn  8361:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8362:                            $selfenroll,$context);
                   8363:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8364:                  ($role eq 'au') || ($role eq 'dc')) {
                   8365:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8366:                            $context);
                   8367:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8368:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8369:                              $context); 
                   8370:         }
1.1053    raeburn  8371:         if ($role eq 'cc') {
                   8372:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8373:         }
1.349     www      8374:     }
                   8375:     return $answer;
1.169     harris41 8376: }
                   8377: 
1.1053    raeburn  8378: sub autoupdate_coowners {
                   8379:     my ($url,$end,$start,$uname,$udom) = @_;
                   8380:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8381:     if (($cdom ne '') && ($cnum ne '')) {
                   8382:         my $now = time;
                   8383:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8384:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8385:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8386:             my $instcode = $coursehash{'internal.coursecode'};
                   8387:             if ($instcode ne '') {
1.1056    raeburn  8388:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8389:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8390:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8391:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8392:                         if ($result eq 'valid') {
                   8393:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8394:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8395:                                     push(@newcoowners,$coowner);
                   8396:                                 }
                   8397:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8398:                                     push(@newcoowners,$uname.':'.$udom);
                   8399:                                 }
                   8400:                                 @newcoowners = sort(@newcoowners);
                   8401:                             } else {
                   8402:                                 push(@newcoowners,$uname.':'.$udom);
                   8403:                             }
                   8404:                         } else {
                   8405:                             if ($coursehash{'internal.co-owners'}) {
                   8406:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8407:                                     unless ($coowner eq $uname.':'.$udom) {
                   8408:                                         push(@newcoowners,$coowner);
                   8409:                                     }
                   8410:                                 }
                   8411:                                 unless (@newcoowners > 0) {
                   8412:                                     $delcoowners = 1;
                   8413:                                     $coowners = '';
                   8414:                                 }
                   8415:                             }
                   8416:                         }
                   8417:                         if (@newcoowners || $delcoowners) {
                   8418:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8419:                                             $delcoowners,@newcoowners);
                   8420:                         }
                   8421:                     }
                   8422:                 }
                   8423:             }
                   8424:         }
                   8425:     }
                   8426: }
                   8427: 
                   8428: sub store_coowners {
                   8429:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8430:     my $cid = $cdom.'_'.$cnum;
                   8431:     my ($coowners,$delresult,$putresult);
                   8432:     if (@newcoowners) {
                   8433:         $coowners = join(',',@newcoowners);
                   8434:         my %coownershash = (
                   8435:                             'internal.co-owners' => $coowners,
                   8436:                            );
                   8437:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8438:         if ($putresult eq 'ok') {
                   8439:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8440:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8441:             }
                   8442:         }
                   8443:     }
                   8444:     if ($delcoowners) {
                   8445:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8446:         if ($delresult eq 'ok') {
                   8447:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8448:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8449:             }
                   8450:         }
                   8451:     }
                   8452:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8453:         my %crsinfo =
                   8454:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8455:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8456:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8457:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8458:         }
                   8459:     }
                   8460: }
                   8461: 
1.169     harris41 8462: # -------------------------------------------------- Modify user authentication
1.197     www      8463: # Overrides without validation
                   8464: 
1.169     harris41 8465: sub modifyuserauth {
                   8466:     my ($udom,$uname,$umode,$upass)=@_;
                   8467:     my $uhome=&homeserver($uname,$udom);
1.197     www      8468:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8469:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8470:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8471:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8472:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8473: 		     &escape($upass),$uhome);
1.620     albertel 8474:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8475:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8476:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8477:     &log($udom,,$uname,$uhome,
1.620     albertel 8478:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8479:                                      $env{'user.name'}.', '.$umode.
1.197     www      8480:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8481:     unless ($reply eq 'ok') {
1.197     www      8482:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8483: 	return 'error: '.$reply;
                   8484:     }   
1.170     harris41 8485:     return 'ok';
1.80      www      8486: }
                   8487: 
1.81      www      8488: # --------------------------------------------------------------- Modify a user
1.80      www      8489: 
1.81      www      8490: sub modifyuser {
1.206     matthew  8491:     my ($udom,    $uname, $uid,
                   8492:         $umode,   $upass, $first,
                   8493:         $middle,  $last,  $gene,
1.1058    raeburn  8494:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8495:     $udom= &LONCAPA::clean_domain($udom);
                   8496:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8497:     my $showcandelete = 'none';
                   8498:     if (ref($candelete) eq 'ARRAY') {
                   8499:         if (@{$candelete} > 0) {
                   8500:             $showcandelete = join(', ',@{$candelete});
                   8501:         }
                   8502:     }
1.81      www      8503:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8504:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8505: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8506:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8507:                                      ' desiredhome not specified'). 
1.620     albertel 8508:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8509:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8510:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8511:     my $newuser;
                   8512:     if ($uhome eq 'no_host') {
                   8513:         $newuser = 1;
                   8514:     }
1.80      www      8515: # ----------------------------------------------------------------- Create User
1.406     albertel 8516:     if (($uhome eq 'no_host') && 
                   8517: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8518:         my $unhome='';
1.844     albertel 8519:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8520:             $unhome = $desiredhome;
1.620     albertel 8521: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8522: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8523:         } else { # load balancing routine for determining $unhome
1.81      www      8524:             my $loadm=10000000;
1.841     albertel 8525: 	    my %servers = &get_servers($udom,'library');
                   8526: 	    foreach my $tryserver (keys(%servers)) {
                   8527: 		my $answer=reply('load',$tryserver);
                   8528: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8529: 		    $loadm=$answer;
                   8530: 		    $unhome=$tryserver;
                   8531: 		}
1.80      www      8532: 	    }
                   8533:         }
                   8534:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8535: 	    return 'error: unable to find a home server for '.$uname.
                   8536:                    ' in domain '.$udom;
1.80      www      8537:         }
                   8538:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8539:                          &escape($upass),$unhome);
                   8540: 	unless ($reply eq 'ok') {
                   8541:             return 'error: '.$reply;
                   8542:         }   
1.230     stredwic 8543:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8544:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8545: 	    return 'error: unable verify users home machine.';
1.80      www      8546:         }
1.209     matthew  8547:     }   # End of creation of new user
1.80      www      8548: # ---------------------------------------------------------------------- Add ID
                   8549:     if ($uid) {
                   8550:        $uid=~tr/A-Z/a-z/;
                   8551:        my %uidhash=&idrget($udom,$uname);
1.196     www      8552:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8553:          && (!$forceid)) {
1.80      www      8554: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8555: 	      return 'error: user id "'.$uid.'" does not match '.
                   8556:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8557:           }
                   8558:        } else {
                   8559: 	  &idput($udom,($uname => $uid));
                   8560:        }
                   8561:     }
                   8562: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8563:     my @tmp=&get('environment',
1.899     raeburn  8564: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8565:                     'permanentemail','inststatus'],
1.134     albertel 8566: 		   $udom,$uname);
1.1075    raeburn  8567:     my (%names,%oldnames);
1.313     matthew  8568:     if ($tmp[0] =~ m/^error:.*/) { 
                   8569:         %names=(); 
                   8570:     } else {
                   8571:         %names = @tmp;
1.1075    raeburn  8572:         %oldnames = %names;
1.313     matthew  8573:     }
1.388     www      8574: #
1.1058    raeburn  8575: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8576: # of users did not contain them), do not overwrite existing values
                   8577: # unless field is in $candelete array ref.  
                   8578: #
                   8579: 
                   8580:     my @fields = ('firstname','middlename','lastname','generation',
                   8581:                   'permanentemail','id');
                   8582:     my %newvalues;
                   8583:     if (ref($candelete) eq 'ARRAY') {
                   8584:         foreach my $field (@fields) {
                   8585:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8586:                 if ($field eq 'firstname') {
                   8587:                     $names{$field} = $first;
                   8588:                 } elsif ($field eq 'middlename') {
                   8589:                     $names{$field} = $middle;
                   8590:                 } elsif ($field eq 'lastname') {
                   8591:                     $names{$field} = $last;
                   8592:                 } elsif ($field eq 'generation') { 
                   8593:                     $names{$field} = $gene;
                   8594:                 } elsif ($field eq 'permanentemail') {
                   8595:                     $names{$field} = $email;
                   8596:                 } elsif ($field eq 'id') {
                   8597:                     $names{$field}  = $uid;
                   8598:                 }
                   8599:             }
                   8600:         }
                   8601:     }
1.388     www      8602:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8603:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8604:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8605:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8606:     if ($email) {
                   8607:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8608:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8609:     }
1.899     raeburn  8610:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8611:     if (defined($inststatus)) {
                   8612:         $names{'inststatus'} = '';
                   8613:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8614:         if (ref($usertypes) eq 'HASH') {
                   8615:             my @okstatuses; 
                   8616:             foreach my $item (split(/:/,$inststatus)) {
                   8617:                 if (defined($usertypes->{$item})) {
                   8618:                     push(@okstatuses,$item);  
                   8619:                 }
                   8620:             }
                   8621:             if (@okstatuses) {
                   8622:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8623:             }
                   8624:         }
                   8625:     }
1.1075    raeburn  8626:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8627:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8628:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8629:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8630:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8631:     } else {
                   8632:         $logmsg .= ' during self creation';
                   8633:     }
1.1075    raeburn  8634:     my $changed;
                   8635:     if ($newuser) {
                   8636:         $changed = 1;
                   8637:     } else {
                   8638:         foreach my $field (@fields) {
                   8639:             if ($names{$field} ne $oldnames{$field}) {
                   8640:                 $changed = 1;
                   8641:                 last;
                   8642:             }
                   8643:         }
                   8644:     }
                   8645:     unless ($changed) {
                   8646:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8647:         &logthis($logmsg);
                   8648:         return 'ok';
                   8649:     }
                   8650:     my $reply = &put('environment', \%names, $udom,$uname);
                   8651:     if ($reply ne 'ok') { 
                   8652:         return 'error: '.$reply;
                   8653:     }
1.1087    raeburn  8654:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8655:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8656:     }
1.1075    raeburn  8657:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8658:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8659:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8660:     &logthis($logmsg);
1.134     albertel 8661:     return 'ok';
1.80      www      8662: }
                   8663: 
1.81      www      8664: # -------------------------------------------------------------- Modify student
1.80      www      8665: 
1.81      www      8666: sub modifystudent {
                   8667:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8668:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216    raeburn  8669:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8670:     if (!$cid) {
1.620     albertel 8671: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8672: 	    return 'not_in_class';
                   8673: 	}
1.80      www      8674:     }
                   8675: # --------------------------------------------------------------- Make the user
1.81      www      8676:     my $reply=&modifyuser
1.209     matthew  8677: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8678:          $desiredhome,$email,$inststatus);
1.80      www      8679:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8680:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  8681:     # student's environment
1.297     matthew  8682:     $uid = undef if (!$forceid);
1.455     albertel 8683:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  8684:                                         $gene,$usec,$end,$start,$type,$locktype,
                   8685:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8686:     return $reply;
                   8687: }
                   8688: 
                   8689: sub modify_student_enrollment {
1.1216    raeburn  8690:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8691:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8692:     my ($cdom,$cnum,$chome);
                   8693:     if (!$cid) {
1.620     albertel 8694: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8695: 	    return 'not_in_class';
                   8696: 	}
1.620     albertel 8697: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8698: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8699:     } else {
                   8700: 	($cdom,$cnum)=split(/_/,$cid);
                   8701:     }
1.620     albertel 8702:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8703:     if (!$chome) {
1.457     raeburn  8704: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8705:     }
1.455     albertel 8706:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8707:     # Make sure the user exists
1.81      www      8708:     my $uhome=&homeserver($uname,$udom);
                   8709:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8710: 	return 'error: no such user';
                   8711:     }
1.297     matthew  8712:     # Get student data if we were not given enough information
                   8713:     if (!defined($first)  || $first  eq '' || 
                   8714:         !defined($last)   || $last   eq '' || 
                   8715:         !defined($uid)    || $uid    eq '' || 
                   8716:         !defined($middle) || $middle eq '' || 
                   8717:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8718:         # They did not supply us with enough data to enroll the student, so
                   8719:         # we need to pick up more information.
1.297     matthew  8720:         my %tmp = &get('environment',
1.294     matthew  8721:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8722:                        ,$udom,$uname);
                   8723: 
1.800     albertel 8724:         #foreach my $key (keys(%tmp)) {
                   8725:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8726:         #}
1.294     matthew  8727:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8728:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8729:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8730:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8731:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8732:     }
1.556     albertel 8733:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8734:     my $user = "$uname:$udom";
                   8735:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8736:     my $reply=cput('classlist',
1.1148    raeburn  8737: 		   {$user => 
1.1216    raeburn  8738: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8739: 		   $cdom,$cnum);
1.1148    raeburn  8740:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8741:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8742:     } else { 
1.81      www      8743: 	return 'error: '.$reply;
                   8744:     }
1.297     matthew  8745:     # Add student role to user
1.83      www      8746:     my $uurl='/'.$cid;
1.81      www      8747:     $uurl=~s/\_/\//g;
                   8748:     if ($usec) {
                   8749: 	$uurl.='/'.$usec;
                   8750:     }
1.1148    raeburn  8751:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8752:                              $selfenroll,$context);
                   8753:     if ($result ne 'ok') {
                   8754:         if ($old_entry{$user} ne '') {
                   8755:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8756:         } else {
                   8757:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8758:         }
                   8759:     }
                   8760:     return $result; 
1.21      www      8761: }
                   8762: 
1.556     albertel 8763: sub format_name {
                   8764:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8765:     my $name;
                   8766:     if ($first ne 'lastname') {
                   8767: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8768:     } else {
                   8769: 	if ($lastname=~/\S/) {
                   8770: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8771: 	    $name=~s/\s+,/,/;
                   8772: 	} else {
                   8773: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8774: 	}
                   8775:     }
                   8776:     $name=~s/^\s+//;
                   8777:     $name=~s/\s+$//;
                   8778:     $name=~s/\s+/ /g;
                   8779:     return $name;
                   8780: }
                   8781: 
1.84      www      8782: # ------------------------------------------------- Write to course preferences
                   8783: 
                   8784: sub writecoursepref {
                   8785:     my ($courseid,%prefs)=@_;
                   8786:     $courseid=~s/^\///;
                   8787:     $courseid=~s/\_/\//g;
                   8788:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8789:     my $chome=homeserver($cnum,$cdomain);
                   8790:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8791: 	return 'error: no such course';
                   8792:     }
                   8793:     my $cstring='';
1.800     albertel 8794:     foreach my $pref (keys(%prefs)) {
                   8795: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8796:     }
1.84      www      8797:     $cstring=~s/\&$//;
                   8798:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8799: }
                   8800: 
                   8801: # ---------------------------------------------------------- Make/modify course
                   8802: 
                   8803: sub createcourse {
1.741     raeburn  8804:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8805:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8806:     $url=&declutter($url);
                   8807:     my $cid='';
1.1028    raeburn  8808:     if ($context eq 'requestcourses') {
                   8809:         my $can_create = 0;
                   8810:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8811:         if ($udom eq $ownerdom) {
                   8812:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8813:                                   $context)) {
                   8814:                 $can_create = 1;
                   8815:             }
                   8816:         } else {
                   8817:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8818:                                            $category);
                   8819:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8820:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8821:                 if (@curr > 0) {
                   8822:                     my @options = qw(approval validate autolimit);
                   8823:                     my $optregex = join('|',@options);
                   8824:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8825:                         $can_create = 1;
                   8826:                     }
                   8827:                 }
                   8828:             }
                   8829:         }
                   8830:         if ($can_create) {
                   8831:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8832:                 unless (&allowed('ccc',$udom)) {
                   8833:                     return 'refused'; 
                   8834:                 }
1.1017    raeburn  8835:             }
                   8836:         } else {
                   8837:             return 'refused';
                   8838:         }
1.1028    raeburn  8839:     } elsif (!&allowed('ccc',$udom)) {
                   8840:         return 'refused';
1.84      www      8841:     }
1.1011    raeburn  8842: # --------------------------------------------------------------- Get Unique ID
                   8843:     my $uname;
                   8844:     if ($cnum =~ /^$match_courseid$/) {
                   8845:         my $chome=&homeserver($cnum,$udom,'true');
                   8846:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8847:             $uname = $cnum;
                   8848:         } else {
1.1038    raeburn  8849:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8850:         }
                   8851:     } else {
1.1038    raeburn  8852:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8853:     }
                   8854:     return $uname if ($uname =~ /^error/);
                   8855: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8856:     if (!defined($course_server)) {
                   8857:         if (defined(&domain($udom,'primary'))) {
                   8858:             $course_server = &domain($udom,'primary');
                   8859:         } else {
                   8860:             $course_server = $env{'user.home'}; 
                   8861:         }
                   8862:     }
                   8863:     my %host_servers =
                   8864:         &Apache::lonnet::get_servers($udom,'library');
                   8865:     unless ($host_servers{$course_server}) {
                   8866:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8867:     }
1.84      www      8868: # ------------------------------------------------------------- Make the course
                   8869:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8870:                       $course_server);
1.84      www      8871:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8872:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8873:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8874: 	return 'error: no such course';
                   8875:     }
1.271     www      8876: # ----------------------------------------------------------------- Course made
1.516     raeburn  8877: # log existence
1.1029    raeburn  8878:     my $now = time;
1.918     raeburn  8879:     my $newcourse = {
                   8880:                     $udom.'_'.$uname => {
1.921     raeburn  8881:                                      description => $description,
                   8882:                                      inst_code   => $inst_code,
                   8883:                                      owner       => $course_owner,
                   8884:                                      type        => $crstype,
1.1029    raeburn  8885:                                      creator     => $env{'user.name'}.':'.
                   8886:                                                     $env{'user.domain'},
                   8887:                                      created     => $now,
                   8888:                                      context     => $context,
1.918     raeburn  8889:                                                 },
                   8890:                     };
1.921     raeburn  8891:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8892: # set toplevel url
1.271     www      8893:     my $topurl=$url;
                   8894:     unless ($nonstandard) {
                   8895: # ------------------------------------------ For standard courses, make top url
                   8896:         my $mapurl=&clutter($url);
1.278     www      8897:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8898:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8899: <map>
                   8900: <resource id="1" type="start"></resource>
                   8901: <resource id="2" src="$mapurl"></resource>
                   8902: <resource id="3" type="finish"></resource>
                   8903: <link index="1" from="1" to="2"></link>
                   8904: <link index="2" from="2" to="3"></link>
                   8905: </map>
                   8906: ENDINITMAP
                   8907:         $topurl=&declutter(
1.638     albertel 8908:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8909:                           );
                   8910:     }
                   8911: # ----------------------------------------------------------- Write preferences
1.84      www      8912:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8913:                      ('description'              => $description,
                   8914:                       'url'                      => $topurl,
                   8915:                       'internal.creator'         => $env{'user.name'}.':'.
                   8916:                                                     $env{'user.domain'},
                   8917:                       'internal.created'         => $now,
                   8918:                       'internal.creationcontext' => $context)
                   8919:                     );
1.84      www      8920:     return '/'.$udom.'/'.$uname;
                   8921: }
                   8922: 
1.1011    raeburn  8923: # ------------------------------------------------------------------- Create ID
                   8924: sub generate_coursenum {
1.1038    raeburn  8925:     my ($udom,$crstype) = @_;
1.1011    raeburn  8926:     my $domdesc = &domain($udom);
                   8927:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8928:     my $first;
                   8929:     if ($crstype eq 'Community') {
                   8930:         $first = '0';
                   8931:     } else {
                   8932:         $first = int(1+rand(9)); 
                   8933:     } 
                   8934:     my $uname=$first.
1.1011    raeburn  8935:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8936:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8937:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8938: # ----------------------------------------------- Make sure that does not exist
                   8939:     my $uhome=&homeserver($uname,$udom,'true');
                   8940:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8941:         if ($crstype eq 'Community') {
                   8942:             $first = '0';
                   8943:         } else {
                   8944:             $first = int(1+rand(9));
                   8945:         }
                   8946:         $uname=$first.
1.1011    raeburn  8947:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8948:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8949:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8950:         $uhome=&homeserver($uname,$udom,'true');
                   8951:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8952:             return 'error: unable to generate unique course-ID';
                   8953:         }
                   8954:     }
                   8955:     return $uname;
                   8956: }
                   8957: 
1.813     albertel 8958: sub is_course {
1.1167    droeschl 8959:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8960:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8961: 
                   8962:     return unless $cdom and $cnum;
                   8963: 
                   8964:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8965:         '.');
                   8966: 
1.1219    raeburn  8967:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 8968:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8969: }
                   8970: 
1.1015    raeburn  8971: sub store_userdata {
                   8972:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8973:     my $result;
1.1016    raeburn  8974:     if ($datakey ne '') {
1.1013    raeburn  8975:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8976:             if ($udom eq '' || $uname eq '') {
                   8977:                 $udom = $env{'user.domain'};
                   8978:                 $uname = $env{'user.name'};
                   8979:             }
                   8980:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8981:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8982:                 $result = 'error: no_host';
                   8983:             } else {
                   8984:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8985:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8986: 
                   8987:                 my $namevalue='';
                   8988:                 foreach my $key (keys(%{$storehash})) {
                   8989:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8990:                 }
                   8991:                 $namevalue=~s/\&$//;
1.1224    raeburn  8992:                 unless ($namespace eq 'courserequests') {
                   8993:                     $datakey = &escape($datakey);
                   8994:                 }
1.1105    raeburn  8995:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8996:                                   $namevalue,$uhome);
1.1013    raeburn  8997:             }
                   8998:         } else {
                   8999:             $result = 'error: data to store was not a hash reference'; 
                   9000:         }
                   9001:     } else {
                   9002:         $result= 'error: invalid requestkey'; 
                   9003:     }
                   9004:     return $result;
                   9005: }
                   9006: 
1.21      www      9007: # ---------------------------------------------------------- Assign Custom Role
                   9008: 
                   9009: sub assigncustomrole {
1.957     raeburn  9010:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9011:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9012:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9013: }
                   9014: 
                   9015: # ----------------------------------------------------------------- Revoke Role
                   9016: 
                   9017: sub revokerole {
1.957     raeburn  9018:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9019:     my $now=time;
1.965     raeburn  9020:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9021: }
                   9022: 
                   9023: # ---------------------------------------------------------- Revoke Custom Role
                   9024: 
                   9025: sub revokecustomrole {
1.957     raeburn  9026:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9027:     my $now=time;
1.357     www      9028:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9029:            $deleteflag,$selfenroll,$context);
1.17      www      9030: }
                   9031: 
1.533     banghart 9032: # ------------------------------------------------------------ Disk usage
1.535     albertel 9033: sub diskusage {
1.955     raeburn  9034:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9035:     $directorypath =~ s/\/$//;
                   9036:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9037:                        .&escape($getpropath).':'.&escape($uname).':'
                   9038:                        .&escape($udom),homeserver($uname,$udom));
                   9039:     if ($listing eq 'unknown_cmd') {
                   9040:         if ($getpropath) {
                   9041:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9042:         }
                   9043:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9044:     }
1.514     albertel 9045:     return $listing;
1.512     banghart 9046: }
                   9047: 
1.566     banghart 9048: sub is_locked {
1.1096    raeburn  9049:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9050:     my @check;
                   9051:     my $is_locked;
1.1093    raeburn  9052:     push (@check,$file_name);
1.613     albertel 9053:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9054: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9055:     my ($tmp)=keys(%locked);
                   9056:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9057:     
1.566     banghart 9058:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9059:         $is_locked = 'false';
                   9060:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9061:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9062:                $is_locked = 'true';
1.1096    raeburn  9063:                if (ref($which) eq 'ARRAY') {
                   9064:                    push(@{$which},$entry);
                   9065:                } else {
                   9066:                    last;
                   9067:                }
1.745     raeburn  9068:            }
                   9069:        }
1.566     banghart 9070:     } else {
                   9071:         $is_locked = 'false';
                   9072:     }
1.1093    raeburn  9073:     return $is_locked;
1.566     banghart 9074: }
                   9075: 
1.759     albertel 9076: sub declutter_portfile {
                   9077:     my ($file) = @_;
1.833     albertel 9078:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9079:     return $file;
                   9080: }
                   9081: 
1.559     banghart 9082: # ------------------------------------------------------------- Mark as Read Only
                   9083: 
                   9084: sub mark_as_readonly {
                   9085:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9086:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9087:     my ($tmp)=keys(%current_permissions);
                   9088:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9089:     foreach my $file (@{$files}) {
1.759     albertel 9090: 	$file = &declutter_portfile($file);
1.561     banghart 9091:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9092:     }
1.613     albertel 9093:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9094:     return;
                   9095: }
                   9096: 
1.572     banghart 9097: # ------------------------------------------------------------Save Selected Files
                   9098: 
                   9099: sub save_selected_files {
                   9100:     my ($user, $path, @files) = @_;
                   9101:     my $filename = $user."savedfiles";
1.573     banghart 9102:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9103:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9104:     foreach my $file (@files) {
1.620     albertel 9105:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9106:     }
                   9107:     foreach my $file (@other_files) {
1.574     banghart 9108:         print (OUT $file."\n");
1.572     banghart 9109:     }
1.574     banghart 9110:     close (OUT);
1.572     banghart 9111:     return 'ok';
                   9112: }
                   9113: 
1.574     banghart 9114: sub clear_selected_files {
                   9115:     my ($user) = @_;
                   9116:     my $filename = $user."savedfiles";
1.1117    foxr     9117:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9118:     print (OUT undef);
                   9119:     close (OUT);
                   9120:     return ("ok");    
                   9121: }
                   9122: 
1.572     banghart 9123: sub files_in_path {
                   9124:     my ($user, $path) = @_;
                   9125:     my $filename = $user."savedfiles";
                   9126:     my %return_files;
1.1117    foxr     9127:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9128:     while (my $line_in = <IN>) {
1.574     banghart 9129:         chomp ($line_in);
                   9130:         my @paths_and_file = split (m!/!, $line_in);
                   9131:         my $file_part = pop (@paths_and_file);
                   9132:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9133:         $path_part.='/';
                   9134:         my $path_and_file = $path_part.$file_part;
                   9135:         if ($path_part eq $path) {
                   9136:             $return_files{$file_part}= 'selected';
                   9137:         }
                   9138:     }
1.574     banghart 9139:     close (IN);
                   9140:     return (\%return_files);
1.572     banghart 9141: }
                   9142: 
                   9143: # called in portfolio select mode, to show files selected NOT in current directory
                   9144: sub files_not_in_path {
                   9145:     my ($user, $path) = @_;
                   9146:     my $filename = $user."savedfiles";
                   9147:     my @return_files;
                   9148:     my $path_part;
1.1117    foxr     9149:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9150:     while (my $line = <IN>) {
1.572     banghart 9151:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9152:         my @paths_and_file = split(m|/|, $line);
                   9153:         my $file_part = pop(@paths_and_file);
                   9154:         chomp($file_part);
                   9155:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9156:         $path_part .= '/';
                   9157:         my $path_and_file = $path_part.$file_part;
                   9158:         if ($path_part ne $path) {
1.800     albertel 9159:             push(@return_files, ($path_and_file));
1.572     banghart 9160:         }
                   9161:     }
1.800     albertel 9162:     close(OUT);
1.574     banghart 9163:     return (@return_files);
1.572     banghart 9164: }
                   9165: 
1.1273    raeburn  9166: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9167:  
                   9168: sub portfiles_versioning {
                   9169:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   9170:     my $portfolio_root = '/userfiles/portfolio';
                   9171:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   9172:     foreach my $file (@{$portfiles}) {
                   9173:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   9174:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   9175:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   9176:         my $getpropath = 1;
                   9177:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   9178:                                              $stu_name,$getpropath);
                   9179:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   9180:         my $new_answer = 
                   9181:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   9182:         if ($new_answer ne 'problem getting file') {
                   9183:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   9184:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   9185:                               [$symb,$env{'request.course.id'},'graded']);
                   9186:         }
                   9187:     }
                   9188: }
                   9189: 
                   9190: sub get_next_version {
                   9191:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   9192:     my $version;
                   9193:     if (ref($dir_list) eq 'ARRAY') {
                   9194:         foreach my $row (@{$dir_list}) {
                   9195:             my ($file) = split(/\&/,$row,2);
                   9196:             my ($file_name,$file_version,$file_ext) =
                   9197:                 &file_name_version_ext($file);
                   9198:             if (($file_name eq $answer_name) &&
                   9199:                 ($file_ext eq $answer_ext)) {
                   9200:                      # gets here if filename and extension match,
                   9201:                      # regardless of version
                   9202:                 if ($file_version ne '') {
                   9203:                     # a versioned file is found  so save it for later
                   9204:                     if ($file_version > $version) {
                   9205:                         $version = $file_version;
                   9206:                     }
                   9207:                 }
                   9208:             }
                   9209:         }
                   9210:     }
                   9211:     $version ++;
                   9212:     return($version);
                   9213: }
                   9214: 
                   9215: sub version_selected_portfile {
                   9216:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   9217:     my ($answer_name,$answer_ver,$answer_ext) =
                   9218:         &file_name_version_ext($file_name);
                   9219:     my $new_answer;
                   9220:     $env{'form.copy'} =
                   9221:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   9222:     if($env{'form.copy'} eq '-1') {
                   9223:         $new_answer = 'problem getting file';
                   9224:     } else {
                   9225:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   9226:         my $copy_result = 
                   9227:             &finishuserfileupload($stu_name,$domain,'copy',
                   9228:                                   '/portfolio'.$directory.$new_answer);
                   9229:     }
                   9230:     undef($env{'form.copy'});
                   9231:     return ($new_answer);
                   9232: }
                   9233: 
                   9234: sub file_name_version_ext {
                   9235:     my ($file)=@_;
                   9236:     my @file_parts = split(/\./, $file);
                   9237:     my ($name,$version,$ext);
                   9238:     if (@file_parts > 1) {
                   9239:         $ext=pop(@file_parts);
                   9240:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   9241:             $version=pop(@file_parts);
                   9242:         }
                   9243:         $name=join('.',@file_parts);
                   9244:     } else {
                   9245:         $name=join('.',@file_parts);
                   9246:     }
                   9247:     return($name,$version,$ext);
                   9248: }
                   9249: 
1.745     raeburn  9250: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9251: 
1.745     raeburn  9252: sub get_portfile_permissions {
                   9253:     my ($domain,$user) = @_;
1.613     albertel 9254:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9255:     my ($tmp)=keys(%current_permissions);
                   9256:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9257:     return \%current_permissions;
                   9258: }
                   9259: 
                   9260: #---------------------------------------------Get portfolio file access controls
                   9261: 
1.749     raeburn  9262: sub get_access_controls {
1.745     raeburn  9263:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9264:     my %access;
                   9265:     my $real_file = $file;
                   9266:     $file =~ s/\.meta$//;
1.745     raeburn  9267:     if (defined($file)) {
1.749     raeburn  9268:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9269:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9270:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9271:             }
                   9272:         }
1.745     raeburn  9273:     } else {
1.749     raeburn  9274:         foreach my $key (keys(%{$current_permissions})) {
                   9275:             if ($key =~ /\0accesscontrol$/) {
                   9276:                 if (defined($group)) {
                   9277:                     if ($key !~ m-^\Q$group\E/-) {
                   9278:                         next;
                   9279:                     }
                   9280:                 }
                   9281:                 my ($fullpath) = split(/\0/,$key);
                   9282:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9283:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9284:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9285:                     }
                   9286:                 }
                   9287:             }
                   9288:         }
                   9289:     }
                   9290:     return %access;
                   9291: }
                   9292: 
                   9293: sub modify_access_controls {
                   9294:     my ($file_name,$changes,$domain,$user)=@_;
                   9295:     my ($outcome,$deloutcome);
                   9296:     my %store_permissions;
                   9297:     my %new_values;
                   9298:     my %new_control;
                   9299:     my %translation;
                   9300:     my @deletions = ();
                   9301:     my $now = time;
                   9302:     if (exists($$changes{'activate'})) {
                   9303:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9304:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9305:             my $numnew = scalar(@newitems);
                   9306:             for (my $i=0; $i<$numnew; $i++) {
                   9307:                 my $newkey = $newitems[$i];
                   9308:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9309:                 if ($newkey =~ /^\d+:/) { 
                   9310:                     $newkey =~ s/^(\d+)/$newid/;
                   9311:                     $translation{$1} = $newid;
                   9312:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9313:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9314:                     $translation{$1} = $newid;
                   9315:                 }
1.749     raeburn  9316:                 $new_values{$file_name."\0".$newkey} = 
                   9317:                                           $$changes{'activate'}{$newitems[$i]};
                   9318:                 $new_control{$newkey} = $now;
                   9319:             }
                   9320:         }
                   9321:     }
                   9322:     my %todelete;
                   9323:     my %changed_items;
                   9324:     foreach my $action ('delete','update') {
                   9325:         if (exists($$changes{$action})) {
                   9326:             if (ref($$changes{$action}) eq 'HASH') {
                   9327:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9328:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9329:                     if ($action eq 'delete') { 
                   9330:                         $todelete{$itemnum} = 1;
                   9331:                     } else {
                   9332:                         $changed_items{$itemnum} = $key;
                   9333:                     }
                   9334:                 }
1.745     raeburn  9335:             }
                   9336:         }
1.749     raeburn  9337:     }
                   9338:     # get lock on access controls for file.
                   9339:     my $lockhash = {
                   9340:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9341:                                                        ':'.$env{'user.domain'},
                   9342:                    }; 
                   9343:     my $tries = 0;
                   9344:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9345:    
                   9346:     while (($gotlock ne 'ok') && $tries <3) {
                   9347:         $tries ++;
                   9348:         sleep 1;
                   9349:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9350:     }
                   9351:     if ($gotlock eq 'ok') {
                   9352:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9353:         my ($tmp)=keys(%curr_permissions);
                   9354:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9355:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9356:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9357:             if (ref($curr_controls) eq 'HASH') {
                   9358:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9359:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9360:                     if (defined($todelete{$itemnum})) {
                   9361:                         push(@deletions,$file_name."\0".$control_item);
                   9362:                     } else {
                   9363:                         if (defined($changed_items{$itemnum})) {
                   9364:                             $new_control{$changed_items{$itemnum}} = $now;
                   9365:                             push(@deletions,$file_name."\0".$control_item);
                   9366:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9367:                         } else {
                   9368:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9369:                         }
                   9370:                     }
1.745     raeburn  9371:                 }
                   9372:             }
                   9373:         }
1.970     raeburn  9374:         my ($group);
                   9375:         if (&is_course($domain,$user)) {
                   9376:             ($group,my $file) = split(/\//,$file_name,2);
                   9377:         }
1.749     raeburn  9378:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9379:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9380:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9381:         #  remove lock
                   9382:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9383:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9384:         my $sqlresult =
1.970     raeburn  9385:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9386:                                     $group);
1.749     raeburn  9387:     } else {
                   9388:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9389:     }
1.749     raeburn  9390:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9391: }
                   9392: 
1.827     raeburn  9393: sub make_public_indefinitely {
1.1271    raeburn  9394:     my (@requrl) = @_;
                   9395:     return &automated_portfile_access('public',\@requrl);
                   9396: }
                   9397: 
                   9398: sub automated_portfile_access {
                   9399:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  9400:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   9401:         return 'invalid';
                   9402:     }
1.1271    raeburn  9403:     my %urls;
                   9404:     if (ref($addsref) eq 'ARRAY') {
                   9405:         foreach my $requrl (@{$addsref}) {
                   9406:             if (&is_portfolio_url($requrl)) {
                   9407:                 unless (exists($urls{$requrl})) {
                   9408:                     $urls{$requrl} = 'add';
                   9409:                 }
                   9410:             }
                   9411:         }
                   9412:     }
                   9413:     if (ref($delsref) eq 'ARRAY') {
                   9414:         foreach my $requrl (@{$delsref}) { 
                   9415:             if (&is_portfolio_url($requrl)) {
                   9416:                 unless (exists($urls{$requrl})) {
                   9417:                     $urls{$requrl} = 'delete'; 
                   9418:                 }
                   9419:             }
                   9420:         }
                   9421:     }
                   9422:     unless (keys(%urls)) {
                   9423:         return 'invalid';
                   9424:     }
                   9425:     my $ip;
                   9426:     if ($accesstype eq 'ip') {
                   9427:         if (ref($info) eq 'HASH') {
                   9428:             if ($info->{'ip'} ne '') {
                   9429:                 $ip = $info->{'ip'};
                   9430:             }
                   9431:         }
                   9432:         if ($ip eq '') {
                   9433:             return 'invalid';
                   9434:         }
                   9435:     }
                   9436:     my $errors;
1.827     raeburn  9437:     my $now = time;
1.1271    raeburn  9438:     my %current_perms;
                   9439:     foreach my $requrl (sort(keys(%urls))) {
                   9440:         my $action;
                   9441:         if ($urls{$requrl} eq 'add') {
                   9442:             $action = 'activate';
                   9443:         } else {
                   9444:             $action = 'none';
                   9445:         }
                   9446:         my $aclnum = 0;
1.827     raeburn  9447:         my (undef,$udom,$unum,$file_name,$group) =
                   9448:             &parse_portfolio_url($requrl);
1.1271    raeburn  9449:         unless (exists($current_perms{$unum.':'.$udom})) {
                   9450:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   9451:         }
                   9452:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  9453:                                                    $group,$file_name);
                   9454:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9455:             my ($num,$scope,$end,$start) = 
                   9456:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  9457:             if ($scope eq $accesstype) {
                   9458:                 if (($start <= $now) && ($end == 0)) {
                   9459:                     if ($accesstype eq 'ip') {
                   9460:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   9461:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   9462:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   9463:                                     if ($urls{$requrl} eq 'add') {
                   9464:                                         $action = 'none';
                   9465:                                         last;
                   9466:                                     } else {
                   9467:                                         $action = 'delete';
                   9468:                                         $aclnum = $num;
                   9469:                                         last;
                   9470:                                     }
                   9471:                                 }
                   9472:                             }
                   9473:                         }
                   9474:                     } elsif ($accesstype eq 'public') {
                   9475:                         if ($urls{$requrl} eq 'add') {
                   9476:                             $action = 'none';
                   9477:                             last;
                   9478:                         } else {
                   9479:                             $action = 'delete';
                   9480:                             $aclnum = $num;
                   9481:                             last;
                   9482:                         }
                   9483:                     }
                   9484:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  9485:                     $action = 'update';
                   9486:                     $aclnum = $num;
1.1271    raeburn  9487:                     last;
1.827     raeburn  9488:                 }
                   9489:             }
                   9490:         }
                   9491:         if ($action eq 'none') {
1.1271    raeburn  9492:             next;
1.827     raeburn  9493:         } else {
                   9494:             my %changes;
                   9495:             my $newend = 0;
                   9496:             my $newstart = $now;
1.1271    raeburn  9497:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  9498:             $changes{$action}{$newkey} = {
1.1271    raeburn  9499:                 type => $accesstype,
1.827     raeburn  9500:                 time => {
                   9501:                     start => $newstart,
                   9502:                     end   => $newend,
                   9503:                 },
                   9504:             };
1.1271    raeburn  9505:             if ($accesstype eq 'ip') {
                   9506:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   9507:             }
1.827     raeburn  9508:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9509:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  9510:             unless ($outcome eq 'ok') {
                   9511:                 $errors .= $outcome.' ';
                   9512:             }
1.827     raeburn  9513:         }
1.1271    raeburn  9514:     }
                   9515:     if ($errors) {
                   9516:         $errors =~ s/\s$//;
                   9517:         return $errors;
1.827     raeburn  9518:     } else {
1.1271    raeburn  9519:         return 'ok';
1.827     raeburn  9520:     }
                   9521: }
                   9522: 
1.745     raeburn  9523: #------------------------------------------------------Get Marked as Read Only
                   9524: 
                   9525: sub get_marked_as_readonly {
                   9526:     my ($domain,$user,$what,$group) = @_;
                   9527:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9528:     my @readonly_files;
1.629     banghart 9529:     my $cmp1=$what;
                   9530:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9531:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9532:         if (defined($group)) {
                   9533:             if ($file_name !~ m-^\Q$group\E/-) {
                   9534:                 next;
                   9535:             }
                   9536:         }
1.561     banghart 9537:         if (ref($value) eq "ARRAY"){
                   9538:             foreach my $stored_what (@{$value}) {
1.629     banghart 9539:                 my $cmp2=$stored_what;
1.759     albertel 9540:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9541:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9542:                 }
1.629     banghart 9543:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9544:                     push(@readonly_files, $file_name);
1.745     raeburn  9545:                     last;
1.563     banghart 9546:                 } elsif (!defined($what)) {
                   9547:                     push(@readonly_files, $file_name);
1.745     raeburn  9548:                     last;
1.561     banghart 9549:                 }
                   9550:             }
1.745     raeburn  9551:         }
1.561     banghart 9552:     }
                   9553:     return @readonly_files;
                   9554: }
1.577     banghart 9555: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9556: 
1.577     banghart 9557: sub get_marked_as_readonly_hash {
1.745     raeburn  9558:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9559:     my %readonly_files;
1.745     raeburn  9560:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9561:         if (defined($group)) {
                   9562:             if ($file_name !~ m-^\Q$group\E/-) {
                   9563:                 next;
                   9564:             }
                   9565:         }
1.577     banghart 9566:         if (ref($value) eq "ARRAY"){
                   9567:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9568:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9569:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9570:                         if ($lock_descriptor eq 'graded') {
                   9571:                             $readonly_files{$file_name} = 'graded';
                   9572:                         } elsif ($lock_descriptor eq 'handback') {
                   9573:                             $readonly_files{$file_name} = 'handback';
                   9574:                         } else {
                   9575:                             if (!exists($readonly_files{$file_name})) {
                   9576:                                 $readonly_files{$file_name} = 'locked';
                   9577:                             }
                   9578:                         }
1.745     raeburn  9579:                     }
1.750     banghart 9580:                 } 
1.577     banghart 9581:             }
                   9582:         } 
                   9583:     }
                   9584:     return %readonly_files;
                   9585: }
1.559     banghart 9586: # ------------------------------------------------------------ Unmark as Read Only
                   9587: 
                   9588: sub unmark_as_readonly {
1.629     banghart 9589:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9590:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9591:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9592:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9593:     my $symb_crs = $what;
                   9594:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9595:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9596:     my ($tmp)=keys(%current_permissions);
                   9597:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9598:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9599:     foreach my $file (@readonly_files) {
1.759     albertel 9600: 	my $clean_file = &declutter_portfile($file);
                   9601: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9602: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9603:         my @new_locks;
                   9604:         my @del_keys;
                   9605:         if (ref($current_locks) eq "ARRAY"){
                   9606:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9607:                 my $compare=$locker;
1.749     raeburn  9608:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9609:                     $compare=join('',@{$locker});
1.746     raeburn  9610:                     if ($compare ne $symb_crs) {
                   9611:                         push(@new_locks, $locker);
                   9612:                     }
1.563     banghart 9613:                 }
                   9614:             }
1.650     albertel 9615:             if (scalar(@new_locks) > 0) {
1.563     banghart 9616:                 $current_permissions{$file} = \@new_locks;
                   9617:             } else {
                   9618:                 push(@del_keys, $file);
1.613     albertel 9619:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9620:                 delete($current_permissions{$file});
1.563     banghart 9621:             }
                   9622:         }
1.561     banghart 9623:     }
1.613     albertel 9624:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9625:     return;
                   9626: }
1.512     banghart 9627: 
1.17      www      9628: # ------------------------------------------------------------ Directory lister
                   9629: 
                   9630: sub dirlist {
1.955     raeburn  9631:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9632:     $uri=~s/^\///;
                   9633:     $uri=~s/\/$//;
1.253     stredwic 9634:     my ($udom, $uname);
1.955     raeburn  9635:     if ($getuserdir) {
1.253     stredwic 9636:         $udom = $userdomain;
                   9637:         $uname = $username;
1.955     raeburn  9638:     } else {
                   9639:         (undef,$udom,$uname)=split(/\//,$uri);
                   9640:         if(defined($userdomain)) {
                   9641:             $udom = $userdomain;
                   9642:         }
                   9643:         if(defined($username)) {
                   9644:             $uname = $username;
                   9645:         }
1.253     stredwic 9646:     }
1.955     raeburn  9647:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9648: 
1.955     raeburn  9649:     $dirRoot = $perlvar{'lonDocRoot'};
                   9650:     if (defined($getpropath)) {
                   9651:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9652:         $dirRoot =~ s/\/$//;
1.955     raeburn  9653:     } elsif (defined($getuserdir)) {
                   9654:         my $subdir=$uname.'__';
                   9655:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9656:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9657:                    ."/$udom/$subdir/$uname";
                   9658:     } elsif (defined($alternateRoot)) {
                   9659:         $dirRoot = $alternateRoot;
1.751     banghart 9660:     }
1.253     stredwic 9661: 
                   9662:     if($udom) {
                   9663:         if($uname) {
1.1135    raeburn  9664:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9665:             if ($uhome eq 'no_host') {
                   9666:                 return ([],'no_host');
                   9667:             }
1.955     raeburn  9668:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9669:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9670:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9671:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9672:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9673:             } else {
                   9674:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9675:             }
1.605     matthew  9676:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9677:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9678:                 @listing_results = split(/:/,$listing);
                   9679:             } else {
                   9680:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9681:             }
1.1135    raeburn  9682:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9683:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9684:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9685:                 return ([],$listing);
                   9686:             } else {
                   9687:                 return (\@listing_results);
1.1135    raeburn  9688:             }
1.955     raeburn  9689:         } elsif(!$alternateRoot) {
1.1136    raeburn  9690:             my (%allusers,%listerror);
1.841     albertel 9691: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9692:  	    foreach my $tryserver (keys(%servers)) {
                   9693:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9694:                                   &escape($udom),$tryserver);
                   9695:                 if ($listing eq 'unknown_cmd') {
                   9696: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9697: 				      $udom, $tryserver);
                   9698:                 } else {
                   9699:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9700:                 }
1.841     albertel 9701: 		if ($listing eq 'unknown_cmd') {
                   9702: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9703: 				      $udom, $tryserver);
                   9704: 		    @listing_results = split(/:/,$listing);
                   9705: 		} else {
                   9706: 		    @listing_results =
                   9707: 			map { &unescape($_); } split(/:/,$listing);
                   9708: 		}
1.1136    raeburn  9709:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9710:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9711:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9712:                     $listerror{$tryserver} = $listing;
                   9713:                 } else {
1.841     albertel 9714: 		    foreach my $line (@listing_results) {
                   9715: 			my ($entry) = split(/&/,$line,2);
                   9716: 			$allusers{$entry} = 1;
                   9717: 		    }
                   9718: 		}
1.253     stredwic 9719:             }
1.1136    raeburn  9720:             my @alluserslist=();
1.800     albertel 9721:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9722:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9723:             }
1.1136    raeburn  9724:             return (\@alluserslist);
1.253     stredwic 9725:         } else {
1.1136    raeburn  9726:             return ([],'missing username');
1.253     stredwic 9727:         }
1.955     raeburn  9728:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9729:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9730:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9731:         return (\@all_domains);
1.955     raeburn  9732:     } else {
1.1136    raeburn  9733:         return ([],'missing domain');
1.275     stredwic 9734:     }
                   9735: }
                   9736: 
                   9737: # --------------------------------------------- GetFileTimestamp
                   9738: # This function utilizes dirlist and returns the date stamp for
                   9739: # when it was last modified.  It will also return an error of -1
                   9740: # if an error occurs
                   9741: 
                   9742: sub GetFileTimestamp {
1.955     raeburn  9743:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9744:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9745:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9746:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9747:                                     undef,$getuserdir);
                   9748:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9749:         return -1;
                   9750:     }
                   9751:     if (ref($fileref) eq 'ARRAY') {
                   9752:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9753:         # @stats contains first the filename, then the stat output
                   9754:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9755:     } else {
                   9756:         return -1;
1.253     stredwic 9757:     }
1.26      www      9758: }
                   9759: 
1.712     albertel 9760: sub stat_file {
                   9761:     my ($uri) = @_;
1.787     albertel 9762:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9763: 
1.955     raeburn  9764:     my ($udom,$uname,$file);
1.712     albertel 9765:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9766: 	($udom,$uname,$file) =
1.811     albertel 9767: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9768: 	$file = 'userfiles/'.$file;
                   9769:     }
                   9770:     if ($uri =~ m-^/res/-) {
                   9771: 	($udom,$uname) = 
1.807     albertel 9772: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9773: 	$file = $uri;
                   9774:     }
                   9775: 
                   9776:     if (!$udom || !$uname || !$file) {
                   9777: 	# unable to handle the uri
                   9778: 	return ();
                   9779:     }
1.956     raeburn  9780:     my $getpropath;
                   9781:     if ($file =~ /^userfiles\//) {
                   9782:         $getpropath = 1;
                   9783:     }
1.1136    raeburn  9784:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9785:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9786:         return ();
                   9787:     } else {
                   9788:         if (ref($listref) eq 'ARRAY') {
                   9789:             my @stats = split('&',$listref->[0]);
                   9790: 	    shift(@stats); #filename is first
                   9791: 	    return @stats;
                   9792:         }
1.712     albertel 9793:     }
                   9794:     return ();
                   9795: }
                   9796: 
1.26      www      9797: # -------------------------------------------------------- Value of a Condition
                   9798: 
1.713     albertel 9799: # gets the value of a specific preevaluated condition
                   9800: #    stored in the string  $env{user.state.<cid>}
                   9801: # or looks up a condition reference in the bighash and if if hasn't
                   9802: # already been evaluated recurses into docondval to get the value of
                   9803: # the condition, then memoizing it to 
                   9804: #   $env{user.state.<cid>.<condition>}
1.40      www      9805: sub directcondval {
                   9806:     my $number=shift;
1.620     albertel 9807:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9808: 	&Apache::lonuserstate::evalstate();
                   9809:     }
1.713     albertel 9810:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9811: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9812:     } elsif ($number =~ /^_/) {
                   9813: 	my $sub_condition;
                   9814: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9815: 		&GDBM_READER(),0640)) {
                   9816: 	    $sub_condition=$bighash{'conditions'.$number};
                   9817: 	    untie(%bighash);
                   9818: 	}
                   9819: 	my $value = &docondval($sub_condition);
1.949     raeburn  9820: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9821: 	return $value;
                   9822:     }
1.620     albertel 9823:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9824:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9825:     } else {
                   9826:        return 2;
                   9827:     }
                   9828: }
                   9829: 
1.713     albertel 9830: # get the collection of conditions for this resource
1.26      www      9831: sub condval {
                   9832:     my $condidx=shift;
1.54      www      9833:     my $allpathcond='';
1.713     albertel 9834:     foreach my $cond (split(/\|/,$condidx)) {
                   9835: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9836: 	    $allpathcond.=
                   9837: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9838: 	}
1.191     harris41 9839:     }
1.54      www      9840:     $allpathcond=~s/\|$//;
1.713     albertel 9841:     return &docondval($allpathcond);
                   9842: }
                   9843: 
                   9844: #evaluates an expression of conditions
                   9845: sub docondval {
                   9846:     my ($allpathcond) = @_;
                   9847:     my $result=0;
                   9848:     if ($env{'request.course.id'}
                   9849: 	&& defined($allpathcond)) {
                   9850: 	my $operand='|';
                   9851: 	my @stack;
                   9852: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9853: 	    if ($chunk eq '(') {
                   9854: 		push @stack,($operand,$result);
                   9855: 	    } elsif ($chunk eq ')') {
                   9856: 		my $before=pop @stack;
                   9857: 		if (pop @stack eq '&') {
                   9858: 		    $result=$result>$before?$before:$result;
                   9859: 		} else {
                   9860: 		    $result=$result>$before?$result:$before;
                   9861: 		}
                   9862: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9863: 		$operand=$chunk;
                   9864: 	    } else {
                   9865: 		my $new=directcondval($chunk);
                   9866: 		if ($operand eq '&') {
                   9867: 		    $result=$result>$new?$new:$result;
                   9868: 		} else {
                   9869: 		    $result=$result>$new?$result:$new;
                   9870: 		}
                   9871: 	    }
                   9872: 	}
1.26      www      9873:     }
                   9874:     return $result;
1.421     albertel 9875: }
                   9876: 
                   9877: # ---------------------------------------------------- Devalidate courseresdata
                   9878: 
                   9879: sub devalidatecourseresdata {
                   9880:     my ($coursenum,$coursedomain)=@_;
                   9881:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9882:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9883: }
                   9884: 
1.763     www      9885: 
1.200     www      9886: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9887: #
                   9888: #  Parameters:
                   9889: #      $coursenum    - Number of the course.
                   9890: #      $coursedomain - Domain at which the course was created.
                   9891: #  Returns:
                   9892: #     A hash of the course parameters along (I think) with timestamps
                   9893: #     and version info.
1.877     foxr     9894: 
1.624     albertel 9895: sub get_courseresdata {
                   9896:     my ($coursenum,$coursedomain)=@_;
1.200     www      9897:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9898:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9899:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9900:     my %dumpreply;
1.417     albertel 9901:     unless (defined($cached)) {
1.624     albertel 9902: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9903: 	$result=\%dumpreply;
1.251     albertel 9904: 	my ($tmp) = keys(%dumpreply);
                   9905: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9906: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9907: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9908: 	    return $tmp;
1.416     albertel 9909: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9910: 	    $result=undef;
1.599     albertel 9911: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9912: 	}
                   9913:     }
1.624     albertel 9914:     return $result;
                   9915: }
                   9916: 
1.633     albertel 9917: sub devalidateuserresdata {
                   9918:     my ($uname,$udom)=@_;
                   9919:     my $hashid="$udom:$uname";
                   9920:     &devalidate_cache_new('userres',$hashid);
                   9921: }
                   9922: 
1.624     albertel 9923: sub get_userresdata {
                   9924:     my ($uname,$udom)=@_;
                   9925:     #most student don\'t have any data set, check if there is some data
                   9926:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9927: 
                   9928:     my $hashid="$udom:$uname";
                   9929:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9930:     if (!defined($cached)) {
                   9931: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9932: 	$result=\%resourcedata;
                   9933: 	&do_cache_new('userres',$hashid,$result,600);
                   9934:     }
                   9935:     my ($tmp)=keys(%$result);
                   9936:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9937: 	return $result;
                   9938:     }
                   9939:     #error 2 occurs when the .db doesn't exist
                   9940:     if ($tmp!~/error: 2 /) {
1.672     albertel 9941: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9942: 		 " Trying to get resource data for ".
                   9943: 		 $uname." at ".$udom.": ".
                   9944: 		 $tmp."</font>");
                   9945:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9946: 	#&EXT_cache_set($udom,$uname);
                   9947: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9948: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9949:     }
                   9950:     return $tmp;
                   9951: }
1.879     foxr     9952: #----------------------------------------------- resdata - return resource data
                   9953: #  Purpose:
                   9954: #    Return resource data for either users or for a course.
                   9955: #  Parameters:
                   9956: #     $name      - Course/user name.
                   9957: #     $domain    - Name of the domain the user/course is registered on.
                   9958: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9959: #     @which     - Array of names of resources desired.
                   9960: #  Returns:
                   9961: #     The value of the first reasource in @which that is found in the
                   9962: #     resource hash.
                   9963: #  Exceptional Conditions:
                   9964: #     If the $type passed in is not valid (not the string 'course' or 
                   9965: #     'user', an undefined  reference is returned.
                   9966: #     If none of the resources are found, an undef is returned
1.624     albertel 9967: sub resdata {
                   9968:     my ($name,$domain,$type,@which)=@_;
                   9969:     my $result;
                   9970:     if ($type eq 'course') {
                   9971: 	$result=&get_courseresdata($name,$domain);
                   9972:     } elsif ($type eq 'user') {
                   9973: 	$result=&get_userresdata($name,$domain);
                   9974:     }
                   9975:     if (!ref($result)) { return $result; }    
1.251     albertel 9976:     foreach my $item (@which) {
1.927     albertel 9977: 	if (defined($result->{$item->[0]})) {
                   9978: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9979: 	}
1.250     albertel 9980:     }
1.291     albertel 9981:     return undef;
1.200     www      9982: }
                   9983: 
1.1236    raeburn  9984: sub get_numsuppfiles {
                   9985:     my ($cnum,$cdom,$ignorecache)=@_;
                   9986:     my $hashid=$cnum.':'.$cdom;
                   9987:     my ($suppcount,$cached);
                   9988:     unless ($ignorecache) {
                   9989:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   9990:     }
                   9991:     unless (defined($cached)) {
                   9992:         my $chome=&homeserver($cnum,$cdom);
                   9993:         unless ($chome eq 'no_host') {
                   9994:             ($suppcount,my $errors) = (0,0);
                   9995:             my $suppmap = 'supplemental.sequence';
                   9996:             ($suppcount,$errors) = 
                   9997:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   9998:         }
                   9999:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10000:     }
                   10001:     return $suppcount;
                   10002: }
                   10003: 
1.379     matthew  10004: #
                   10005: # EXT resource caching routines
                   10006: #
                   10007: 
                   10008: sub clear_EXT_cache_status {
1.383     albertel 10009:     &delenv('cache.EXT.');
1.379     matthew  10010: }
                   10011: 
                   10012: sub EXT_cache_status {
                   10013:     my ($target_domain,$target_user) = @_;
1.383     albertel 10014:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10015:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10016:         # We know already the user has no data
                   10017:         return 1;
                   10018:     } else {
                   10019:         return 0;
                   10020:     }
                   10021: }
                   10022: 
                   10023: sub EXT_cache_set {
                   10024:     my ($target_domain,$target_user) = @_;
1.383     albertel 10025:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10026:     #&appenv({$cachename => time});
1.379     matthew  10027: }
                   10028: 
1.28      www      10029: # --------------------------------------------------------- Value of a Variable
1.58      www      10030: sub EXT {
1.715     albertel 10031: 
1.1228    raeburn  10032:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10033:     unless ($varname) { return ''; }
1.218     albertel 10034:     #get real user name/domain, courseid and symb
                   10035:     my $courseid;
1.359     albertel 10036:     my $publicuser;
1.427     www      10037:     if ($symbparm) {
                   10038: 	$symbparm=&get_symb_from_alias($symbparm);
                   10039:     }
1.218     albertel 10040:     if (!($uname && $udom)) {
1.790     albertel 10041:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10042:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10043:     } else {
1.620     albertel 10044: 	$courseid=$env{'request.course.id'};
1.218     albertel 10045:     }
1.48      www      10046:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10047:     my $rest;
1.320     albertel 10048:     if (defined($therest[0])) {
1.48      www      10049:        $rest=join('.',@therest);
                   10050:     } else {
                   10051:        $rest='';
                   10052:     }
1.320     albertel 10053: 
1.57      www      10054:     my $qualifierrest=$qualifier;
                   10055:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10056:     my $spacequalifierrest=$space;
                   10057:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10058:     if ($realm eq 'user') {
1.48      www      10059: # --------------------------------------------------------------- user.resource
                   10060: 	if ($space eq 'resource') {
1.651     albertel 10061: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10062: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10063: 		 &&
1.744     albertel 10064: 		 ($symbparm eq &symbread()) ) {	
                   10065: 		# if we are in the middle of processing the resource the
                   10066: 		# get the value we are planning on committing
                   10067:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10068:                     return $Apache::lonhomework::results{$qualifierrest};
                   10069:                 } else {
                   10070:                     return $Apache::lonhomework::history{$qualifierrest};
                   10071:                 }
1.335     albertel 10072: 	    } else {
1.359     albertel 10073: 		my %restored;
1.620     albertel 10074: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10075: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10076: 		} else {
                   10077: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10078: 		}
1.335     albertel 10079: 		return $restored{$qualifierrest};
                   10080: 	    }
1.48      www      10081: # ----------------------------------------------------------------- user.access
                   10082:         } elsif ($space eq 'access') {
1.218     albertel 10083: 	    # FIXME - not supporting calls for a specific user
1.48      www      10084:             return &allowed($qualifier,$rest);
                   10085: # ------------------------------------------ user.preferences, user.environment
                   10086:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10087: 	    if (($uname eq $env{'user.name'}) &&
                   10088: 		($udom eq $env{'user.domain'})) {
                   10089: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10090: 	    } else {
1.359     albertel 10091: 		my %returnhash;
                   10092: 		if (!$publicuser) {
                   10093: 		    %returnhash=&userenvironment($udom,$uname,
                   10094: 						 $qualifierrest);
                   10095: 		}
1.218     albertel 10096: 		return $returnhash{$qualifierrest};
                   10097: 	    }
1.48      www      10098: # ----------------------------------------------------------------- user.course
                   10099:         } elsif ($space eq 'course') {
1.218     albertel 10100: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10101:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10102: # ------------------------------------------------------------------- user.role
                   10103:         } elsif ($space eq 'role') {
1.218     albertel 10104: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10105:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10106:             if ($qualifier eq 'value') {
                   10107: 		return $role;
                   10108:             } elsif ($qualifier eq 'extent') {
                   10109:                 return $where;
                   10110:             }
                   10111: # ----------------------------------------------------------------- user.domain
                   10112:         } elsif ($space eq 'domain') {
1.218     albertel 10113:             return $udom;
1.48      www      10114: # ------------------------------------------------------------------- user.name
                   10115:         } elsif ($space eq 'name') {
1.218     albertel 10116:             return $uname;
1.48      www      10117: # ---------------------------------------------------- Any other user namespace
1.29      www      10118:         } else {
1.359     albertel 10119: 	    my %reply;
                   10120: 	    if (!$publicuser) {
                   10121: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10122: 	    }
                   10123: 	    return $reply{$qualifierrest};
1.48      www      10124:         }
1.236     www      10125:     } elsif ($realm eq 'query') {
                   10126: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10127:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10128: 						[$spacequalifierrest]);
1.620     albertel 10129: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10130:    } elsif ($realm eq 'request') {
1.48      www      10131: # ------------------------------------------------------------- request.browser
                   10132:         if ($space eq 'browser') {
1.1145    bisitz   10133:             return $env{'browser.'.$qualifier};
1.57      www      10134: # ------------------------------------------------------------ request.filename
                   10135:         } else {
1.620     albertel 10136:             return $env{'request.'.$spacequalifierrest};
1.29      www      10137:         }
1.28      www      10138:     } elsif ($realm eq 'course') {
1.48      www      10139: # ---------------------------------------------------------- course.description
1.620     albertel 10140:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10141:     } elsif ($realm eq 'resource') {
1.165     www      10142: 
1.620     albertel 10143: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10144: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10145: 	}
1.693     albertel 10146: 
1.1232    raeburn  10147:         if ($qualifier eq '') {
                   10148: 	    if ($space eq 'title') {
                   10149: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10150: 	        return &gettitle($symbparm);
                   10151: 	    }
1.693     albertel 10152: 	
1.1232    raeburn  10153: 	    if ($space eq 'map') {
                   10154: 	        my ($map) = &decode_symb($symbparm);
                   10155: 	        return &symbread($map);
                   10156: 	    }
                   10157:             if ($space eq 'maptitle') {
                   10158:                 my ($map) = &decode_symb($symbparm);
                   10159:                 return &gettitle($map);
                   10160:             }
                   10161: 	    if ($space eq 'filename') {
                   10162: 	        if ($symbparm) {
                   10163: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10164: 	        }
                   10165: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10166: 	    }
1.1232    raeburn  10167: 
1.1233    raeburn  10168:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10169:                 if ($space eq 'visibleparts') {
                   10170:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10171:                     my $item;
                   10172:                     if (ref($navmap)) {
                   10173:                         my $res = $navmap->getBySymb($symbparm);
                   10174:                         my $parts = $res->parts();
                   10175:                         if (ref($parts) eq 'ARRAY') {
                   10176:                             $item = join(',',@{$parts});
                   10177:                         }
                   10178:                         undef($navmap);
1.1232    raeburn  10179:                     }
1.1233    raeburn  10180:                     return $item;
1.1232    raeburn  10181:                 }
                   10182:             }
                   10183:         }
1.693     albertel 10184: 
                   10185: 	my ($section, $group, @groups);
1.593     albertel 10186: 	my ($courselevelm,$courselevel);
1.1228    raeburn  10187:         if (($courseid eq '') && ($cid)) {
                   10188:             $courseid = $cid;
                   10189:         }
                   10190: 	if (($symbparm && $courseid) && 
                   10191: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      10192: 
1.218     albertel 10193: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10194: 
1.60      www      10195: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10196: 	    my $symbp=$symbparm;
1.735     albertel 10197: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10198: 
                   10199: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10200: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10201: 
1.620     albertel 10202: 	    if (($env{'user.name'} eq $uname) &&
                   10203: 		($env{'user.domain'} eq $udom)) {
                   10204: 		$section=$env{'request.course.sec'};
1.733     raeburn  10205:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10206:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10207: 	    } else {
1.539     albertel 10208: 		if (! defined($usection)) {
1.551     albertel 10209: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10210: 		} else {
                   10211: 		    $section = $usection;
                   10212: 		}
1.733     raeburn  10213:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10214: 	    }
                   10215: 
                   10216: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10217: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10218: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10219: 
1.593     albertel 10220: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10221: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10222: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10223: 
1.60      www      10224: # ----------------------------------------------------------- first, check user
1.624     albertel 10225: 
                   10226: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10227: 				       ([$courselevelr,'resource'],
                   10228: 					[$courselevelm,'map'     ],
                   10229: 					[$courselevel, 'course'  ]));
1.931     albertel 10230: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10231: 
1.594     albertel 10232: # ------------------------------------------------ second, check some of course
1.684     raeburn  10233:             my $coursereply;
1.691     raeburn  10234:             if (@groups > 0) {
                   10235:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10236:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10237:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10238:             }
1.96      www      10239: 
1.684     raeburn  10240: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10241: 				  $env{'course.'.$courseid.'.domain'},
                   10242: 				  'course',
                   10243: 				  ([$seclevelr,   'resource'],
                   10244: 				   [$seclevelm,   'map'     ],
                   10245: 				   [$seclevel,    'course'  ],
                   10246: 				   [$courselevelr,'resource']));
                   10247: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10248: 
1.60      www      10249: # ------------------------------------------------------ third, check map parms
1.218     albertel 10250: 	    my %parmhash=();
                   10251: 	    my $thisparm='';
                   10252: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10253: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10254: 		    &GDBM_READER(),0640)) {
1.218     albertel 10255: 		$thisparm=$parmhash{$symbparm};
                   10256: 		untie(%parmhash);
                   10257: 	    }
1.927     albertel 10258: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10259: 	}
1.594     albertel 10260: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10261: 
1.218     albertel 10262: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10263: 	my $filename;
                   10264: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10265: 	if ($symbparm) {
1.409     www      10266: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10267: 	} else {
1.620     albertel 10268: 	    $filename=$env{'request.filename'};
1.282     albertel 10269: 	}
                   10270: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10271: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10272: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10273: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10274: 
1.927     albertel 10275: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10276: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10277: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10278: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10279: 				     $env{'course.'.$courseid.'.domain'},
                   10280: 				     'course',
1.927     albertel 10281: 				     ([$courselevelm,'map'   ],
                   10282: 				      [$courselevel, 'course']));
                   10283: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10284: 	}
1.145     www      10285: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10286: 	unless ($space eq '0') {
1.336     albertel 10287: 	    my @parts=split(/_/,$space);
                   10288: 	    my $id=pop(@parts);
                   10289: 	    my $part=join('_',@parts);
                   10290: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10291: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10292: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10293: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10294: 	}
1.395     albertel 10295: 	if ($recurse) { return undef; }
                   10296: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10297: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10298: # ---------------------------------------------------- Any other user namespace
                   10299:     } elsif ($realm eq 'environment') {
                   10300: # ----------------------------------------------------------------- environment
1.620     albertel 10301: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10302: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10303: 	} else {
1.770     albertel 10304: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10305: 		return '';
                   10306: 	    }
1.219     albertel 10307: 	    my %returnhash=&userenvironment($udom,$uname,
                   10308: 					    $spacequalifierrest);
                   10309: 	    return $returnhash{$spacequalifierrest};
                   10310: 	}
1.28      www      10311:     } elsif ($realm eq 'system') {
1.48      www      10312: # ----------------------------------------------------------------- system.time
                   10313: 	if ($space eq 'time') {
                   10314: 	    return time;
                   10315:         }
1.696     albertel 10316:     } elsif ($realm eq 'server') {
                   10317: # ----------------------------------------------------------------- system.time
                   10318: 	if ($space eq 'name') {
                   10319: 	    return $ENV{'SERVER_NAME'};
                   10320:         }
1.28      www      10321:     }
1.48      www      10322:     return '';
1.61      www      10323: }
                   10324: 
1.927     albertel 10325: sub get_reply {
                   10326:     my ($reply_value) = @_;
1.940     raeburn  10327:     if (ref($reply_value) eq 'ARRAY') {
                   10328:         if (wantarray) {
                   10329: 	    return @$reply_value;
                   10330:         }
                   10331:         return $reply_value->[0];
                   10332:     } else {
                   10333:         return $reply_value;
1.927     albertel 10334:     }
                   10335: }
                   10336: 
1.691     raeburn  10337: sub check_group_parms {
                   10338:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10339:     my @groupitems = ();
                   10340:     my $resultitem;
1.927     albertel 10341:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10342:     foreach my $group (@{$groups}) {
                   10343:         foreach my $level (@levels) {
1.927     albertel 10344:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10345:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10346:         }
                   10347:     }
                   10348:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10349:                             $env{'course.'.$courseid.'.domain'},
                   10350:                                      'course',@groupitems);
                   10351:     return $coursereply;
                   10352: }
                   10353: 
                   10354: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10355:     my ($courseid,@groups) = @_;
                   10356:     @groups = sort(@groups);
1.691     raeburn  10357:     return @groups;
                   10358: }
                   10359: 
1.395     albertel 10360: sub packages_tab_default {
                   10361:     my ($uri,$varname)=@_;
                   10362:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10363: 
                   10364:     my (@extension,@specifics,$do_default);
                   10365:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10366: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10367: 	if ($pack_type eq 'default') {
                   10368: 	    $do_default=1;
                   10369: 	} elsif ($pack_type eq 'extension') {
                   10370: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10371: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10372: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10373: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10374: 	}
                   10375:     }
                   10376:     # first look for a package that matches the requested part id
                   10377:     foreach my $package (@specifics) {
                   10378: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10379: 	next if ($pack_part ne $part);
                   10380: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10381: 	    return $packagetab{"$pack_type&$name&default"};
                   10382: 	}
                   10383:     }
                   10384:     # look for any possible matching non extension_ package
                   10385:     foreach my $package (@specifics) {
                   10386: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10387: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10388: 	    return $packagetab{"$pack_type&$name&default"};
                   10389: 	}
1.585     albertel 10390: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10391: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10392: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10393: 	}
                   10394:     }
1.738     albertel 10395:     # look for any posible extension_ match
                   10396:     foreach my $package (@extension) {
                   10397: 	my ($package,$pack_type)=@{$package};
                   10398: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10399: 	    return $packagetab{"$pack_type&$name&default"};
                   10400: 	}
                   10401: 	if (defined($packagetab{$package."&$name&default"})) {
                   10402: 	    return $packagetab{$package."&$name&default"};
                   10403: 	}
                   10404:     }
                   10405:     # look for a global default setting
                   10406:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10407: 	return $packagetab{"default&$name&default"};
                   10408:     }
1.395     albertel 10409:     return undef;
                   10410: }
                   10411: 
1.334     albertel 10412: sub add_prefix_and_part {
                   10413:     my ($prefix,$part)=@_;
                   10414:     my $keyroot;
                   10415:     if (defined($prefix) && $prefix !~ /^__/) {
                   10416: 	# prefix that has a part already
                   10417: 	$keyroot=$prefix;
                   10418:     } elsif (defined($prefix)) {
                   10419: 	# prefix that is missing a part
                   10420: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10421:     } else {
                   10422: 	# no prefix at all
                   10423: 	if (defined($part)) { $keyroot='_'.$part; }
                   10424:     }
                   10425:     return $keyroot;
                   10426: }
                   10427: 
1.71      www      10428: # ---------------------------------------------------------------- Get metadata
                   10429: 
1.599     albertel 10430: my %metaentry;
1.1070    www      10431: my %importedpartids;
1.71      www      10432: sub metadata {
1.176     www      10433:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10434:     $uri=&declutter($uri);
1.288     albertel 10435:     # if it is a non metadata possible uri return quickly
1.529     albertel 10436:     if (($uri eq '') || 
                   10437: 	(($uri =~ m|^/*adm/|) && 
1.1217    raeburn  10438: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10439:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10440: 	return undef;
                   10441:     }
1.1261    raeburn  10442:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10443: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10444: 	return undef;
1.288     albertel 10445:     }
1.73      www      10446:     my $filename=$uri;
                   10447:     $uri=~s/\.meta$//;
1.172     www      10448: #
                   10449: # Is the metadata already cached?
1.177     www      10450: # Look at timestamp of caching
1.172     www      10451: # Everything is cached by the main uri, libraries are never directly cached
                   10452: #
1.428     albertel 10453:     if (!defined($liburi)) {
1.599     albertel 10454: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10455: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10456:     }
                   10457:     {
1.1069    www      10458: # Imported parts would go here
1.1070    www      10459:         my %importedids=();
                   10460:         my @origfileimportpartids=();
1.1069    www      10461:         my $importedparts=0;
1.172     www      10462: #
                   10463: # Is this a recursive call for a library?
                   10464: #
1.599     albertel 10465: #	if (! exists($metacache{$uri})) {
                   10466: #	    $metacache{$uri}={};
                   10467: #	}
1.924     albertel 10468: 	my $cachetime = 60*60;
1.171     www      10469:         if ($liburi) {
                   10470: 	    $liburi=&declutter($liburi);
                   10471:             $filename=$liburi;
1.401     bowersj2 10472:         } else {
1.599     albertel 10473: 	    &devalidate_cache_new('meta',$uri);
                   10474: 	    undef(%metaentry);
1.401     bowersj2 10475: 	}
1.140     www      10476:         my %metathesekeys=();
1.73      www      10477:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10478: 	my $metastring;
1.1140    www      10479: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10480: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10481: 	    $metastring = 
1.929     albertel 10482: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10483: 					  ('grade_target' => 'meta'));
                   10484: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10485: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10486:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10487: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10488: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10489: 	    $metastring=&getfile($file);
1.489     albertel 10490: 	}
1.208     albertel 10491:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10492:         my $token;
1.140     www      10493:         undef %metathesekeys;
1.71      www      10494:         while ($token=$parser->get_token) {
1.339     albertel 10495: 	    if ($token->[0] eq 'S') {
                   10496: 		if (defined($token->[2]->{'package'})) {
1.172     www      10497: #
                   10498: # This is a package - get package info
                   10499: #
1.339     albertel 10500: 		    my $package=$token->[2]->{'package'};
                   10501: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10502: 		    if (defined($token->[2]->{'id'})) { 
                   10503: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10504: 		    }
1.599     albertel 10505: 		    if ($metaentry{':packages'}) {
                   10506: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10507: 		    } else {
1.599     albertel 10508: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10509: 		    }
1.736     albertel 10510: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10511: 			my $part=$keyroot;
                   10512: 			$part=~s/^\_//;
1.736     albertel 10513: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10514: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10515: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10516: 			    # ignore package.tab specified default values
                   10517:                             # here &package_tab_default() will fetch those
                   10518: 			    if ($subp eq 'default') { next; }
1.736     albertel 10519: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10520: 			    my $unikey;
                   10521: 			    if ($pack =~ /_0$/) {
                   10522: 				$unikey='parameter_0_'.$name;
                   10523: 				$part=0;
                   10524: 			    } else {
                   10525: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10526: 			    }
1.339     albertel 10527: 			    if ($subp eq 'display') {
                   10528: 				$value.=' [Part: '.$part.']';
                   10529: 			    }
1.599     albertel 10530: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10531: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10532: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10533: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10534: 			    }
1.599     albertel 10535: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10536: 				$metaentry{':'.$unikey}=
                   10537: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10538: 			    }
1.339     albertel 10539: 			}
                   10540: 		    }
                   10541: 		} else {
1.172     www      10542: #
                   10543: # This is not a package - some other kind of start tag
1.339     albertel 10544: #
                   10545: 		    my $entry=$token->[1];
1.1068    www      10546: 		    my $unikey='';
1.175     www      10547: 
1.339     albertel 10548: 		    if ($entry eq 'import') {
1.175     www      10549: #
                   10550: # Importing a library here
1.339     albertel 10551: #
1.1067    www      10552:                         my $location=$parser->get_text('/import');
                   10553:                         my $dir=$filename;
                   10554:                         $dir=~s|[^/]*$||;
                   10555:                         $location=&filelocation($dir,$location);
1.1069    www      10556:                        
1.1068    www      10557:                         my $importmode=$token->[2]->{'importmode'};
                   10558:                         if ($importmode eq 'problem') {
1.1069    www      10559: # Import as problem/response
1.1068    www      10560:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10561:                         } elsif ($importmode eq 'part') {
                   10562: # Import as part(s)
1.1069    www      10563:                            $importedparts=1;
                   10564: # We need to get the original file and the imported file to get the part order correct
                   10565: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10566: # Load and inspect original file
1.1070    www      10567:                            if ($#origfileimportpartids<0) {
                   10568:                               undef(%importedpartids);
                   10569:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10570:                               my $origfile=&getfile($origfilelocation);
                   10571:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10572:                            }
                   10573: 
1.1069    www      10574: # Load and inspect imported file
                   10575:                            my $impfile=&getfile($location);
                   10576:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10577:                            if ($#impfilepartids>=0) {
                   10578: # This problem had parts
1.1070    www      10579:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10580:                            } else {
                   10581: # Importing by turning a single problem into a problem part
                   10582: # It gets the import-tags ID as part-ID
                   10583:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10584:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10585:                            }
1.1068    www      10586:                         } else {
                   10587: # Normal import
                   10588:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10589:                            if (defined($token->[2]->{'id'})) {
                   10590:                               $unikey.='_'.$token->[2]->{'id'};
                   10591:                            }
1.1067    www      10592:                         }
                   10593: 
1.339     albertel 10594: 			if ($depthcount<20) {
1.736     albertel 10595: 			    my $metadata = 
                   10596: 				&metadata($uri,'keys', $location,$unikey,
                   10597: 					  $depthcount+1);
                   10598: 			    foreach my $meta (split(',',$metadata)) {
                   10599: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10600: 				$metathesekeys{$meta}=1;
1.339     albertel 10601: 			    }
1.1068    www      10602: 			
                   10603:                         }
1.1067    www      10604: 		    } else {
                   10605: #
                   10606: # Not importing, some other kind of non-package, non-library start tag
                   10607: # 
                   10608:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10609:                         if (defined($token->[2]->{'id'})) {
                   10610:                             $unikey.='_'.$token->[2]->{'id'};
                   10611:                         }
1.339     albertel 10612: 			if (defined($token->[2]->{'name'})) { 
                   10613: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10614: 			}
                   10615: 			$metathesekeys{$unikey}=1;
1.736     albertel 10616: 			foreach my $param (@{$token->[3]}) {
                   10617: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10618: 				$token->[2]->{$param};
1.339     albertel 10619: 			}
                   10620: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10621: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10622: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10623: 		 # only ws inside the tag, and not in default, so use default
                   10624: 		 # as value
1.599     albertel 10625: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10626: 			} elsif ( $internaltext =~ /\S/ ) {
                   10627: 		  # something interesting inside the tag
                   10628: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10629: 			} else {
1.908     albertel 10630: 		  # no interesting values, don't set a default
1.339     albertel 10631: 			}
1.172     www      10632: # end of not-a-package not-a-library import
1.339     albertel 10633: 		    }
1.172     www      10634: # end of not-a-package start tag
1.339     albertel 10635: 		}
1.172     www      10636: # the next is the end of "start tag"
1.339     albertel 10637: 	    }
                   10638: 	}
1.483     albertel 10639: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10640: 	$extension = lc($extension);
                   10641: 	if ($extension eq 'htm') { $extension='html'; }
                   10642: 
1.737     albertel 10643: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10644: 	    #no specific packages #how's our extension
                   10645: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10646: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10647: 					 \%metathesekeys);
                   10648: 	}
1.883     albertel 10649: 
                   10650: 	if (!exists($metaentry{':packages'})
                   10651: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10652: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10653: 		#no specific packages well let's get default then
                   10654: 		if ($key!~/^default&/) { next; }
1.488     albertel 10655: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10656: 					     \%metathesekeys);
                   10657: 	    }
                   10658: 	}
1.338     www      10659: # are there custom rights to evaluate
1.599     albertel 10660: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10661: 
1.338     www      10662:     #
                   10663:     # Importing a rights file here
1.339     albertel 10664:     #
                   10665: 	    unless ($depthcount) {
1.599     albertel 10666: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10667: 		my $dir=$filename;
                   10668: 		$dir=~s|[^/]*$||;
                   10669: 		$location=&filelocation($dir,$location);
1.736     albertel 10670: 		my $rights_metadata =
                   10671: 		    &metadata($uri,'keys',$location,'_rights',
                   10672: 			      $depthcount+1);
                   10673: 		foreach my $rights (split(',',$rights_metadata)) {
                   10674: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10675: 		    $metathesekeys{$rights}=1;
1.339     albertel 10676: 		}
                   10677: 	    }
                   10678: 	}
1.737     albertel 10679: 	# uniqifiy package listing
                   10680: 	my %seen;
                   10681: 	my @uniq_packages =
                   10682: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10683: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10684: 
1.1070    www      10685:         if ($importedparts) {
                   10686: # We had imported parts and need to rebuild partorder
                   10687:            $metaentry{':partorder'}='';
                   10688:            $metathesekeys{'partorder'}=1;
                   10689:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10690:                if ($origfileimportpartids[$index] eq 'part') {
                   10691: # original part, part of the problem
                   10692:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10693:                } else {
                   10694: # we have imported parts at this position
                   10695:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10696:                }
                   10697:            }
                   10698:            $metaentry{':partorder'}=~s/^\,//;
                   10699:         }
                   10700: 
1.737     albertel 10701: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10702: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  10703: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 10704: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10705: # this is the end of "was not already recently cached
1.71      www      10706:     }
1.599     albertel 10707:     return $metaentry{':'.$what};
1.261     albertel 10708: }
                   10709: 
1.488     albertel 10710: sub metadata_create_package_def {
1.483     albertel 10711:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10712:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10713:     if ($subp eq 'default') { next; }
                   10714:     
1.599     albertel 10715:     if (defined($metaentry{':packages'})) {
                   10716: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10717:     } else {
1.599     albertel 10718: 	$metaentry{':packages'}=$package;
1.483     albertel 10719:     }
                   10720:     my $value=$packagetab{$key};
                   10721:     my $unikey;
                   10722:     $unikey='parameter_0_'.$name;
1.599     albertel 10723:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10724:     $$metathesekeys{$unikey}=1;
1.599     albertel 10725:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10726: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10727:     }
1.599     albertel 10728:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10729: 	$metaentry{':'.$unikey}=
                   10730: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10731:     }
                   10732: }
                   10733: 
1.261     albertel 10734: sub metadata_generate_part0 {
                   10735:     my ($metadata,$metacache,$uri) = @_;
                   10736:     my %allnames;
1.737     albertel 10737:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10738: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10739: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10740: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10741: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10742: 	    $allnames{$name}=$part;
                   10743: 	  }
                   10744: 	}
                   10745:     }
                   10746:     foreach my $name (keys(%allnames)) {
                   10747:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10748:       my $key=":parameter_0_$name";
1.261     albertel 10749:       $$metacache{"$key.part"}='0';
                   10750:       $$metacache{"$key.name"}=$name;
1.428     albertel 10751:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10752: 					   $allnames{$name}.'_'.$name.
                   10753: 					   '.type'};
1.428     albertel 10754:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10755: 			     '.display'};
1.644     www      10756:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10757:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10758:       $$metacache{"$key.display"}=$olddis;
                   10759:     }
1.71      www      10760: }
                   10761: 
1.764     albertel 10762: # ------------------------------------------------------ Devalidate title cache
                   10763: 
                   10764: sub devalidate_title_cache {
                   10765:     my ($url)=@_;
                   10766:     if (!$env{'request.course.id'}) { return; }
                   10767:     my $symb=&symbread($url);
                   10768:     if (!$symb) { return; }
                   10769:     my $key=$env{'request.course.id'}."\0".$symb;
                   10770:     &devalidate_cache_new('title',$key);
                   10771: }
                   10772: 
1.1014    droeschl 10773: # ------------------------------------------------- Get the title of a course
                   10774: 
                   10775: sub current_course_title {
                   10776:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10777: }
1.301     www      10778: # ------------------------------------------------- Get the title of a resource
                   10779: 
                   10780: sub gettitle {
                   10781:     my $urlsymb=shift;
                   10782:     my $symb=&symbread($urlsymb);
1.534     albertel 10783:     if ($symb) {
1.620     albertel 10784: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10785: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10786: 	if (defined($cached)) { 
                   10787: 	    return $result;
                   10788: 	}
1.534     albertel 10789: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10790: 	my $title='';
1.907     albertel 10791: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10792: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10793: 	} else {
                   10794: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10795: 		    &GDBM_READER(),0640)) {
                   10796: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10797: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10798: 		untie(%bighash);
                   10799: 	    }
1.534     albertel 10800: 	}
                   10801: 	$title=~s/\&colon\;/\:/gs;
                   10802: 	if ($title) {
1.1159    www      10803: # Remember both $symb and $title for dynamic metadata
                   10804:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10805:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10806: # Cache this title and then return it
1.599     albertel 10807: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10808: 	}
                   10809: 	$urlsymb=$url;
                   10810:     }
                   10811:     my $title=&metadata($urlsymb,'title');
                   10812:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10813:     return $title;
1.301     www      10814: }
1.613     albertel 10815: 
1.614     albertel 10816: sub get_slot {
                   10817:     my ($which,$cnum,$cdom)=@_;
                   10818:     if (!$cnum || !$cdom) {
1.790     albertel 10819: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10820: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10821: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10822:     }
1.703     albertel 10823:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10824:     my %slotinfo;
                   10825:     if (exists($remembered{$key})) {
                   10826: 	$slotinfo{$which} = $remembered{$key};
                   10827:     } else {
                   10828: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10829: 	&Apache::lonhomework::showhash(%slotinfo);
                   10830: 	my ($tmp)=keys(%slotinfo);
                   10831: 	if ($tmp=~/^error:/) { return (); }
                   10832: 	$remembered{$key} = $slotinfo{$which};
                   10833:     }
1.616     albertel 10834:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10835: 	return %{$slotinfo{$which}};
                   10836:     }
                   10837:     return $slotinfo{$which};
1.614     albertel 10838: }
1.1150    raeburn  10839: 
                   10840: sub get_reservable_slots {
                   10841:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10842:     my $now = time;
                   10843:     my $reservable_info;
                   10844:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10845:     if (exists($remembered{$key})) {
                   10846:         $reservable_info = $remembered{$key};
                   10847:     } else {
                   10848:         my %resv;
                   10849:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10850:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10851:         $reservable_info = \%resv;
                   10852:         $remembered{$key} = $reservable_info;
                   10853:     }
                   10854:     return $reservable_info;
                   10855: }
                   10856: 
                   10857: sub get_course_slots {
                   10858:     my ($cnum,$cdom) = @_;
                   10859:     my $hashid=$cnum.':'.$cdom;
                   10860:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10861:     if (defined($cached)) {
                   10862:         if (ref($result) eq 'HASH') {
                   10863:             return %{$result};
                   10864:         }
                   10865:     } else {
                   10866:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10867:         my ($tmp) = keys(%slots);
                   10868:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  10869:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10870:             return %slots;
                   10871:         }
                   10872:     }
                   10873:     return;
                   10874: }
                   10875: 
                   10876: sub devalidate_slots_cache {
                   10877:     my ($cnum,$cdom)=@_;
                   10878:     my $hashid=$cnum.':'.$cdom;
                   10879:     &devalidate_cache_new('allslots',$hashid);
                   10880: }
                   10881: 
1.1181    raeburn  10882: sub get_coursechange {
                   10883:     my ($cdom,$cnum) = @_;
                   10884:     if ($cdom eq '' || $cnum eq '') {
                   10885:         return unless ($env{'request.course.id'});
                   10886:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10887:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10888:     }
                   10889:     my $hashid=$cdom.'_'.$cnum;
                   10890:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10891:     if ((defined($cached)) && ($change ne '')) {
                   10892:         return $change;
                   10893:     } else {
                   10894:         my %crshash;
                   10895:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10896:         if ($crshash{'internal.contentchange'} eq '') {
                   10897:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10898:             if ($change eq '') {
                   10899:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10900:                 $change = $crshash{'internal.created'};
                   10901:             }
                   10902:         } else {
                   10903:             $change = $crshash{'internal.contentchange'};
                   10904:         }
                   10905:         my $cachetime = 600;
                   10906:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10907:     }
                   10908:     return $change;
                   10909: }
                   10910: 
                   10911: sub devalidate_coursechange_cache {
                   10912:     my ($cnum,$cdom)=@_;
                   10913:     my $hashid=$cnum.':'.$cdom;
                   10914:     &devalidate_cache_new('crschange',$hashid);
                   10915: }
                   10916: 
1.31      www      10917: # ------------------------------------------------- Update symbolic store links
                   10918: 
                   10919: sub symblist {
                   10920:     my ($mapname,%newhash)=@_;
1.438     www      10921:     $mapname=&deversion(&declutter($mapname));
1.31      www      10922:     my %hash;
1.620     albertel 10923:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10924:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10925:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10926: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10927: 		next if ($url eq 'last_known'
                   10928: 			 && $env{'form.no_update_last_known'});
                   10929: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10930: 						    $newhash{$url}->[1],
                   10931: 						    $newhash{$url}->[0]);
1.191     harris41 10932:             }
1.31      www      10933:             if (untie(%hash)) {
                   10934: 		return 'ok';
                   10935:             }
                   10936:         }
                   10937:     }
                   10938:     return 'error';
1.212     www      10939: }
                   10940: 
                   10941: # --------------------------------------------------------------- Verify a symb
                   10942: 
                   10943: sub symbverify {
1.1190    raeburn  10944:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10945:     my $thisfn=$thisurl;
1.439     www      10946:     $thisfn=&declutter($thisfn);
1.215     www      10947: # direct jump to resource in page or to a sequence - will construct own symbs
                   10948:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10949: # check URL part
1.409     www      10950:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10951: 
1.431     www      10952:     unless ($url eq $thisfn) { return 0; }
1.213     www      10953: 
1.216     www      10954:     $symb=&symbclean($symb);
1.510     www      10955:     $thisurl=&deversion($thisurl);
1.439     www      10956:     $thisfn=&deversion($thisfn);
1.213     www      10957: 
                   10958:     my %bighash;
                   10959:     my $okay=0;
1.431     www      10960: 
1.620     albertel 10961:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10962:                             &GDBM_READER(),0640)) {
1.1204    raeburn  10963:         my $noclutter;
1.1032    raeburn  10964:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10965:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  10966:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10967:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10968:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10969:                 $noclutter = 1;
                   10970:             }
                   10971:         }
                   10972:         my $ids;
                   10973:         if ($noclutter) {
                   10974:             $ids=$bighash{'ids_'.$thisurl};
                   10975:         } else {
                   10976:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10977:         }
1.1102    raeburn  10978:         unless ($ids) {
                   10979:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   10980:             $ids=$bighash{$idkey};
1.216     www      10981:         }
                   10982:         if ($ids) {
                   10983: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  10984:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  10985:                 $symb =~ s/\?.+$//;
1.1202    raeburn  10986:             }
1.800     albertel 10987: 	    foreach my $id (split(/\,/,$ids)) {
                   10988: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10989:                if (
                   10990:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  10991:    eq $symb) {
                   10992:                    if (ref($encstate)) {
                   10993:                        $$encstate = $bighash{'encrypted_'.$id};
                   10994:                    }
1.620     albertel 10995: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  10996: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   10997:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  10998: 		       $okay=1;
1.1202    raeburn  10999:                        last;
1.582     albertel 11000: 		   }
                   11001: 	       }
1.216     www      11002: 	   }
                   11003:         }
1.213     www      11004: 	untie(%bighash);
                   11005:     }
                   11006:     return $okay;
1.31      www      11007: }
                   11008: 
1.210     www      11009: # --------------------------------------------------------------- Clean-up symb
                   11010: 
                   11011: sub symbclean {
                   11012:     my $symb=shift;
1.568     albertel 11013:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11014: # remove version from map
                   11015:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11016: 
1.210     www      11017: # remove version from URL
                   11018:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11019: 
1.507     www      11020: # remove wrapper
                   11021: 
1.510     www      11022:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11023:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11024:     return $symb;
1.409     www      11025: }
                   11026: 
                   11027: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11028: 
                   11029: sub encode_symb {
                   11030:     my ($map,$resid,$url)=@_;
                   11031:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11032: }
1.409     www      11033: 
                   11034: sub decode_symb {
1.568     albertel 11035:     my $symb=shift;
                   11036:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11037:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11038:     return (&fixversion($map),$resid,&fixversion($url));
                   11039: }
                   11040: 
                   11041: sub fixversion {
                   11042:     my $fn=shift;
1.609     banghart 11043:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11044:     my %bighash;
                   11045:     my $uri=&clutter($fn);
1.620     albertel 11046:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11047: # is this cached?
1.599     albertel 11048:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11049:     if (defined($cached)) { return $result; }
                   11050: # unfortunately not cached, or expired
1.620     albertel 11051:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11052: 	    &GDBM_READER(),0640)) {
                   11053:  	if ($bighash{'version_'.$uri}) {
                   11054:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11055:  	    unless (($version eq 'mostrecent') || 
                   11056: 		    ($version==&getversion($uri))) {
1.440     www      11057:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11058:  	    }
                   11059:  	}
                   11060:  	untie %bighash;
1.413     www      11061:     }
1.599     albertel 11062:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11063: }
                   11064: 
                   11065: sub deversion {
                   11066:     my $url=shift;
                   11067:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11068:     return $url;
1.210     www      11069: }
                   11070: 
1.31      www      11071: # ------------------------------------------------------ Return symb list entry
                   11072: 
                   11073: sub symbread {
1.249     www      11074:     my ($thisfn,$donotrecurse)=@_;
1.1265    raeburn  11075:     my $cache_str='request.symbread.cached.'.$thisfn;
                   11076:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      11077: # no filename provided? try from environment
1.1265    raeburn  11078:     unless ($thisfn) {
1.620     albertel 11079:         if ($env{'request.symb'}) {
                   11080: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 11081: 	}
1.620     albertel 11082: 	$thisfn=$env{'request.filename'};
1.44      www      11083:     }
1.569     albertel 11084:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11085: # is that filename actually a symb? Verify, clean, and return
                   11086:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11087: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11088: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11089: 	}
1.242     www      11090:     }
1.44      www      11091:     $thisfn=declutter($thisfn);
1.31      www      11092:     my %hash;
1.37      www      11093:     my %bighash;
                   11094:     my $syval='';
1.620     albertel 11095:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11096:         my $targetfn = $thisfn;
1.609     banghart 11097:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11098:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11099:         }
1.687     albertel 11100: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11101: 	    $targetfn=$1;
                   11102: 	}
1.620     albertel 11103:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11104:                       &GDBM_READER(),0640)) {
1.481     raeburn  11105: 	    $syval=$hash{$targetfn};
1.37      www      11106:             untie(%hash);
                   11107:         }
                   11108: # ---------------------------------------------------------- There was an entry
                   11109:         if ($syval) {
1.601     albertel 11110: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11111: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11112: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11113: 		    #return $env{$cache_str}='';
1.601     albertel 11114: 		#}    
                   11115: 		#$syval.=$1;
                   11116: 	    #}
1.37      www      11117:         } else {
                   11118: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11119:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11120:                             &GDBM_READER(),0640)) {
1.37      www      11121: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11122:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11123:               unless ($ids) { 
                   11124:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11125:               }
                   11126:               unless ($ids) {
                   11127: # alias?
                   11128: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11129:               }
1.37      www      11130:               if ($ids) {
                   11131: # ------------------------------------------------------------------- Has ID(s)
                   11132:                  my @possibilities=split(/\,/,$ids);
1.39      www      11133:                  if ($#possibilities==0) {
                   11134: # ----------------------------------------------- There is only one possibility
1.37      www      11135: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11136: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11137: 						    $resid,$thisfn);
1.249     www      11138:                  } elsif (!$donotrecurse) {
1.39      www      11139: # ------------------------------------------ There is more than one possibility
                   11140:                      my $realpossible=0;
1.800     albertel 11141:                      foreach my $id (@possibilities) {
                   11142: 			 my $file=$bighash{'src_'.$id};
1.39      www      11143:                          if (&allowed('bre',$file)) {
1.800     albertel 11144:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      11145:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11146: 				$realpossible++;
1.626     albertel 11147:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11148: 						    $resid,$thisfn);
1.39      www      11149:                             }
                   11150: 			 }
1.191     harris41 11151:                      }
1.39      www      11152: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11153:                  } else {
                   11154:                      $syval='';
1.37      www      11155:                  }
                   11156: 	      }
                   11157:               untie(%bighash)
1.481     raeburn  11158:            }
1.31      www      11159:         }
1.62      www      11160:         if ($syval) {
1.620     albertel 11161: 	    return $env{$cache_str}=$syval;
1.62      www      11162:         }
1.31      www      11163:     }
1.949     raeburn  11164:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11165:     return $env{$cache_str}='';
1.31      www      11166: }
                   11167: 
                   11168: # ---------------------------------------------------------- Return random seed
                   11169: 
1.32      www      11170: sub numval {
                   11171:     my $txt=shift;
                   11172:     $txt=~tr/A-J/0-9/;
                   11173:     $txt=~tr/a-j/0-9/;
                   11174:     $txt=~tr/K-T/0-9/;
                   11175:     $txt=~tr/k-t/0-9/;
                   11176:     $txt=~tr/U-Z/0-5/;
                   11177:     $txt=~tr/u-z/0-5/;
                   11178:     $txt=~s/\D//g;
1.564     albertel 11179:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11180:     return int($txt);
1.368     albertel 11181: }
                   11182: 
1.484     albertel 11183: sub numval2 {
                   11184:     my $txt=shift;
                   11185:     $txt=~tr/A-J/0-9/;
                   11186:     $txt=~tr/a-j/0-9/;
                   11187:     $txt=~tr/K-T/0-9/;
                   11188:     $txt=~tr/k-t/0-9/;
                   11189:     $txt=~tr/U-Z/0-5/;
                   11190:     $txt=~tr/u-z/0-5/;
                   11191:     $txt=~s/\D//g;
                   11192:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11193:     my $total;
                   11194:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11195:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11196:     return int($total);
                   11197: }
                   11198: 
1.575     albertel 11199: sub numval3 {
                   11200:     use integer;
                   11201:     my $txt=shift;
                   11202:     $txt=~tr/A-J/0-9/;
                   11203:     $txt=~tr/a-j/0-9/;
                   11204:     $txt=~tr/K-T/0-9/;
                   11205:     $txt=~tr/k-t/0-9/;
                   11206:     $txt=~tr/U-Z/0-5/;
                   11207:     $txt=~tr/u-z/0-5/;
                   11208:     $txt=~s/\D//g;
                   11209:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11210:     my $total;
                   11211:     foreach my $val (@txts) { $total+=$val; }
                   11212:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11213:     return $total;
                   11214: }
                   11215: 
1.675     albertel 11216: sub digest {
                   11217:     my ($data)=@_;
                   11218:     my $digest=&Digest::MD5::md5($data);
                   11219:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11220:     my ($e,$f);
                   11221:     {
                   11222:         use integer;
                   11223:         $e=($a+$b);
                   11224:         $f=($c+$d);
                   11225:         if ($_64bit) {
                   11226:             $e=(($e<<32)>>32);
                   11227:             $f=(($f<<32)>>32);
                   11228:         }
                   11229:     }
                   11230:     if (wantarray) {
                   11231: 	return ($e,$f);
                   11232:     } else {
                   11233: 	my $g;
                   11234: 	{
                   11235: 	    use integer;
                   11236: 	    $g=($e+$f);
                   11237: 	    if ($_64bit) {
                   11238: 		$g=(($g<<32)>>32);
                   11239: 	    }
                   11240: 	}
                   11241: 	return $g;
                   11242:     }
                   11243: }
                   11244: 
1.368     albertel 11245: sub latest_rnd_algorithm_id {
1.675     albertel 11246:     return '64bit5';
1.366     albertel 11247: }
1.32      www      11248: 
1.503     albertel 11249: sub get_rand_alg {
                   11250:     my ($courseid)=@_;
1.790     albertel 11251:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11252:     if ($courseid) {
1.620     albertel 11253: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11254:     }
                   11255:     return &latest_rnd_algorithm_id();
                   11256: }
                   11257: 
1.562     albertel 11258: sub validCODE {
                   11259:     my ($CODE)=@_;
                   11260:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11261:     return 0;
                   11262: }
                   11263: 
1.491     albertel 11264: sub getCODE {
1.620     albertel 11265:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11266:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11267: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11268: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11269: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11270:     }
                   11271:     return undef;
                   11272: }
1.1133    foxr     11273: #
                   11274: #  Determines the random seed for a specific context:
                   11275: #
                   11276: # parameters:
                   11277: #   symb      - in course context the symb for the seed.
                   11278: #   course_id - The course id of the form domain_coursenum.
                   11279: #   domain    - Domain for the user.
                   11280: #   course    - Course for the user.
                   11281: #   cenv      - environment of the course.
                   11282: #
                   11283: # NOTE:
                   11284: #   All parameters are picked out of the environment if missing
                   11285: #   or not defined.
                   11286: #   If a symb cannot be determined the current time is used instead.
                   11287: #
                   11288: #  For a given well defined symb, courside, domain, username,
                   11289: #  and course environment, the seed is reproducible.
                   11290: #
1.31      www      11291: sub rndseed {
1.1133    foxr     11292:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11293:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11294:     if (!defined($symb)) {
1.366     albertel 11295: 	unless ($symb=$wsymb) { return time; }
                   11296:     }
1.1146    foxr     11297:     if (!defined $courseid) { 
                   11298: 	$courseid=$wcourseid; 
                   11299:     }
                   11300:     if (!defined $domain) { $domain=$wdomain; }
                   11301:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11302: 
                   11303:     my $which;
                   11304:     if (defined($cenv->{'rndseed'})) {
                   11305: 	$which = $cenv->{'rndseed'};
                   11306:     } else {
                   11307: 	$which =&get_rand_alg($courseid);
                   11308:     }
1.491     albertel 11309:     if (defined(&getCODE())) {
1.1133    foxr     11310: 
1.675     albertel 11311: 	if ($which eq '64bit5') {
                   11312: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11313: 	} elsif ($which eq '64bit4') {
1.575     albertel 11314: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11315: 	} else {
                   11316: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11317: 	}
1.675     albertel 11318:     } elsif ($which eq '64bit5') {
                   11319: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11320:     } elsif ($which eq '64bit4') {
                   11321: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11322:     } elsif ($which eq '64bit3') {
                   11323: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11324:     } elsif ($which eq '64bit2') {
                   11325: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11326:     } elsif ($which eq '64bit') {
                   11327: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11328:     }
                   11329:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11330: }
                   11331: 
                   11332: sub rndseed_32bit {
                   11333:     my ($symb,$courseid,$domain,$username)=@_;
                   11334:     {
                   11335: 	use integer;
                   11336: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11337: 	my $symbseed=numval($symb) << 22;
                   11338: 	my $namechck=unpack("%32C*",$username) << 17;
                   11339: 	my $nameseed=numval($username) << 12;
                   11340: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11341: 	my $courseseed=unpack("%32C*",$courseid);
                   11342: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11343: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11344: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11345: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11346: 	return $num;
                   11347:     }
                   11348: }
                   11349: 
                   11350: sub rndseed_64bit {
                   11351:     my ($symb,$courseid,$domain,$username)=@_;
                   11352:     {
                   11353: 	use integer;
                   11354: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11355: 	my $symbseed=numval($symb) << 10;
                   11356: 	my $namechck=unpack("%32S*",$username);
                   11357: 	
                   11358: 	my $nameseed=numval($username) << 21;
                   11359: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11360: 	my $courseseed=unpack("%32S*",$courseid);
                   11361: 	
                   11362: 	my $num1=$symbchck+$symbseed+$namechck;
                   11363: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11364: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11365: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11366: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11367: 	return "$num1,$num2";
1.155     albertel 11368:     }
1.366     albertel 11369: }
                   11370: 
1.443     albertel 11371: sub rndseed_64bit2 {
                   11372:     my ($symb,$courseid,$domain,$username)=@_;
                   11373:     {
                   11374: 	use integer;
                   11375: 	# strings need to be an even # of cahracters long, it it is odd the
                   11376:         # last characters gets thrown away
                   11377: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11378: 	my $symbseed=numval($symb) << 10;
                   11379: 	my $namechck=unpack("%32S*",$username.' ');
                   11380: 	
                   11381: 	my $nameseed=numval($username) << 21;
1.501     albertel 11382: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11383: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11384: 	
                   11385: 	my $num1=$symbchck+$symbseed+$namechck;
                   11386: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11387: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11388: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11389: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11390: 	return "$num1,$num2";
                   11391:     }
                   11392: }
                   11393: 
                   11394: sub rndseed_64bit3 {
                   11395:     my ($symb,$courseid,$domain,$username)=@_;
                   11396:     {
                   11397: 	use integer;
                   11398: 	# strings need to be an even # of cahracters long, it it is odd the
                   11399:         # last characters gets thrown away
                   11400: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11401: 	my $symbseed=numval2($symb) << 10;
                   11402: 	my $namechck=unpack("%32S*",$username.' ');
                   11403: 	
                   11404: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11405: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11406: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11407: 	
                   11408: 	my $num1=$symbchck+$symbseed+$namechck;
                   11409: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11410: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11411: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11412: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11413: 	
1.503     albertel 11414: 	return "$num1:$num2";
1.443     albertel 11415:     }
                   11416: }
                   11417: 
1.575     albertel 11418: sub rndseed_64bit4 {
                   11419:     my ($symb,$courseid,$domain,$username)=@_;
                   11420:     {
                   11421: 	use integer;
                   11422: 	# strings need to be an even # of cahracters long, it it is odd the
                   11423:         # last characters gets thrown away
                   11424: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11425: 	my $symbseed=numval3($symb) << 10;
                   11426: 	my $namechck=unpack("%32S*",$username.' ');
                   11427: 	
                   11428: 	my $nameseed=numval3($username) << 21;
                   11429: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11430: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11431: 	
                   11432: 	my $num1=$symbchck+$symbseed+$namechck;
                   11433: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11434: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11435: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11436: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11437: 	
1.575     albertel 11438: 	return "$num1:$num2";
                   11439:     }
                   11440: }
                   11441: 
1.675     albertel 11442: sub rndseed_64bit5 {
                   11443:     my ($symb,$courseid,$domain,$username)=@_;
                   11444:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11445:     return "$num1:$num2";
                   11446: }
                   11447: 
1.366     albertel 11448: sub rndseed_CODE_64bit {
                   11449:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11450:     {
1.366     albertel 11451: 	use integer;
1.443     albertel 11452: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11453: 	my $symbseed=numval2($symb);
1.491     albertel 11454: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11455: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11456: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11457: 	my $num1=$symbseed+$CODEchck;
                   11458: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11459: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11460: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11461: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11462: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11463: 	return "$num1:$num2";
1.366     albertel 11464:     }
                   11465: }
                   11466: 
1.575     albertel 11467: sub rndseed_CODE_64bit4 {
                   11468:     my ($symb,$courseid,$domain,$username)=@_;
                   11469:     {
                   11470: 	use integer;
                   11471: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11472: 	my $symbseed=numval3($symb);
                   11473: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11474: 	my $CODEseed=numval3(&getCODE());
                   11475: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11476: 	my $num1=$symbseed+$CODEchck;
                   11477: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11478: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11479: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11480: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11481: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11482: 	return "$num1:$num2";
                   11483:     }
                   11484: }
                   11485: 
1.675     albertel 11486: sub rndseed_CODE_64bit5 {
                   11487:     my ($symb,$courseid,$domain,$username)=@_;
                   11488:     my $code = &getCODE();
                   11489:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11490:     return "$num1:$num2";
                   11491: }
                   11492: 
1.366     albertel 11493: sub setup_random_from_rndseed {
                   11494:     my ($rndseed)=@_;
1.503     albertel 11495:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  11496:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   11497:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   11498:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   11499:         } else {
                   11500:             &Math::Random::random_set_seed($num1,$num2);
                   11501:         }
1.366     albertel 11502:     } else {
                   11503: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11504:     }
1.36      albertel 11505: }
                   11506: 
1.474     albertel 11507: sub latest_receipt_algorithm_id {
1.835     albertel 11508:     return 'receipt3';
1.474     albertel 11509: }
                   11510: 
1.480     www      11511: sub recunique {
                   11512:     my $fucourseid=shift;
                   11513:     my $unique;
1.835     albertel 11514:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11515: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11516: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11517:     } else {
                   11518: 	$unique=$perlvar{'lonReceipt'};
                   11519:     }
                   11520:     return unpack("%32C*",$unique);
                   11521: }
                   11522: 
                   11523: sub recprefix {
                   11524:     my $fucourseid=shift;
                   11525:     my $prefix;
1.835     albertel 11526:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11527: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11528: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11529:     } else {
                   11530: 	$prefix=$perlvar{'lonHostID'};
                   11531:     }
                   11532:     return unpack("%32C*",$prefix);
                   11533: }
                   11534: 
1.76      www      11535: sub ireceipt {
1.474     albertel 11536:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11537: 
                   11538:     my $return =&recprefix($fucourseid).'-';
                   11539: 
                   11540:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11541: 	$env{'request.state'} eq 'construct') {
                   11542: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11543: 	return $return;
                   11544:     }
                   11545: 
1.76      www      11546:     my $cuname=unpack("%32C*",$funame);
                   11547:     my $cudom=unpack("%32C*",$fudom);
                   11548:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11549:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11550:     my $cunique=&recunique($fucourseid);
1.474     albertel 11551:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11552:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11553: 
1.790     albertel 11554: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11555: 			       
                   11556: 	$return.= ($cunique%$cuname+
                   11557: 		   $cunique%$cudom+
                   11558: 		   $cusymb%$cuname+
                   11559: 		   $cusymb%$cudom+
                   11560: 		   $cucourseid%$cuname+
                   11561: 		   $cucourseid%$cudom+
                   11562: 		   $cpart%$cuname+
                   11563: 		   $cpart%$cudom);
                   11564:     } else {
                   11565: 	$return.= ($cunique%$cuname+
                   11566: 		   $cunique%$cudom+
                   11567: 		   $cusymb%$cuname+
                   11568: 		   $cusymb%$cudom+
                   11569: 		   $cucourseid%$cuname+
                   11570: 		   $cucourseid%$cudom);
                   11571:     }
                   11572:     return $return;
1.76      www      11573: }
                   11574: 
                   11575: sub receipt {
1.474     albertel 11576:     my ($part)=@_;
1.790     albertel 11577:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11578:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11579: }
1.260     ng       11580: 
1.790     albertel 11581: sub whichuser {
                   11582:     my ($passedsymb)=@_;
                   11583:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11584:     if (defined($env{'form.grade_symb'})) {
                   11585: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11586: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11587: 	if (!$allowed &&
                   11588: 	    exists($env{'request.course.sec'}) &&
                   11589: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11590: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11591: 			      '/'.$env{'request.course.sec'});
                   11592: 	}
                   11593: 	if ($allowed) {
                   11594: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11595: 	    $courseid=$tmp_courseid;
                   11596: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11597: 	    ($name)=&get_env_multiple('form.grade_username');
                   11598: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11599: 	}
                   11600:     }
                   11601:     if (!$passedsymb) {
                   11602: 	$symb=&symbread();
                   11603:     } else {
                   11604: 	$symb=$passedsymb;
                   11605:     }
                   11606:     $courseid=$env{'request.course.id'};
                   11607:     $domain=$env{'user.domain'};
                   11608:     $name=$env{'user.name'};
                   11609:     if ($name eq 'public' && $domain eq 'public') {
                   11610: 	if (!defined($env{'form.username'})) {
                   11611: 	    $env{'form.username'}.=time.rand(10000000);
                   11612: 	}
                   11613: 	$name.=$env{'form.username'};
                   11614:     }
                   11615:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11616: 
                   11617: }
                   11618: 
1.36      albertel 11619: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11620: # returns either the contents of the file or 
                   11621: # -1 if the file doesn't exist
1.481     raeburn  11622: #
                   11623: # if the target is a file that was uploaded via DOCS, 
                   11624: # a check will be made to see if a current copy exists on the local server,
                   11625: # if it does this will be served, otherwise a copy will be retrieved from
                   11626: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11627: # the local server.   
1.472     albertel 11628: 
1.36      albertel 11629: sub getfile {
1.538     albertel 11630:     my ($file) = @_;
1.609     banghart 11631:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11632:     &repcopy($file);
                   11633:     return &readfile($file);
                   11634: }
                   11635: 
                   11636: sub repcopy_userfile {
                   11637:     my ($file)=@_;
1.1142    raeburn  11638:     my $londocroot = $perlvar{'lonDocRoot'};
                   11639:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11640:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11641:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11642: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11643:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11644:     if (-e "$file") {
1.828     www      11645: # we already have a local copy, check it out
1.538     albertel 11646: 	my @fileinfo = stat($file);
1.828     www      11647: 	my $rtncode;
                   11648: 	my $info;
1.538     albertel 11649: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11650: 	if ($lwpresp ne 'ok') {
1.828     www      11651: # there is no such file anymore, even though we had a local copy
1.482     albertel 11652: 	    if ($rtncode eq '404') {
1.538     albertel 11653: 		unlink($file);
1.482     albertel 11654: 	    }
                   11655: 	    return -1;
                   11656: 	}
                   11657: 	if ($info < $fileinfo[9]) {
1.828     www      11658: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11659: 	    return 'ok';
1.828     www      11660: 	} else {
                   11661: # the file is outdated, get rid of it
                   11662: 	    unlink($file);
1.482     albertel 11663: 	}
1.828     www      11664:     }
                   11665: # one way or the other, at this point, we don't have the file
                   11666: # construct the correct path for the file
                   11667:     my @parts = ($cdom,$cnum); 
                   11668:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11669: 	push @parts, split(/\//,$1);
                   11670:     }
                   11671:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11672:     foreach my $part (@parts) {
                   11673: 	$path .= '/'.$part;
                   11674: 	if (!-e $path) {
                   11675: 	    mkdir($path,0770);
1.482     albertel 11676: 	}
                   11677:     }
1.828     www      11678: # now the path exists for sure
                   11679: # get a user agent
                   11680:     my $ua=new LWP::UserAgent;
                   11681:     my $transferfile=$file.'.in.transfer';
                   11682: # FIXME: this should flock
                   11683:     if (-e $transferfile) { return 'ok'; }
                   11684:     my $request;
                   11685:     $uri=~s/^\///;
1.980     raeburn  11686:     my $homeserver = &homeserver($cnum,$cdom);
                   11687:     my $protocol = $protocol{$homeserver};
                   11688:     $protocol = 'http' if ($protocol ne 'https');
                   11689:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11690:     my $response=$ua->request($request,$transferfile);
                   11691: # did it work?
                   11692:     if ($response->is_error()) {
                   11693: 	unlink($transferfile);
                   11694: 	&logthis("Userfile repcopy failed for $uri");
                   11695: 	return -1;
                   11696:     }
                   11697: # worked, rename the transfer file
                   11698:     rename($transferfile,$file);
1.607     raeburn  11699:     return 'ok';
1.481     raeburn  11700: }
                   11701: 
1.517     albertel 11702: sub tokenwrapper {
                   11703:     my $uri=shift;
1.980     raeburn  11704:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11705:     $uri=~s|^/||;
1.620     albertel 11706:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11707:     my $token=$1;
1.552     albertel 11708:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11709:     if ($udom && $uname && $file) {
                   11710: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11711:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11712:         my $homeserver = &homeserver($uname,$udom);
                   11713:         my $protocol = $protocol{$homeserver};
                   11714:         $protocol = 'http' if ($protocol ne 'https');
                   11715:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11716:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11717:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11718:     } else {
                   11719:         return '/adm/notfound.html';
                   11720:     }
                   11721: }
                   11722: 
1.828     www      11723: # call with reqtype HEAD: get last modification time
                   11724: # call with reqtype GET: get the file contents
                   11725: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11726: #
1.481     raeburn  11727: sub getuploaded {
                   11728:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11729:     $uri=~s/^\///;
1.980     raeburn  11730:     my $homeserver = &homeserver($cnum,$cdom);
                   11731:     my $protocol = $protocol{$homeserver};
                   11732:     $protocol = 'http' if ($protocol ne 'https');
                   11733:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11734:     my $ua=new LWP::UserAgent;
                   11735:     my $request=new HTTP::Request($reqtype,$uri);
                   11736:     my $response=$ua->request($request);
                   11737:     $$rtncode = $response->code;
1.482     albertel 11738:     if (! $response->is_success()) {
                   11739: 	return 'failed';
                   11740:     }      
                   11741:     if ($reqtype eq 'HEAD') {
1.486     www      11742: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11743:     } elsif ($reqtype eq 'GET') {
                   11744: 	$$info = $response->content;
1.472     albertel 11745:     }
1.482     albertel 11746:     return 'ok';
1.36      albertel 11747: }
                   11748: 
1.481     raeburn  11749: sub readfile {
                   11750:     my $file = shift;
                   11751:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11752:     my $fh;
                   11753:     open($fh,"<$file");
                   11754:     my $a='';
1.800     albertel 11755:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11756:     return $a;
                   11757: }
                   11758: 
1.36      albertel 11759: sub filelocation {
1.590     banghart 11760:     my ($dir,$file) = @_;
                   11761:     my $location;
                   11762:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11763: 
                   11764:     if ($file =~ m-^/adm/-) {
                   11765: 	$file=~s-^/adm/wrapper/-/-;
                   11766: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11767:     }
1.882     albertel 11768: 
1.1139    www      11769:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11770:         $location = $file;
1.609     banghart 11771:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11772:         my ($udom,$uname,$filename)=
1.811     albertel 11773:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11774:         my $home=&homeserver($uname,$udom);
                   11775:         my $is_me=0;
                   11776:         my @ids=&current_machine_ids();
                   11777:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11778:         if ($is_me) {
1.1117    foxr     11779:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11780:         } else {
                   11781:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11782:   	      $udom.'/'.$uname.'/'.$filename;
                   11783:         }
1.882     albertel 11784:     } elsif ($file =~ m-^/adm/-) {
                   11785: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11786:     } else {
                   11787:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11788:         $file=~s:^/(res|priv)/:/:;
                   11789:         my $space=$1;
1.590     banghart 11790:         if ( !( $file =~ m:^/:) ) {
                   11791:             $location = $dir. '/'.$file;
                   11792:         } else {
1.1142    raeburn  11793:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11794:         }
1.59      albertel 11795:     }
1.590     banghart 11796:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11797:     while ($location=~m{/\.\./}) {
                   11798: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11799: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11800: 	} else {
                   11801: 	    $location=~ s{/\.\./}{/}g;
                   11802: 	}
                   11803:     } #remove dir/..
1.590     banghart 11804:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11805:     return $location;
1.46      www      11806: }
1.36      albertel 11807: 
1.46      www      11808: sub hreflocation {
                   11809:     my ($dir,$file)=@_;
1.980     raeburn  11810:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11811: 	$file=filelocation($dir,$file);
1.700     albertel 11812:     } elsif ($file=~m-^/adm/-) {
                   11813: 	$file=~s-^/adm/wrapper/-/-;
                   11814: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11815:     }
                   11816:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11817: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11818:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11819: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11820: 	        {/uploaded/$1/$2/}x;
1.46      www      11821:     }
1.913     albertel 11822:     if ($file=~ m{^/userfiles/}) {
                   11823: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11824:     }
1.462     albertel 11825:     return $file;
1.465     albertel 11826: }
                   11827: 
1.1139    www      11828: 
                   11829: 
                   11830: 
                   11831: 
1.465     albertel 11832: sub current_machine_domains {
1.853     albertel 11833:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11834: }
                   11835: 
                   11836: sub machine_domains {
                   11837:     my ($hostname) = @_;
1.465     albertel 11838:     my @domains;
1.838     albertel 11839:     my %hostname = &all_hostnames();
1.465     albertel 11840:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11841: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11842: 	if ($hostname eq $name) {
1.844     albertel 11843: 	    push(@domains,&host_domain($id));
1.465     albertel 11844: 	}
                   11845:     }
                   11846:     return @domains;
                   11847: }
                   11848: 
                   11849: sub current_machine_ids {
1.853     albertel 11850:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11851: }
                   11852: 
                   11853: sub machine_ids {
                   11854:     my ($hostname) = @_;
                   11855:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11856:     my @ids;
1.888     albertel 11857:     my %name_to_host = &all_names();
1.889     albertel 11858:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11859: 	return @{ $name_to_host{$hostname} };
                   11860:     }
                   11861:     return;
1.31      www      11862: }
                   11863: 
1.824     raeburn  11864: sub additional_machine_domains {
                   11865:     my @domains;
                   11866:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11867:     while( my $line = <$fh>) {
                   11868:         $line =~ s/\s//g;
                   11869:         push(@domains,$line);
                   11870:     }
                   11871:     return @domains;
                   11872: }
                   11873: 
                   11874: sub default_login_domain {
                   11875:     my $domain = $perlvar{'lonDefDomain'};
                   11876:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11877:     foreach my $posdom (&current_machine_domains(),
                   11878:                         &additional_machine_domains()) {
                   11879:         if (lc($posdom) eq lc($testdomain)) {
                   11880:             $domain=$posdom;
                   11881:             last;
                   11882:         }
                   11883:     }
                   11884:     return $domain;
                   11885: }
                   11886: 
1.31      www      11887: # ------------------------------------------------------------- Declutters URLs
                   11888: 
                   11889: sub declutter {
                   11890:     my $thisfn=shift;
1.569     albertel 11891:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  11892:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   11893:         $thisfn=~s{^/home/httpd/html}{};
                   11894:     }
1.31      www      11895:     $thisfn=~s/^\///;
1.697     albertel 11896:     $thisfn=~s|^adm/wrapper/||;
                   11897:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11898:     $thisfn=~s/^res\///;
1.1172    bisitz   11899:     $thisfn=~s/^priv\///;
1.1032    raeburn  11900:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11901:         $thisfn=~s/\?.+$//;
                   11902:     }
1.268     www      11903:     return $thisfn;
                   11904: }
                   11905: 
                   11906: # ------------------------------------------------------------- Clutter up URLs
                   11907: 
                   11908: sub clutter {
                   11909:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11910:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11911: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11912:        $thisfn='/res'.$thisfn; 
                   11913:     }
1.1031    raeburn  11914:     if ($thisfn !~m|^/adm|) {
                   11915: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11916: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11917: 	} else {
                   11918: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11919: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11920: 	    if ($embstyle eq 'ssi'
                   11921: 		|| ($embstyle eq 'hdn')
                   11922: 		|| ($embstyle eq 'rat')
                   11923: 		|| ($embstyle eq 'prv')
                   11924: 		|| ($embstyle eq 'ign')) {
                   11925: 		#do nothing with these
                   11926: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11927: 		|| ($embstyle eq 'emb')
                   11928: 		|| ($embstyle eq 'wrp')) {
                   11929: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11930: 	    } elsif ($embstyle eq 'unk'
                   11931: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11932: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11933: 	    } else {
1.718     www      11934: #		&logthis("Got a blank emb style");
1.695     albertel 11935: 	    }
1.694     albertel 11936: 	}
                   11937:     }
1.31      www      11938:     return $thisfn;
1.12      www      11939: }
                   11940: 
1.787     albertel 11941: sub clutter_with_no_wrapper {
                   11942:     my $uri = &clutter(shift);
                   11943:     if ($uri =~ m-^/adm/-) {
                   11944: 	$uri =~ s-^/adm/wrapper/-/-;
                   11945: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11946:     }
                   11947:     return $uri;
                   11948: }
                   11949: 
1.557     albertel 11950: sub freeze_escape {
                   11951:     my ($value)=@_;
                   11952:     if (ref($value)) {
                   11953: 	$value=&nfreeze($value);
                   11954: 	return '__FROZEN__'.&escape($value);
                   11955:     }
                   11956:     return &escape($value);
                   11957: }
                   11958: 
1.11      www      11959: 
1.557     albertel 11960: sub thaw_unescape {
                   11961:     my ($value)=@_;
                   11962:     if ($value =~ /^__FROZEN__/) {
                   11963: 	substr($value,0,10,undef);
                   11964: 	$value=&unescape($value);
                   11965: 	return &thaw($value);
                   11966:     }
                   11967:     return &unescape($value);
                   11968: }
                   11969: 
1.436     albertel 11970: sub correct_line_ends {
                   11971:     my ($result)=@_;
                   11972:     $$result =~s/\r\n/\n/mg;
                   11973:     $$result =~s/\r/\n/mg;
1.415     albertel 11974: }
1.1       albertel 11975: # ================================================================ Main Program
                   11976: 
1.184     www      11977: sub goodbye {
1.204     albertel 11978:    &logthis("Starting Shut down");
1.443     albertel 11979: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11980:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11981: #converted
1.599     albertel 11982: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11983:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11984: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11985: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11986: #1.1 only
1.870     albertel 11987: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11988: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11989: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11990: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11991:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11992:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11993:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11994:    &flushcourselogs();
                   11995:    &logthis("Shutting down");
                   11996: }
                   11997: 
1.852     albertel 11998: sub get_dns {
1.1210    raeburn  11999:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12000:     if (!$ignore_cache) {
                   12001: 	my ($content,$cached)=
                   12002: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12003: 	if ($cached) {
1.1210    raeburn  12004: 	    &$func($content,$hashref);
1.869     albertel 12005: 	    return;
                   12006: 	}
                   12007:     }
                   12008: 
                   12009:     my %alldns;
1.852     albertel 12010:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12011:     foreach my $dns (<$config>) {
                   12012: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12013:         my $line = $1;
                   12014:         my ($host,$protocol) = split(/:/,$line);
                   12015:         if ($protocol ne 'https') {
                   12016:             $protocol = 'http';
                   12017:         }
                   12018: 	$alldns{$host} = $protocol;
1.869     albertel 12019:     }
                   12020:     while (%alldns) {
1.1263    raeburn  12021: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12022: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12023:         $ua->timeout(30);
1.979     raeburn  12024: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12025: 	my $response=$ua->request($request);
1.979     raeburn  12026:         delete($alldns{$dns});
1.852     albertel 12027: 	next if ($response->is_error());
                   12028: 	my @content = split("\n",$response->content);
1.1210    raeburn  12029: 	unless ($nocache) {
1.1219    raeburn  12030: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  12031: 	}
                   12032: 	&$func(\@content,$hashref);
1.869     albertel 12033: 	return;
1.852     albertel 12034:     }
                   12035:     close($config);
1.871     albertel 12036:     my $which = (split('/',$url))[3];
                   12037:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12038:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12039:     my @content = <$config>;
1.1210    raeburn  12040:     &$func(\@content,$hashref);
                   12041:     return;
                   12042: }
                   12043: 
                   12044: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  12045: sub parse_dns_checksums_tab {
1.1210    raeburn  12046:     my ($lines,$hashref) = @_;
1.1264    raeburn  12047:     my $lonhost = $perlvar{'lonHostID'};
                   12048:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  12049:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  12050:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12051:     my $webconfdir = '/etc/httpd/conf';
                   12052:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12053:         $webconfdir = '/etc/apache2';
                   12054:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12055:         if ($1 >= 10) {
                   12056:             $webconfdir = '/etc/apache2';
                   12057:         }
                   12058:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12059:         if ($1 >= 10.0) {
                   12060:             $webconfdir = '/etc/apache2';
                   12061:         }
                   12062:     }
1.1210    raeburn  12063:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12064:     my (%chksum,%revnum);
                   12065:     if (ref($lines) eq 'ARRAY') {
                   12066:         chomp(@{$lines});
1.1238    raeburn  12067:         my $version = shift(@{$lines});
                   12068:         if ($version eq $release) {  
1.1210    raeburn  12069:             foreach my $line (@{$lines}) {
1.1238    raeburn  12070:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  12071:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12072:                     if ($webconfdir eq '/etc/apache2') {
                   12073:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12074:                     }
                   12075:                 }
1.1238    raeburn  12076:                 $chksum{$file} = $shasum;
                   12077:                 $revnum{$file} = $version;
1.1210    raeburn  12078:             }
                   12079:             if (ref($hashref) eq 'HASH') {
                   12080:                 %{$hashref} = (
                   12081:                                 sums     => \%chksum,
                   12082:                                 versions => \%revnum,
                   12083:                               );
                   12084:             }
                   12085:         }
                   12086:     }
1.869     albertel 12087:     return;
1.852     albertel 12088: }
1.1210    raeburn  12089: 
                   12090: sub fetch_dns_checksums {
1.1238    raeburn  12091:     my %checksums;
                   12092:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  12093:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  12094:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12095:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  12096:              \%checksums);
1.1210    raeburn  12097:     return \%checksums;
                   12098: }
                   12099: 
1.327     albertel 12100: # ------------------------------------------------------------ Read domain file
                   12101: {
1.852     albertel 12102:     my $loaded;
1.846     albertel 12103:     my %domain;
                   12104: 
1.852     albertel 12105:     sub parse_domain_tab {
                   12106: 	my ($lines) = @_;
                   12107: 	foreach my $line (@$lines) {
                   12108: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12109: 
1.846     albertel 12110: 	    chomp($line);
1.852     albertel 12111: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12112: 	    my %this_domain;
                   12113: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12114: 			       'lang_def', 'city', 'longi', 'lati',
                   12115: 			       'primary') {
                   12116: 		$this_domain{$field} = shift(@elements);
                   12117: 	    }
                   12118: 	    $domain{$name} = \%this_domain;
1.852     albertel 12119: 	}
                   12120:     }
1.864     albertel 12121: 
                   12122:     sub reset_domain_info {
                   12123: 	undef($loaded);
                   12124: 	undef(%domain);
                   12125:     }
                   12126: 
1.852     albertel 12127:     sub load_domain_tab {
1.869     albertel 12128: 	my ($ignore_cache) = @_;
                   12129: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 12130: 	my $fh;
                   12131: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12132: 	    my @lines = <$fh>;
                   12133: 	    &parse_domain_tab(\@lines);
1.448     albertel 12134: 	}
1.852     albertel 12135: 	close($fh);
                   12136: 	$loaded = 1;
1.327     albertel 12137:     }
1.846     albertel 12138: 
                   12139:     sub domain {
1.852     albertel 12140: 	&load_domain_tab() if (!$loaded);
                   12141: 
1.846     albertel 12142: 	my ($name,$what) = @_;
                   12143: 	return if ( !exists($domain{$name}) );
                   12144: 
                   12145: 	if (!$what) {
                   12146: 	    return $domain{$name}{'description'};
                   12147: 	}
                   12148: 	return $domain{$name}{$what};
                   12149:     }
1.974     raeburn  12150: 
                   12151:     sub domain_info {
                   12152:         &load_domain_tab() if (!$loaded);
                   12153:         return %domain;
                   12154:     }
                   12155: 
1.327     albertel 12156: }
                   12157: 
                   12158: 
1.1       albertel 12159: # ------------------------------------------------------------- Read hosts file
                   12160: {
1.838     albertel 12161:     my %hostname;
1.844     albertel 12162:     my %hostdom;
1.845     albertel 12163:     my %libserv;
1.852     albertel 12164:     my $loaded;
1.888     albertel 12165:     my %name_to_host;
1.1074    raeburn  12166:     my %internetdom;
1.1107    raeburn  12167:     my %LC_dns_serv;
1.852     albertel 12168: 
                   12169:     sub parse_hosts_tab {
                   12170: 	my ($file) = @_;
                   12171: 	foreach my $configline (@$file) {
                   12172: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12173:             chomp($configline);
                   12174: 	    if ($configline =~ /^\^/) {
                   12175:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12176:                     $LC_dns_serv{$1} = 1;
                   12177:                 }
                   12178:                 next;
                   12179:             }
1.1074    raeburn  12180: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12181: 	    $name=~s/\s//g;
                   12182: 	    if ($id && $domain && $role && $name) {
                   12183: 		$hostname{$id}=$name;
1.888     albertel 12184: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12185: 		$hostdom{$id}=$domain;
                   12186: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12187:                 if (defined($protocol)) {
                   12188:                     if ($protocol eq 'https') {
                   12189:                         $protocol{$id} = $protocol;
                   12190:                     } else {
                   12191:                         $protocol{$id} = 'http'; 
                   12192:                     }
1.968     raeburn  12193:                 } else {
1.969     raeburn  12194:                     $protocol{$id} = 'http';
1.968     raeburn  12195:                 }
1.1074    raeburn  12196:                 if (defined($intdom)) {
                   12197:                     $internetdom{$id} = $intdom;
                   12198:                 }
1.852     albertel 12199: 	    }
                   12200: 	}
                   12201:     }
1.864     albertel 12202:     
                   12203:     sub reset_hosts_info {
1.897     albertel 12204: 	&purge_remembered();
1.864     albertel 12205: 	&reset_domain_info();
                   12206: 	&reset_hosts_ip_info();
1.892     albertel 12207: 	undef(%name_to_host);
1.864     albertel 12208: 	undef(%hostname);
                   12209: 	undef(%hostdom);
                   12210: 	undef(%libserv);
                   12211: 	undef($loaded);
                   12212:     }
1.1       albertel 12213: 
1.852     albertel 12214:     sub load_hosts_tab {
1.869     albertel 12215: 	my ($ignore_cache) = @_;
                   12216: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 12217: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12218: 	my @config = <$config>;
                   12219: 	&parse_hosts_tab(\@config);
                   12220: 	close($config);
                   12221: 	$loaded=1;
1.1       albertel 12222:     }
1.852     albertel 12223: 
1.838     albertel 12224:     sub hostname {
1.852     albertel 12225: 	&load_hosts_tab() if (!$loaded);
                   12226: 
1.838     albertel 12227: 	my ($lonid) = @_;
                   12228: 	return $hostname{$lonid};
                   12229:     }
1.845     albertel 12230: 
1.838     albertel 12231:     sub all_hostnames {
1.852     albertel 12232: 	&load_hosts_tab() if (!$loaded);
                   12233: 
1.838     albertel 12234: 	return %hostname;
                   12235:     }
1.845     albertel 12236: 
1.888     albertel 12237:     sub all_names {
                   12238: 	&load_hosts_tab() if (!$loaded);
                   12239: 
                   12240: 	return %name_to_host;
                   12241:     }
                   12242: 
1.974     raeburn  12243:     sub all_host_domain {
                   12244:         &load_hosts_tab() if (!$loaded);
                   12245:         return %hostdom;
                   12246:     }
                   12247: 
1.845     albertel 12248:     sub is_library {
1.852     albertel 12249: 	&load_hosts_tab() if (!$loaded);
                   12250: 
1.845     albertel 12251: 	return exists($libserv{$_[0]});
                   12252:     }
                   12253: 
                   12254:     sub all_library {
1.852     albertel 12255: 	&load_hosts_tab() if (!$loaded);
                   12256: 
1.845     albertel 12257: 	return %libserv;
                   12258:     }
                   12259: 
1.1062    droeschl 12260:     sub unique_library {
                   12261: 	#2x reverse removes all hostnames that appear more than once
                   12262:         my %unique = reverse &all_library();
                   12263:         return reverse %unique;
                   12264:     }
                   12265: 
1.841     albertel 12266:     sub get_servers {
1.852     albertel 12267: 	&load_hosts_tab() if (!$loaded);
                   12268: 
1.841     albertel 12269: 	my ($domain,$type) = @_;
                   12270: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12271: 	                                          : %hostname;
                   12272: 	my %result;
1.842     albertel 12273: 	if (ref($domain) eq 'ARRAY') {
                   12274: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12275: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12276: 		    $result{$host} = $hostname;
                   12277: 		}
                   12278: 	    }
                   12279: 	} else {
                   12280: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12281: 		if ($hostdom{$host} eq $domain) {
                   12282: 		    $result{$host} = $hostname;
                   12283: 		}
1.841     albertel 12284: 	    }
                   12285: 	}
                   12286: 	return %result;
                   12287:     }
1.845     albertel 12288: 
1.1062    droeschl 12289:     sub get_unique_servers {
                   12290:         my %unique = reverse &get_servers(@_);
                   12291: 	return reverse %unique;
                   12292:     }
                   12293: 
1.844     albertel 12294:     sub host_domain {
1.852     albertel 12295: 	&load_hosts_tab() if (!$loaded);
                   12296: 
1.844     albertel 12297: 	my ($lonid) = @_;
                   12298: 	return $hostdom{$lonid};
                   12299:     }
                   12300: 
1.841     albertel 12301:     sub all_domains {
1.852     albertel 12302: 	&load_hosts_tab() if (!$loaded);
                   12303: 
1.841     albertel 12304: 	my %seen;
                   12305: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12306: 	return @uniq;
                   12307:     }
1.1074    raeburn  12308: 
                   12309:     sub internet_dom {
                   12310:         &load_hosts_tab() if (!$loaded);
                   12311: 
                   12312:         my ($lonid) = @_;
                   12313:         return $internetdom{$lonid};
                   12314:     }
1.1107    raeburn  12315: 
                   12316:     sub is_LC_dns {
                   12317:         &load_hosts_tab() if (!$loaded);
                   12318: 
                   12319:         my ($hostname) = @_;
                   12320:         return exists($LC_dns_serv{$hostname});
                   12321:     }
                   12322: 
1.1       albertel 12323: }
                   12324: 
1.847     albertel 12325: { 
                   12326:     my %iphost;
1.856     albertel 12327:     my %name_to_ip;
                   12328:     my %lonid_to_ip;
1.869     albertel 12329: 
1.847     albertel 12330:     sub get_hosts_from_ip {
                   12331: 	my ($ip) = @_;
                   12332: 	my %iphosts = &get_iphost();
                   12333: 	if (ref($iphosts{$ip})) {
                   12334: 	    return @{$iphosts{$ip}};
                   12335: 	}
                   12336: 	return;
1.839     albertel 12337:     }
1.864     albertel 12338:     
                   12339:     sub reset_hosts_ip_info {
                   12340: 	undef(%iphost);
                   12341: 	undef(%name_to_ip);
                   12342: 	undef(%lonid_to_ip);
                   12343:     }
1.856     albertel 12344: 
                   12345:     sub get_host_ip {
                   12346: 	my ($lonid) = @_;
                   12347: 	if (exists($lonid_to_ip{$lonid})) {
                   12348: 	    return $lonid_to_ip{$lonid};
                   12349: 	}
                   12350: 	my $name=&hostname($lonid);
                   12351:    	my $ip = gethostbyname($name);
                   12352: 	return if (!$ip || length($ip) ne 4);
                   12353: 	$ip=inet_ntoa($ip);
                   12354: 	$name_to_ip{$name}   = $ip;
                   12355: 	$lonid_to_ip{$lonid} = $ip;
                   12356: 	return $ip;
                   12357:     }
1.847     albertel 12358:     
                   12359:     sub get_iphost {
1.869     albertel 12360: 	my ($ignore_cache) = @_;
1.894     albertel 12361: 
1.869     albertel 12362: 	if (!$ignore_cache) {
                   12363: 	    if (%iphost) {
                   12364: 		return %iphost;
                   12365: 	    }
                   12366: 	    my ($ip_info,$cached)=
                   12367: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12368: 	    if ($cached) {
                   12369: 		%iphost      = %{$ip_info->[0]};
                   12370: 		%name_to_ip  = %{$ip_info->[1]};
                   12371: 		%lonid_to_ip = %{$ip_info->[2]};
                   12372: 		return %iphost;
                   12373: 	    }
                   12374: 	}
1.894     albertel 12375: 
                   12376: 	# get yesterday's info for fallback
                   12377: 	my %old_name_to_ip;
                   12378: 	my ($ip_info,$cached)=
                   12379: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12380: 	if ($cached) {
                   12381: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12382: 	}
                   12383: 
1.888     albertel 12384: 	my %name_to_host = &all_names();
                   12385: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12386: 	    my $ip;
                   12387: 	    if (!exists($name_to_ip{$name})) {
                   12388: 		$ip = gethostbyname($name);
                   12389: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12390: 		    if (defined($old_name_to_ip{$name})) {
                   12391: 			$ip = $old_name_to_ip{$name};
                   12392: 			&logthis("Can't find $name defaulting to old $ip");
                   12393: 		    } else {
                   12394: 			&logthis("Name $name no IP found");
                   12395: 			next;
                   12396: 		    }
                   12397: 		} else {
                   12398: 		    $ip=inet_ntoa($ip);
1.847     albertel 12399: 		}
                   12400: 		$name_to_ip{$name} = $ip;
                   12401: 	    } else {
                   12402: 		$ip = $name_to_ip{$name};
1.653     albertel 12403: 	    }
1.888     albertel 12404: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12405: 		$lonid_to_ip{$id} = $ip;
                   12406: 	    }
                   12407: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12408: 	}
1.1219    raeburn  12409: 	&do_cache_new('iphost','iphost',
                   12410: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12411: 		      48*60*60);
1.869     albertel 12412: 
1.847     albertel 12413: 	return %iphost;
1.598     albertel 12414:     }
                   12415: 
1.992     raeburn  12416:     #
                   12417:     #  Given a DNS returns the loncapa host name for that DNS 
                   12418:     # 
                   12419:     sub host_from_dns {
                   12420:         my ($dns) = @_;
                   12421:         my @hosts;
                   12422:         my $ip;
                   12423: 
1.993     raeburn  12424:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12425:             $ip = $name_to_ip{$dns};
                   12426:         }
                   12427:         if (!$ip) {
                   12428:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12429:             if (length($ip) == 4) { 
                   12430: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12431:             }
                   12432:         }
                   12433:         if ($ip) {
                   12434: 	    @hosts = get_hosts_from_ip($ip);
                   12435: 	    return $hosts[0];
                   12436:         }
                   12437:         return undef;
1.986     foxr     12438:     }
1.992     raeburn  12439: 
1.1074    raeburn  12440:     sub get_internet_names {
                   12441:         my ($lonid) = @_;
                   12442:         return if ($lonid eq '');
                   12443:         my ($idnref,$cached)=
                   12444:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12445:         if ($cached) {
                   12446:             return $idnref;
                   12447:         }
                   12448:         my $ip = &get_host_ip($lonid);
                   12449:         my @hosts = &get_hosts_from_ip($ip);
                   12450:         my %iphost = &get_iphost();
                   12451:         my (@idns,%seen);
                   12452:         foreach my $id (@hosts) {
                   12453:             my $dom = &host_domain($id);
                   12454:             my $prim_id = &domain($dom,'primary');
                   12455:             my $prim_ip = &get_host_ip($prim_id);
                   12456:             next if ($seen{$prim_ip});
                   12457:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12458:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12459:                     my $intdom = &internet_dom($id);
                   12460:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12461:                         push(@idns,$intdom);
                   12462:                     }
                   12463:                 }
                   12464:             }
                   12465:             $seen{$prim_ip} = 1;
                   12466:         }
1.1219    raeburn  12467:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12468:     }
                   12469: 
1.986     foxr     12470: }
                   12471: 
1.1079    raeburn  12472: sub all_loncaparevs {
1.1249    raeburn  12473:     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  12474: }
                   12475: 
1.1227    raeburn  12476: # ---------------------------------------------------------- Read loncaparev table
                   12477: {
                   12478:     sub load_loncaparevs { 
                   12479:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12480:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12481:                 while (my $configline=<$config>) {
                   12482:                     chomp($configline);
                   12483:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12484:                     $loncaparevs{$hostid}=$loncaparev;
                   12485:                 }
                   12486:                 close($config);
                   12487:             }
                   12488:         }
                   12489:     }
                   12490: }
                   12491: 
                   12492: # ---------------------------------------------------------- Read serverhostID table
                   12493: {
                   12494:     sub load_serverhomeIDs {
                   12495:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12496:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12497:                 while (my $configline=<$config>) {
                   12498:                     chomp($configline);
                   12499:                     my ($name,$id)=split(/:/,$configline);
                   12500:                     $serverhomeIDs{$name}=$id;
                   12501:                 }
                   12502:                 close($config);
                   12503:             }
                   12504:         }
                   12505:     }
                   12506: }
                   12507: 
                   12508: 
1.862     albertel 12509: BEGIN {
                   12510: 
                   12511: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12512:     unless ($readit) {
                   12513: {
                   12514:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12515:     %perlvar = (%perlvar,%{$configvars});
                   12516: }
                   12517: 
                   12518: 
1.1       albertel 12519: # ------------------------------------------------------ Read spare server file
                   12520: {
1.448     albertel 12521:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12522: 
                   12523:     while (my $configline=<$config>) {
                   12524:        chomp($configline);
1.284     matthew  12525:        if ($configline) {
1.784     albertel 12526: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12527: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12528: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12529:        }
                   12530:     }
1.448     albertel 12531:     close($config);
1.1       albertel 12532: }
1.11      www      12533: # ------------------------------------------------------------ Read permissions
                   12534: {
1.448     albertel 12535:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12536: 
                   12537:     while (my $configline=<$config>) {
1.448     albertel 12538: 	chomp($configline);
                   12539: 	if ($configline) {
                   12540: 	    my ($role,$perm)=split(/ /,$configline);
                   12541: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12542: 	}
1.11      www      12543:     }
1.448     albertel 12544:     close($config);
1.11      www      12545: }
                   12546: 
                   12547: # -------------------------------------------- Read plain texts for permissions
                   12548: {
1.448     albertel 12549:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12550: 
                   12551:     while (my $configline=<$config>) {
1.448     albertel 12552: 	chomp($configline);
                   12553: 	if ($configline) {
1.742     raeburn  12554: 	    my ($short,@plain)=split(/:/,$configline);
                   12555:             %{$prp{$short}} = ();
                   12556: 	    if (@plain > 0) {
                   12557:                 $prp{$short}{'std'} = $plain[0];
                   12558:                 for (my $i=1; $i<@plain; $i++) {
                   12559:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12560:                 }
                   12561:             }
1.448     albertel 12562: 	}
1.135     www      12563:     }
1.448     albertel 12564:     close($config);
1.135     www      12565: }
                   12566: 
                   12567: # ---------------------------------------------------------- Read package table
                   12568: {
1.448     albertel 12569:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12570: 
                   12571:     while (my $configline=<$config>) {
1.483     albertel 12572: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12573: 	chomp($configline);
                   12574: 	my ($short,$plain)=split(/:/,$configline);
                   12575: 	my ($pack,$name)=split(/\&/,$short);
                   12576: 	if ($plain ne '') {
                   12577: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12578: 	    $packagetab{$short}=$plain; 
                   12579: 	}
1.11      www      12580:     }
1.448     albertel 12581:     close($config);
1.329     matthew  12582: }
                   12583: 
1.1073    raeburn  12584: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  12585: 
                   12586: &load_loncaparevs();
1.1073    raeburn  12587: 
1.1074    raeburn  12588: # ---------------------------------------------------------- Read serverhostID table
                   12589: 
1.1227    raeburn  12590: &load_serverhomeIDs();
                   12591: 
                   12592: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12593: {
                   12594:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12595:     if (-e $file) {
                   12596:         my $parser = HTML::LCParser->new($file);
                   12597:         while (my $token = $parser->get_token()) {
                   12598:             if ($token->[0] eq 'S') {
                   12599:                 my $item = $token->[1];
                   12600:                 my $name = $token->[2]{'name'};
                   12601:                 my $value = $token->[2]{'value'};
                   12602:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12603:                     my $release = $parser->get_text();
                   12604:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12605:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12606:                 }
                   12607:             }
                   12608:         }
                   12609:     }
1.1073    raeburn  12610: }
                   12611: 
1.1138    raeburn  12612: # ---------------------------------------------------------- Read managers table
                   12613: {
                   12614:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12615:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12616:             while (my $configline=<$config>) {
                   12617:                 chomp($configline);
                   12618:                 next if ($configline =~ /^\#/);
                   12619:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12620:                     $managerstab{$configline} = 1;
                   12621:                 }
                   12622:             }
                   12623:             close($config);
                   12624:         }
                   12625:     }
                   12626: }
                   12627: 
1.329     matthew  12628: # ------------- set up temporary directory
                   12629: {
1.1117    foxr     12630:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12631: 
1.11      www      12632: }
                   12633: 
1.794     albertel 12634: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12635: 				'compress_threshold'=> 20_000,
                   12636:  			        });
1.185     www      12637: 
1.281     www      12638: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12639: $dumpcount=0;
1.958     www      12640: $locknum=0;
1.22      www      12641: 
1.163     harris41 12642: &logtouch();
1.672     albertel 12643: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12644: $readit=1;
1.564     albertel 12645:     {
                   12646: 	use integer;
                   12647: 	my $test=(2**32)+1;
1.568     albertel 12648: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12649: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12650:     }
1.195     www      12651: }
1.1       albertel 12652: }
1.179     www      12653: 
1.1       albertel 12654: 1;
1.191     harris41 12655: __END__
                   12656: 
1.243     albertel 12657: =pod
                   12658: 
1.191     harris41 12659: =head1 NAME
                   12660: 
1.243     albertel 12661: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12662: 
                   12663: =head1 SYNOPSIS
                   12664: 
1.243     albertel 12665: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12666: 
                   12667:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12668: 
1.243     albertel 12669: Common parameters:
                   12670: 
                   12671: =over 4
                   12672: 
                   12673: =item *
                   12674: 
                   12675: $uname : an internal username (if $cname expecting a course Id specifically)
                   12676: 
                   12677: =item *
                   12678: 
                   12679: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12680: 
                   12681: =item *
                   12682: 
                   12683: $symb : a resource instance identifier
                   12684: 
                   12685: =item *
                   12686: 
                   12687: $namespace : the name of a .db file that contains the data needed or
                   12688: being set.
                   12689: 
                   12690: =back
                   12691: 
1.394     bowersj2 12692: =head1 OVERVIEW
1.191     harris41 12693: 
1.394     bowersj2 12694: lonnet provides subroutines which interact with the
                   12695: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12696: about classes, users, and resources.
1.243     albertel 12697: 
                   12698: For many of these objects you can also use this to store data about
                   12699: them or modify them in various ways.
1.191     harris41 12700: 
1.394     bowersj2 12701: =head2 Symbs
1.191     harris41 12702: 
1.394     bowersj2 12703: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12704: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12705: map, the resource number of the resource in the map, and the URL of
                   12706: the resource itself. The latter is somewhat redundant, but might help
                   12707: if maps change.
                   12708: 
                   12709: An example is
                   12710: 
                   12711:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12712: 
                   12713: The respective map entry is
                   12714: 
                   12715:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12716:   title="Problem 2">
                   12717:  </resource>
                   12718: 
                   12719: Symbs are used by the random number generator, as well as to store and
                   12720: restore data specific to a certain instance of for example a problem.
                   12721: 
                   12722: =head2 Storing And Retrieving Data
                   12723: 
                   12724: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12725: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12726: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12727: is is the non-critical message twin of cstore. These functions are for
                   12728: handlers to store a perl hash to a user's permanent data space in an
                   12729: easy manner, and to retrieve it again on another call. It is expected
                   12730: that a handler would use this once at the beginning to retrieve data,
                   12731: and then again once at the end to send only the new data back.
                   12732: 
                   12733: The data is stored in the user's data directory on the user's
                   12734: homeserver under the ID of the course.
                   12735: 
                   12736: The hash that is returned by restore will have all of the previous
                   12737: value for all of the elements of the hash.
                   12738: 
                   12739: Example:
                   12740: 
                   12741:  #creating a hash
                   12742:  my %hash;
                   12743:  $hash{'foo'}='bar';
                   12744: 
                   12745:  #storing it
                   12746:  &Apache::lonnet::cstore(\%hash);
                   12747: 
                   12748:  #changing a value
                   12749:  $hash{'foo'}='notbar';
                   12750: 
                   12751:  #adding a new value
                   12752:  $hash{'bar'}='foo';
                   12753:  &Apache::lonnet::cstore(\%hash);
                   12754: 
                   12755:  #retrieving the hash
                   12756:  my %history=&Apache::lonnet::restore();
                   12757: 
                   12758:  #print the hash
                   12759:  foreach my $key (sort(keys(%history))) {
                   12760:    print("\%history{$key} = $history{$key}");
                   12761:  }
                   12762: 
                   12763: Will print out:
1.191     harris41 12764: 
1.394     bowersj2 12765:  %history{1:foo} = bar
                   12766:  %history{1:keys} = foo:timestamp
                   12767:  %history{1:timestamp} = 990455579
                   12768:  %history{2:bar} = foo
                   12769:  %history{2:foo} = notbar
                   12770:  %history{2:keys} = foo:bar:timestamp
                   12771:  %history{2:timestamp} = 990455580
                   12772:  %history{bar} = foo
                   12773:  %history{foo} = notbar
                   12774:  %history{timestamp} = 990455580
                   12775:  %history{version} = 2
                   12776: 
                   12777: Note that the special hash entries C<keys>, C<version> and
                   12778: C<timestamp> were added to the hash. C<version> will be equal to the
                   12779: total number of versions of the data that have been stored. The
                   12780: C<timestamp> attribute will be the UNIX time the hash was
                   12781: stored. C<keys> is available in every historical section to list which
                   12782: keys were added or changed at a specific historical revision of a
                   12783: hash.
                   12784: 
                   12785: B<Warning>: do not store the hash that restore returns directly. This
                   12786: will cause a mess since it will restore the historical keys as if the
                   12787: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12788: 
1.394     bowersj2 12789: Calling convention:
1.191     harris41 12790: 
1.1225    raeburn  12791:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  12792:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 12793: 
1.394     bowersj2 12794: For more detailed information, see lonnet specific documentation.
1.191     harris41 12795: 
1.394     bowersj2 12796: =head1 RETURN MESSAGES
1.191     harris41 12797: 
1.394     bowersj2 12798: =over 4
1.191     harris41 12799: 
1.394     bowersj2 12800: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12801: 
1.394     bowersj2 12802: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12803: when the connection is brought back up
1.191     harris41 12804: 
1.394     bowersj2 12805: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12806: for later delivery
1.191     harris41 12807: 
1.967     bisitz   12808: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12809: 
1.394     bowersj2 12810: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12811: that was requested
1.191     harris41 12812: 
1.243     albertel 12813: =back
1.191     harris41 12814: 
1.243     albertel 12815: =head1 PUBLIC SUBROUTINES
1.191     harris41 12816: 
1.243     albertel 12817: =head2 Session Environment Functions
1.191     harris41 12818: 
1.243     albertel 12819: =over 4
1.191     harris41 12820: 
1.394     bowersj2 12821: =item * 
                   12822: X<appenv()>
1.949     raeburn  12823: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12824: the user envirnoment file, and will be restored for each access this
1.620     albertel 12825: user makes during this session, also modifies the %env for the current
1.949     raeburn  12826: process. Optional rolesarrayref - if defined contains a reference to an array
                   12827: of roles which are exempt from the restriction on modifying user.role entries 
                   12828: in the user's environment.db and in %env.    
1.191     harris41 12829: 
                   12830: =item *
1.394     bowersj2 12831: X<delenv()>
1.987     raeburn  12832: B<delenv($delthis,$regexp)>: removes all items from the session
                   12833: environment file that begin with $delthis. If the 
                   12834: optional second arg - $regexp - is true, $delthis is treated as a 
                   12835: regular expression, otherwise \Q$delthis\E is used. 
                   12836: The values are also deleted from the current processes %env.
1.191     harris41 12837: 
1.795     albertel 12838: =item * get_env_multiple($name) 
                   12839: 
                   12840: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12841: values may be defined and end up as an array ref.
                   12842: 
                   12843: returns an array of values
                   12844: 
1.243     albertel 12845: =back
                   12846: 
                   12847: =head2 User Information
1.191     harris41 12848: 
1.243     albertel 12849: =over 4
1.191     harris41 12850: 
                   12851: =item *
1.394     bowersj2 12852: X<queryauthenticate()>
                   12853: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12854: authentication scheme
                   12855: 
                   12856: =item *
1.394     bowersj2 12857: X<authenticate()>
1.1073    raeburn  12858: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12859: authenticate user from domain's lib servers (first use the current
                   12860: one). C<$upass> should be the users password.
1.1073    raeburn  12861: $checkdefauth is optional (value is 1 if a check should be made to
                   12862:    authenticate user using default authentication method, and allow
                   12863:    account creation if username does not have account in the domain).
                   12864: $clientcancheckhost is optional (value is 1 if checking whether the
                   12865:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12866: 
                   12867: =item *
1.394     bowersj2 12868: X<homeserver()>
                   12869: B<homeserver($uname,$udom)>: find the server which has
                   12870: the user's directory and files (there must be only one), this caches
                   12871: the answer, and also caches if there is a borken connection.
1.191     harris41 12872: 
                   12873: =item *
1.394     bowersj2 12874: X<idget()>
                   12875: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12876: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12877: username, and only 1 username per ID in a specific domain) (returns
                   12878: hash: id=>name,id=>name)
1.191     harris41 12879: 
                   12880: =item *
1.394     bowersj2 12881: X<idrget()>
                   12882: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12883: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12884: 
                   12885: =item *
1.394     bowersj2 12886: X<idput()>
                   12887: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12888: 
                   12889: =item *
1.394     bowersj2 12890: X<rolesinit()>
1.1169    droeschl 12891: B<rolesinit($udom,$username)>: get user privileges.
                   12892: returns user role, first access and timer interval hashes
1.243     albertel 12893: 
                   12894: =item *
1.1171    droeschl 12895: X<privileged()>
                   12896: B<privileged($username,$domain)>: returns a true if user has a
                   12897: privileged and active role (i.e. su or dc), false otherwise.
                   12898: 
                   12899: =item *
1.551     albertel 12900: X<getsection()>
                   12901: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12902: course $cname, return section name/number or '' for "not in course"
                   12903: and '-1' for "no section"
                   12904: 
                   12905: =item *
1.394     bowersj2 12906: X<userenvironment()>
                   12907: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12908: passed in @what from the requested user's environment, returns a hash
                   12909: 
1.858     raeburn  12910: =item * 
                   12911: X<userlog_query()>
1.859     albertel 12912: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12913: activity.log file. %filters defines filters applied when parsing the
                   12914: log file. These can be start or end timestamps, or the type of action
                   12915: - log to look for Login or Logout events, check for Checkin or
                   12916: Checkout, role for role selection. The response is in the form
                   12917: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12918: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12919: 
1.243     albertel 12920: =back
                   12921: 
                   12922: =head2 User Roles
                   12923: 
                   12924: =over 4
                   12925: 
                   12926: =item *
                   12927: 
1.810     raeburn  12928: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12929:  F: full access
                   12930:  U,I,K: authentication modes (cxx only)
                   12931:  '': forbidden
                   12932:  1: user needs to choose course
                   12933:  2: browse allowed
1.766     albertel 12934:  A: passphrase authentication needed
1.243     albertel 12935: 
                   12936: =item *
                   12937: 
1.1192    raeburn  12938: constructaccess($url,$setpriv) : check for access to construction space URL
                   12939: 
                   12940: See if the owner domain and name in the URL match those in the
                   12941: expected environment.  If so, return three element list
                   12942: ($ownername,$ownerdomain,$ownerhome).
                   12943: 
                   12944: Otherwise return the null string.
                   12945: 
                   12946: If second argument 'setpriv' is true, it assigns the privileges,
                   12947: and returns the same three element list, unless the owner has
                   12948: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12949: in which case the null string is returned.
                   12950: 
                   12951: =item *
                   12952: 
1.243     albertel 12953: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12954: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12955: and course level
                   12956: 
                   12957: =item *
                   12958: 
1.988     raeburn  12959: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12960: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12961: $type is Course (default) or Community.
1.988     raeburn  12962: If $forcedefault evaluates to true, text returned will be default 
                   12963: text for $type. Otherwise, if this is a course, the text returned 
                   12964: will be a custom name for the role (if defined in the course's 
                   12965: environment).  If no custom name is defined the default is returned.
                   12966:    
1.832     raeburn  12967: =item *
                   12968: 
1.1219    raeburn  12969: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12970: All arguments are optional. Returns a hash of a roles, either for
                   12971: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12972: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12973: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12974: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12975: For each key, value is set to colon-separated start and end times for
                   12976: the role.  If no username and domain are specified, will default to
1.934     raeburn  12977: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12978: of role statuses (active, future or previous), roles 
                   12979: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12980: to restrict the list of roles reported. If no array ref is 
                   12981: provided for types, will default to return only active roles.
1.834     albertel 12982: 
1.1195    raeburn  12983: =item *
                   12984: 
                   12985: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  12986: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   12987: 
                   12988: Additional optional arguments are: $type (if role checking is to be restricted 
                   12989: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  12990: available roles) or future (roles available in the future), and
                   12991: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  12992: have active Domain Coordinator role in course's domain or in additional
                   12993: domains (specified in 'Domains to check for privileged users' in course
                   12994: environment -- set via:  Course Settings -> Classlists and staff listing).
                   12995: 
                   12996: =item *
                   12997: 
                   12998: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   12999: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13000: $possdomains and $possroles are optional array refs -- to domains to check and
                   13001: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13002: users' roles.db to check for a dc or su role in any domain. This can be
                   13003: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13004: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13005: this then allows &privileged_by_domain() to be used, which caches the identity
                   13006: of privileged users, eliminating the need for repeated calls to &dump().
                   13007: 
                   13008: =item *
                   13009: 
                   13010: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13011: where the outer hash keys are domains specified in the $possdomains array ref,
                   13012: next inner hash keys are privileged roles specified in the $roles array ref,
                   13013: and the innermost hash contains key = value pairs for username:domain = end:start
                   13014: for active or future "privileged" users with that role in that domain. To avoid
                   13015: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13016: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  13017: 
1.243     albertel 13018: =back
                   13019: 
                   13020: =head2 User Modification
                   13021: 
                   13022: =over 4
                   13023: 
                   13024: =item *
                   13025: 
1.957     raeburn  13026: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13027: user for the level given by URL.  Optional start and end dates (leave empty
                   13028: string or zero for "no date")
1.191     harris41 13029: 
                   13030: =item *
                   13031: 
1.243     albertel 13032: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13033: change a users, password, possible return values are: ok,
                   13034: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13035: refused
1.191     harris41 13036: 
                   13037: =item *
                   13038: 
1.243     albertel 13039: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13040: 
                   13041: =item *
                   13042: 
1.1058    raeburn  13043: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13044:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13045: 
                   13046: will update user information (firstname,middlename,lastname,generation,
                   13047: permanentemail), and if forceid is true, student/employee ID also.
                   13048: A user's institutional affiliation(s) can also be updated.
                   13049: User information fields will not be overwritten with empty entries 
                   13050: unless the field is included in the $candelete array reference.
                   13051: This array is included when a single user is modified via "Manage Users",
                   13052: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13053: 
                   13054: =item *
                   13055: 
1.286     matthew  13056: modifystudent
                   13057: 
1.957     raeburn  13058: modify a student's enrollment and identification information.
1.1235    raeburn  13059: The course id is resolved based on the current user's environment.  
                   13060: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13061: associated with a course.
                   13062: 
1.297     matthew  13063: This call is essentially a wrapper for lonnet::modifyuser and
                   13064: lonnet::modify_student_enrollment
1.286     matthew  13065: 
                   13066: Inputs: 
                   13067: 
                   13068: =over 4
                   13069: 
1.957     raeburn  13070: =item B<$udom> Student's loncapa domain
1.286     matthew  13071: 
1.957     raeburn  13072: =item B<$uname> Student's loncapa login name
1.286     matthew  13073: 
1.964     bisitz   13074: =item B<$uid> Student/Employee ID
1.286     matthew  13075: 
1.957     raeburn  13076: =item B<$umode> Student's authentication mode
1.286     matthew  13077: 
1.957     raeburn  13078: =item B<$upass> Student's password
1.286     matthew  13079: 
1.957     raeburn  13080: =item B<$first> Student's first name
1.286     matthew  13081: 
1.957     raeburn  13082: =item B<$middle> Student's middle name
1.286     matthew  13083: 
1.957     raeburn  13084: =item B<$last> Student's last name
1.286     matthew  13085: 
1.957     raeburn  13086: =item B<$gene> Student's generation
1.286     matthew  13087: 
1.957     raeburn  13088: =item B<$usec> Student's section in course
1.286     matthew  13089: 
                   13090: =item B<$end> Unix time of the roles expiration
                   13091: 
                   13092: =item B<$start> Unix time of the roles start date
                   13093: 
                   13094: =item B<$forceid> If defined, allow $uid to be changed
                   13095: 
                   13096: =item B<$desiredhome> server to use as home server for student
                   13097: 
1.957     raeburn  13098: =item B<$email> Student's permanent e-mail address
                   13099: 
                   13100: =item B<$type> Type of enrollment (auto or manual)
                   13101: 
1.963     raeburn  13102: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13103: 
                   13104: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13105: 
1.963     raeburn  13106: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13107: 
1.963     raeburn  13108: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13109: 
1.1216    raeburn  13110: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13111: 
                   13112: =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  13113: 
1.286     matthew  13114: =back
1.297     matthew  13115: 
                   13116: =item *
                   13117: 
                   13118: modify_student_enrollment
                   13119: 
1.1235    raeburn  13120: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13121: 'role.request.course' must be defined for this function to proceed.
                   13122: 
                   13123: Inputs:
                   13124: 
                   13125: =over 4
                   13126: 
1.1235    raeburn  13127: =item $udom, student's domain
1.297     matthew  13128: 
1.1235    raeburn  13129: =item $uname, student's name
1.297     matthew  13130: 
1.1235    raeburn  13131: =item $uid, student's user id
1.297     matthew  13132: 
1.1235    raeburn  13133: =item $first, student's first name
1.297     matthew  13134: 
                   13135: =item $middle
                   13136: 
                   13137: =item $last
                   13138: 
                   13139: =item $gene
                   13140: 
                   13141: =item $usec
                   13142: 
                   13143: =item $end
                   13144: 
                   13145: =item $start
                   13146: 
1.957     raeburn  13147: =item $type
                   13148: 
                   13149: =item $locktype
                   13150: 
                   13151: =item $cid
                   13152: 
                   13153: =item $selfenroll
                   13154: 
                   13155: =item $context
                   13156: 
1.1216    raeburn  13157: =item $credits, number of credits student will earn from this class
                   13158: 
1.297     matthew  13159: =back
                   13160: 
1.191     harris41 13161: 
                   13162: =item *
                   13163: 
1.243     albertel 13164: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13165: custom role; give a custom role to a user for the level given by URL.  Specify
                   13166: name and domain of role author, and role name
1.191     harris41 13167: 
                   13168: =item *
                   13169: 
1.243     albertel 13170: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13171: 
                   13172: =item *
                   13173: 
1.243     albertel 13174: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13175: 
                   13176: =back
                   13177: 
                   13178: =head2 Course Infomation
                   13179: 
                   13180: =over 4
1.191     harris41 13181: 
                   13182: =item *
                   13183: 
1.1118    foxr     13184: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13185: specified course id, including all environment settings for the
                   13186: course, the description of the course will be in the hash under the
                   13187: key 'description'
1.191     harris41 13188: 
1.1118    foxr     13189: $options is an optional parameter that if supplied is a hash reference that controls
                   13190: what how this function works.  It has the following key/values:
                   13191: 
                   13192: =over 4
                   13193: 
                   13194: =item freshen_cache
                   13195: 
                   13196: If defined, and the environment cache for the course is valid, it is 
                   13197: returned in the returned hash.
                   13198: 
                   13199: =item one_time
                   13200: 
                   13201: If defined, the last cache time is set to _now_
                   13202: 
                   13203: =item user
                   13204: 
                   13205: If defined, the supplied username is used instead of the current user.
                   13206: 
                   13207: 
                   13208: =back
                   13209: 
1.191     harris41 13210: =item *
                   13211: 
1.624     albertel 13212: resdata($name,$domain,$type,@which) : request for current parameter
                   13213: setting for a specific $type, where $type is either 'course' or 'user',
                   13214: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  13215: answers for 10 minutes.
1.243     albertel 13216: 
1.877     foxr     13217: =item *
                   13218: 
                   13219: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13220: data base, returning a hash that is keyed by the resource name and has
                   13221: values that are the resource value.  I believe that the timestamps and
                   13222: versions are also returned.
                   13223: 
1.1236    raeburn  13224: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13225: supplemental content area. This routine caches the number of files for 
                   13226: 10 minutes.
                   13227: 
1.243     albertel 13228: =back
                   13229: 
                   13230: =head2 Course Modification
                   13231: 
                   13232: =over 4
1.191     harris41 13233: 
                   13234: =item *
                   13235: 
1.243     albertel 13236: writecoursepref($courseid,%prefs) : write preferences (environment
                   13237: database) for a course
1.191     harris41 13238: 
                   13239: =item *
                   13240: 
1.1011    raeburn  13241: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13242: 
                   13243: =item *
                   13244: 
1.1038    raeburn  13245: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13246: 
1.1167    droeschl 13247: =item *
                   13248: 
                   13249: is_course($courseid), is_course($cdom, $cnum)
                   13250: 
                   13251: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13252: two component version $cdom, $cnum. It checks if the specified course exists.
                   13253: 
                   13254: Returns:
                   13255:     undef if the course doesn't exist, otherwise
                   13256:     in scalar context the combined courseid.
                   13257:     in list context the two components of the course identifier, domain and 
                   13258:     courseid.    
                   13259: 
1.243     albertel 13260: =back
                   13261: 
                   13262: =head2 Resource Subroutines
                   13263: 
                   13264: =over 4
1.191     harris41 13265: 
                   13266: =item *
                   13267: 
1.243     albertel 13268: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13269: 
                   13270: =item *
                   13271: 
1.243     albertel 13272: repcopy($filename) : subscribes to the requested file, and attempts to
                   13273: replicate from the owning library server, Might return
1.607     raeburn  13274: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13275: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13276: resource. Expects the local filesystem pathname
                   13277: (/home/httpd/html/res/....)
                   13278: 
                   13279: =back
                   13280: 
                   13281: =head2 Resource Information
                   13282: 
                   13283: =over 4
1.191     harris41 13284: 
                   13285: =item *
                   13286: 
1.1228    raeburn  13287: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13288: and returns the value of a variety of different possible values,
                   13289: $varname should be a request string, and the other parameters can be
                   13290: used to specify who and what one is asking about. Ordinarily, $cid 
                   13291: does not need to be specified, as it is retrived from 
                   13292: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13293: within lonuserstate::loadmap() when initializing a course, before
                   13294: $env{'request.course.id'} has been set, so it needs to be provided
                   13295: in that one case.
1.243     albertel 13296: 
                   13297: Possible values for $varname are environment.lastname (or other item
                   13298: from the envirnment hash), user.name (or someother aspect about the
                   13299: user), resource.0.maxtries (or some other part and parameter of a
                   13300: resource)
1.204     albertel 13301: 
                   13302: =item *
                   13303: 
1.243     albertel 13304: directcondval($number) : get current value of a condition; reads from a state
                   13305: string
1.204     albertel 13306: 
                   13307: =item *
                   13308: 
1.243     albertel 13309: condval($condidx) : value of condition index based on state
1.204     albertel 13310: 
                   13311: =item *
                   13312: 
1.243     albertel 13313: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13314: resource's metadata, $what should be either a specific key, or either
                   13315: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13316: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13317: 
                   13318: this function automatically caches all requests
1.191     harris41 13319: 
                   13320: =item *
                   13321: 
1.243     albertel 13322: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13323: network of library servers; returns file handle of where SQL and regex results
                   13324: will be stored for query
1.191     harris41 13325: 
                   13326: =item *
                   13327: 
1.243     albertel 13328: symbread($filename) : return symbolic list entry (filename argument optional);
                   13329: returns the data handle
1.191     harris41 13330: 
                   13331: =item *
                   13332: 
1.1190    raeburn  13333: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   13334: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13335: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  13336: on failure, user must be in a course, as it assumes the existence of
                   13337: the course initial hash, and uses $env('request.course.id'}.  The third
                   13338: arg is an optional reference to a scalar.  If this arg is passed in the 
                   13339: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13340: encrypted; otherwise it will be null.  
1.191     harris41 13341: 
                   13342: =item *
                   13343: 
1.243     albertel 13344: symbclean($symb) : removes versions numbers from a symb, returns the
                   13345: cleaned symb
1.191     harris41 13346: 
                   13347: =item *
                   13348: 
1.243     albertel 13349: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13350: course map, user must be in a course for it to work.
1.191     harris41 13351: 
                   13352: =item *
                   13353: 
1.243     albertel 13354: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13355: 
                   13356: =item *
                   13357: 
1.243     albertel 13358: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13359: a random seed, all arguments are optional, if they aren't sent it uses the
                   13360: environment to derive them. Note: if symb isn't sent and it can't get one
                   13361: from &symbread it will use the current time as its return value
1.191     harris41 13362: 
                   13363: =item *
                   13364: 
1.243     albertel 13365: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13366: unfakeable, receipt
1.191     harris41 13367: 
                   13368: =item *
                   13369: 
1.620     albertel 13370: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13371: 
                   13372: =item *
                   13373: 
1.243     albertel 13374: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13375: 
                   13376: =item *
                   13377: 
1.243     albertel 13378: 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 13379: 
                   13380: =item *
                   13381: 
1.243     albertel 13382: 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 13383: 
                   13384: =item *
                   13385: 
1.243     albertel 13386: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13387: 
                   13388: =item *
                   13389: 
1.243     albertel 13390: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13391: forcing spreadsheet to reevaluate the resource scores next time.
                   13392: 
1.1195    raeburn  13393: =item * 
                   13394: 
1.1196    raeburn  13395: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13396: when viewing in course context.
1.1195    raeburn  13397: 
1.1196    raeburn  13398:  input: six args -- filename (decluttered), course number, course domain,
                   13399:                     url, symb (if registered) and group (if this is a 
                   13400:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  13401: 
1.1196    raeburn  13402:  output: array of five scalars --
1.1195    raeburn  13403:          $cfile -- url for file editing if editable on current server
                   13404:          $home -- homeserver of resource (i.e., for author if published,
                   13405:                                           or course if uploaded.).
                   13406:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  13407:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   13408:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  13409: 
                   13410: =item *
                   13411: 
                   13412: is_course_upload($file,$cnum,$cdom)
                   13413: 
                   13414: Used in course context to determine if current file was uploaded to 
                   13415: the course (i.e., would be found in /userfiles/docs on the course's 
                   13416: homeserver.
                   13417: 
                   13418:   input: 3 args -- filename (decluttered), course number and course domain.
                   13419:   output: boolean -- 1 if file was uploaded.
                   13420: 
1.243     albertel 13421: =back
                   13422: 
                   13423: =head2 Storing/Retreiving Data
                   13424: 
                   13425: =over 4
1.191     harris41 13426: 
                   13427: =item *
                   13428: 
1.1269    raeburn  13429: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   13430: permanently for this url; hashref needs to be given and should be a \%hashname;
                   13431: the remaining args aren't required and if they aren't passed or are '' they will
                   13432: be derived from the env (with the exception of $laststore, which is an 
                   13433: optional arg used when a user's submission is stored in grading).
                   13434: $laststore is $version=$timestamp, where $version is the most recent version
                   13435: number retrieved for the corresponding $symb in the $namespace db file, and
                   13436: $timestamp is the timestamp for that transaction (UNIX time).
                   13437: $laststore is currently only passed when cstore() is called by 
                   13438: structuretags::finalize_storage().
1.191     harris41 13439: 
                   13440: =item *
                   13441: 
1.1269    raeburn  13442: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   13443: but uses critical subroutine
1.191     harris41 13444: 
                   13445: =item *
                   13446: 
1.243     albertel 13447: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13448: all args are optional
1.191     harris41 13449: 
                   13450: =item *
                   13451: 
1.717     albertel 13452: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13453: dumps the complete (or key matching regexp) namespace into a hash
                   13454: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13455: normally &store()ed into
                   13456: 
                   13457: $range should be either an integer '100' (give me the first 100
                   13458:                                            matching records)
                   13459:               or be  two integers sperated by a - with no spaces
                   13460:                  '30-50' (give me the 30th through the 50th matching
                   13461:                           records)
                   13462: 
                   13463: 
                   13464: =item *
                   13465: 
1.1269    raeburn  13466: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 13467: replaces a &store() version of data with a replacement set of data
                   13468: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  13469: reference. If $tolog is true, the transaction is logged in the courselog
                   13470: with an action=PUTSTORE.
1.717     albertel 13471: 
                   13472: =item *
                   13473: 
1.243     albertel 13474: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13475: works very similar to store/cstore, but all data is stored in a
                   13476: temporary location and can be reset using tmpreset, $storehash should
                   13477: be a hash reference, returns nothing on success
1.191     harris41 13478: 
                   13479: =item *
                   13480: 
1.243     albertel 13481: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13482: similar to restore, but all data is stored in a temporary location and
                   13483: can be reset using tmpreset. Returns a hash of values on success,
                   13484: error string otherwise.
1.191     harris41 13485: 
                   13486: =item *
                   13487: 
1.243     albertel 13488: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13489: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13490: 
                   13491: =item *
                   13492: 
1.243     albertel 13493: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13494: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13495: 
                   13496: =item *
                   13497: 
1.243     albertel 13498: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13499: namesp ($udom and $uname are optional)
1.191     harris41 13500: 
                   13501: =item *
                   13502: 
1.702     albertel 13503: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13504: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13505: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13506: 
1.702     albertel 13507: $range should be either an integer '100' (give me the first 100
                   13508:                                            matching records)
                   13509:               or be  two integers sperated by a - with no spaces
                   13510:                  '30-50' (give me the 30th through the 50th matching
                   13511:                           records)
1.449     matthew  13512: =item *
                   13513: 
                   13514: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13515: $store can be a scalar, an array reference, or if the amount to be 
                   13516: incremented is > 1, a hash reference.
                   13517: 
                   13518: ($udom and $uname are optional)
1.191     harris41 13519: 
                   13520: =item *
                   13521: 
1.243     albertel 13522: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13523: ($udom and $uname are optional)
1.191     harris41 13524: 
                   13525: =item *
                   13526: 
1.243     albertel 13527: cput($namespace,$storehash,$udom,$uname) : critical put
                   13528: ($udom and $uname are optional)
1.191     harris41 13529: 
                   13530: =item *
                   13531: 
1.748     albertel 13532: newput($namespace,$storehash,$udom,$uname) :
                   13533: 
                   13534: Attempts to store the items in the $storehash, but only if they don't
                   13535: currently exist, if this succeeds you can be certain that you have 
                   13536: successfully created a new key value pair in the $namespace db.
                   13537: 
                   13538: 
                   13539: Args:
                   13540:  $namespace: name of database to store values to
                   13541:  $storehash: hashref to store to the db
                   13542:  $udom: (optional) domain of user containing the db
                   13543:  $uname: (optional) name of user caontaining the db
                   13544: 
                   13545: Returns:
                   13546:  'ok' -> succeeded in storing all keys of $storehash
                   13547:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13548:                         least <key> already existed in the db (other
                   13549:                         requested keys may also already exist)
1.967     bisitz   13550:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13551:  'con_lost' -> unable to contact request server
                   13552:  'refused' -> action was not allowed by remote machine
                   13553: 
                   13554: 
                   13555: =item *
                   13556: 
1.243     albertel 13557: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13558: reference filled in from namesp (encrypts the return communication)
                   13559: ($udom and $uname are optional)
1.191     harris41 13560: 
                   13561: =item *
                   13562: 
1.243     albertel 13563: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13564: critical subroutine
                   13565: 
1.806     raeburn  13566: =item *
                   13567: 
1.860     raeburn  13568: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13569: array reference filled in from namespace found in domain level on either
                   13570: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13571: 
                   13572: =item *
                   13573: 
1.860     raeburn  13574: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13575: domain level either on specified domain server ($uhome) or primary domain 
                   13576: server ($udom and $uhome are optional)
1.806     raeburn  13577: 
1.943     raeburn  13578: =item * 
                   13579: 
1.1240    raeburn  13580: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   13581: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13582: the target domain.
                   13583: 
                   13584: May also include additional key => value pairs for the following groups:
                   13585: 
                   13586: =over
                   13587: 
                   13588: =item
                   13589: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13590: 
                   13591: =over
                   13592: 
                   13593: =item defaultquota, authorquota
                   13594: 
                   13595: =back
                   13596: 
                   13597: =item
                   13598: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13599: portfolio for users).
                   13600: 
                   13601: =over
                   13602: 
                   13603: =item
                   13604: aboutme, blog, webdav, portfolio
                   13605: 
                   13606: =back
                   13607: 
                   13608: =item
                   13609: requestcourses: ability to request courses, and how requests are processed.
                   13610: 
                   13611: =over
                   13612: 
                   13613: =item
1.1246    raeburn  13614: official, unofficial, community, textbook
1.1240    raeburn  13615: 
                   13616: =back
                   13617: 
                   13618: =item
                   13619: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13620: 
                   13621: =over
                   13622: 
                   13623: =item
1.1256    raeburn  13624: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  13625: 
                   13626: =back
                   13627: 
                   13628: =item
                   13629: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13630: for course's uploaded content.
                   13631: 
                   13632: =over
                   13633: 
                   13634: =item
1.1246    raeburn  13635: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
                   13636: communityquota, textbookquota
1.1240    raeburn  13637: 
                   13638: =back
                   13639: 
                   13640: =item
                   13641: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13642: on your servers.
                   13643: 
                   13644: =over
                   13645: 
                   13646: =item 
                   13647: remotesessions, hostedsessions
                   13648: 
                   13649: =back
                   13650: 
                   13651: =back
                   13652: 
                   13653: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13654: utility to create a configuration.db file on a domain's primary library server 
                   13655: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13656: -- corresponding values are authentication type (internal, krb4, krb5,
                   13657: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   13658: will be available. Values are retrieved from cache (if current), unless the
                   13659: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13660: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13661: 
                   13662: Typical usage:
1.943     raeburn  13663: 
1.1240    raeburn  13664: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13665: 
1.243     albertel 13666: =back
                   13667: 
                   13668: =head2 Network Status Functions
                   13669: 
                   13670: =over 4
1.191     harris41 13671: 
                   13672: =item *
                   13673: 
1.1137    raeburn  13674: dirlist() : return directory list based on URI (first arg).
                   13675: 
                   13676: Inputs: 1 required, 5 optional.
                   13677: 
                   13678: =over
                   13679: 
                   13680: =item 
                   13681: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13682: 
                   13683: =item
                   13684: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13685: 
                   13686: =item
                   13687: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13688: 
                   13689: =item
                   13690: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13691: 
                   13692: =item
                   13693: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13694: 
                   13695: =item 
                   13696: $alternateRoot - path to prepend in place of path from $uri.
                   13697: 
                   13698: =back
                   13699: 
                   13700: Returns: Array of up to two items.
                   13701: 
                   13702: =over
                   13703: 
                   13704: a reference to an array of files/subdirectories
                   13705: 
                   13706: =over
                   13707: 
                   13708: Each element in the array of files/subdirectories is a & separated list of
                   13709: item name and the result of running stat on the item.  If dirlist was requested
                   13710: for a file instead of a directory, the item name will be ''. For a directory 
                   13711: listing, if the item is a metadata file, the element will end &N&M 
                   13712: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13713: default copyright set (1).  
                   13714: 
                   13715: =back
                   13716: 
                   13717: a scalar containing error condition (if encountered).
                   13718: 
                   13719: =over
                   13720: 
                   13721: =item 
                   13722: no_host (no homeserver identified for $username:$domain).
                   13723: 
                   13724: =item 
                   13725: no_such_host (server contacted for listing not identified as valid host).
                   13726: 
                   13727: =item 
                   13728: con_lost (connection to remote server failed).
                   13729: 
                   13730: =item 
                   13731: refused (invalid $username:$domain received on lond side).
                   13732: 
                   13733: =item 
                   13734: no_such_dir (directory at specified path on lond side does not exist). 
                   13735: 
                   13736: =item 
                   13737: empty (directory at specified path on lond side is empty).
                   13738: 
                   13739: =over
                   13740: 
                   13741: This is currently not encountered because the &ls3, &ls2, 
                   13742: &ls (_handler) routines on the lond side do not filter out
                   13743: . and .. from a directory listing. 
                   13744: 
                   13745: =back
                   13746: 
                   13747: =back
                   13748: 
                   13749: =back
1.191     harris41 13750: 
                   13751: =item *
                   13752: 
1.243     albertel 13753: spareserver() : find server with least workload from spare.tab
                   13754: 
1.986     foxr     13755: 
                   13756: =item *
                   13757: 
                   13758: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13759: if there is no corresponding loncapa host.
                   13760: 
1.243     albertel 13761: =back
                   13762: 
1.986     foxr     13763: 
1.243     albertel 13764: =head2 Apache Request
                   13765: 
                   13766: =over 4
1.191     harris41 13767: 
                   13768: =item *
                   13769: 
1.243     albertel 13770: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13771: localhost, posts hash
                   13772: 
                   13773: =back
                   13774: 
                   13775: =head2 Data to String to Data
                   13776: 
                   13777: =over 4
1.191     harris41 13778: 
                   13779: =item *
                   13780: 
1.243     albertel 13781: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13782: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13783: 
                   13784: =item *
                   13785: 
1.243     albertel 13786: hashref2str($hashref) : convert a hashref into a string complete with
                   13787: escaping and '=' and '&' separators, supports elements that are
                   13788: arrayrefs and hashrefs
1.191     harris41 13789: 
                   13790: =item *
                   13791: 
1.243     albertel 13792: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13793: with escaping and '&' separators, supports elements that are arrayrefs
                   13794: and hashrefs
1.191     harris41 13795: 
                   13796: =item *
                   13797: 
1.243     albertel 13798: str2hash($string) : convert string to hash using unescaping and
                   13799: splitting on '=' and '&', supports elements that are arrayrefs and
                   13800: hashrefs
1.191     harris41 13801: 
                   13802: =item *
                   13803: 
1.243     albertel 13804: str2array($string) : convert string to hash using unescaping and
                   13805: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13806: 
                   13807: =back
                   13808: 
                   13809: =head2 Logging Routines
                   13810: 
                   13811: 
                   13812: These routines allow one to make log messages in the lonnet.log and
                   13813: lonnet.perm logfiles.
1.191     harris41 13814: 
1.1119    foxr     13815: =over 4
                   13816: 
1.191     harris41 13817: =item *
                   13818: 
1.243     albertel 13819: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13820: 
                   13821: =item *
                   13822: 
1.243     albertel 13823: logthis() : append message to the normal lonnet.log file, it gets
                   13824: preiodically rolled over and deleted.
1.191     harris41 13825: 
                   13826: =item *
                   13827: 
1.243     albertel 13828: logperm() : append a permanent message to lonnet.perm.log, this log
                   13829: file never gets deleted by any automated portion of the system, only
                   13830: messages of critical importance should go in here.
                   13831: 
1.1119    foxr     13832: 
1.243     albertel 13833: =back
                   13834: 
                   13835: =head2 General File Helper Routines
                   13836: 
                   13837: =over 4
1.191     harris41 13838: 
                   13839: =item *
                   13840: 
1.481     raeburn  13841: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13842: (a) files in /uploaded
                   13843:   (i) If a local copy of the file exists - 
                   13844:       compares modification date of local copy with last-modified date for 
                   13845:       definitive version stored on home server for course. If local copy is 
                   13846:       stale, requests a new version from the home server and stores it. 
                   13847:       If the original has been removed from the home server, then local copy 
                   13848:       is unlinked.
                   13849:   (ii) If local copy does not exist -
                   13850:       requests the file from the home server and stores it. 
                   13851:   
                   13852:   If $caller is 'uploadrep':  
                   13853:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13854:     for request for files originally uploaded via DOCS. 
                   13855:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13856:   
                   13857:   Otherwise:
                   13858:      This indicates a call from the content generation phase of the request.
                   13859:      -  returns the entire contents of the file or -1.
                   13860:      
                   13861: (b) files in /res
                   13862:    - returns the entire contents of a file or -1; 
                   13863:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13864: 
1.712     albertel 13865: 
                   13866: =item *
                   13867: 
                   13868: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13869:                   reference
                   13870: 
                   13871: returns either a stat() list of data about the file or an empty list
                   13872: if the file doesn't exist or couldn't find out about it (connection
                   13873: problems or user unknown)
                   13874: 
1.191     harris41 13875: =item *
                   13876: 
1.243     albertel 13877: filelocation($dir,$file) : returns file system location of a file
                   13878: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13879: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13880: and a file of ../bob will become /a/bob)
1.191     harris41 13881: 
                   13882: =item *
                   13883: 
                   13884: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13885: filelocation except for hrefs
                   13886: 
                   13887: =item *
                   13888: 
1.1261    raeburn  13889: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   13890: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 13891: 
1.243     albertel 13892: =back
                   13893: 
1.608     albertel 13894: =head2 Usererfile file routines (/uploaded*)
                   13895: 
                   13896: =over 4
                   13897: 
                   13898: =item *
                   13899: 
                   13900: userfileupload(): main rotine for putting a file in a user or course's
                   13901:                   filespace, arguments are,
                   13902: 
1.620     albertel 13903:  formname - required - this is the name of the element in $env where the
1.608     albertel 13904:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13905:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13906:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13907:  context - if coursedoc, store the file in the course of the active role
                   13908:              of the current user; 
                   13909:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13910:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13911:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13912:          if undefined, it will be placed in "unknown"
                   13913: 
                   13914:  (This routine calls clean_filename() to remove any dangerous
                   13915:  characters from the filename, and then calls finuserfileupload() to
                   13916:  complete the transaction)
                   13917: 
                   13918:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13919:  and /adm/notfound.html if unsuccessful
                   13920: 
                   13921: =item *
                   13922: 
                   13923: clean_filename(): routine for cleaing a filename up for storage in
                   13924:                  userfile space, argument is:
                   13925: 
                   13926:  filename - proposed filename
                   13927: 
                   13928: returns: the new clean filename
                   13929: 
                   13930: =item *
                   13931: 
1.1090    raeburn  13932: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13933: userspace, probably shouldn't be called directly
                   13934: 
                   13935:   docuname: username or courseid of destination for the file
                   13936:   docudom: domain of user/course of destination for the file
                   13937:   formname: same as for userfileupload()
1.1090    raeburn  13938:   fname: filename (including subdirectories) for the file
                   13939:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13940:   allfiles: reference to hash used to store objects found by parser
                   13941:   codebase: reference to hash used for codebases of java objects found by parser
                   13942:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13943:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13944:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13945:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13946:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13947:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13948:   mimetype: reference to scalar to accommodate mime type determined
                   13949:             from File::MMagic if $parser = parse.
1.608     albertel 13950: 
                   13951:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13952:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13953:  was 'overwrite').
                   13954:  
1.608     albertel 13955: 
                   13956: =item *
                   13957: 
                   13958: renameuserfile(): renames an existing userfile to a new name
                   13959: 
                   13960:   Args:
                   13961:    docuname: username or courseid of destination for the file
                   13962:    docudom: domain of user/course of destination for the file
                   13963:    old: current file name (including any subdirs under userfiles)
                   13964:    new: desired file name (including any subdirs under userfiles)
                   13965: 
                   13966: =item *
                   13967: 
                   13968: mkdiruserfile(): creates a directory is a userfiles dir
                   13969: 
                   13970:   Args:
                   13971:    docuname: username or courseid of destination for the file
                   13972:    docudom: domain of user/course of destination for the file
                   13973:    dir: dir to create (including any subdirs under userfiles)
                   13974: 
                   13975: =item *
                   13976: 
                   13977: removeuserfile(): removes a file that exists in userfiles
                   13978: 
                   13979:   Args:
                   13980:    docuname: username or courseid of destination for the file
                   13981:    docudom: domain of user/course of destination for the file
                   13982:    fname: filname to delete (including any subdirs under userfiles)
                   13983: 
                   13984: =item *
                   13985: 
                   13986: removeuploadedurl(): convience function for removeuserfile()
                   13987: 
                   13988:   Args:
                   13989:    url:  a full /uploaded/... url to delete
                   13990: 
1.747     albertel 13991: =item * 
                   13992: 
                   13993: get_portfile_permissions():
                   13994:   Args:
                   13995:     domain: domain of user or course contain the portfolio files
                   13996:     user: name of user or num of course contain the portfolio files
                   13997:   Returns:
                   13998:     hashref of a dump of the proper file_permissions.db
                   13999:    
                   14000: 
                   14001: =item * 
                   14002: 
                   14003: get_access_controls():
                   14004: 
                   14005: Args:
                   14006:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14007:   group: (optional) the group you want the files associated with
                   14008:   file: (optional) the file you want access info on
                   14009: 
                   14010: Returns:
1.749     raeburn  14011:     a hash (keys are file names) of hashes containing
                   14012:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14013:         values are XML containing access control settings (see below) 
1.747     albertel 14014: 
                   14015: Internal notes:
                   14016: 
1.749     raeburn  14017:  access controls are stored in file_permissions.db as key=value pairs.
                   14018:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14019:         where scope -> public,guest,course,group,domains or users.
                   14020:               end -> UNIX time for end of access (0 -> no end date)
                   14021:               start -> UNIX time for start of access
                   14022: 
                   14023:     value -> XML description of access control
                   14024:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14025:             <start></start>
                   14026:             <end></end>
                   14027: 
                   14028:             <password></password>  for scope type = guest
                   14029: 
                   14030:             <domain></domain>     for scope type = course or group
                   14031:             <number></number>
                   14032:             <roles id="">
                   14033:              <role></role>
                   14034:              <access></access>
                   14035:              <section></section>
                   14036:              <group></group>
                   14037:             </roles>
                   14038: 
                   14039:             <dom></dom>         for scope type = domains
                   14040: 
                   14041:             <users>             for scope type = users
                   14042:              <user>
                   14043:               <uname></uname>
                   14044:               <udom></udom>
                   14045:              </user>
                   14046:             </users>
                   14047:            </scope> 
                   14048:               
                   14049:  Access data is also aggregated for each file in an additional key=value pair:
                   14050:  key -> path to file/file_name\0accesscontrol 
                   14051:  value -> reference to hash
                   14052:           hash contains key = value pairs
                   14053:           where key = uniqueID:scope_end_start
                   14054:                 value = UNIX time record was last updated
                   14055: 
                   14056:           Used to improve speed of look-ups of access controls for each file.  
                   14057:  
                   14058:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14059: 
1.1198    raeburn  14060: =item *
                   14061: 
1.749     raeburn  14062: modify_access_controls():
                   14063: 
                   14064: Modifies access controls for a portfolio file
                   14065: Args
                   14066: 1. file name
                   14067: 2. reference to hash of required changes,
                   14068: 3. domain
                   14069: 4. username
                   14070:   where domain,username are the domain of the portfolio owner 
                   14071:   (either a user or a course) 
                   14072: 
                   14073: Returns:
                   14074: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14075: 2. result of deletions ('ok' or 'error', with error message).
                   14076: 3. reference to hash of any new or updated access controls.
                   14077: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14078:    key = integer (inbound ID)
1.1198    raeburn  14079:    value = uniqueID
                   14080: 
                   14081: =item *
                   14082: 
                   14083: get_timebased_id():
                   14084: 
                   14085: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   14086: course via the Course Editor (e.g., folders, composite pages, 
                   14087: group bulletin boards).
                   14088: 
                   14089: Args: (first three required; six others optional)
                   14090: 
                   14091: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14092:    docssequence, or name of group
                   14093: 
                   14094: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14095:    e.g., num, boardids
                   14096: 
                   14097: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   14098:    file will be named nohist_namespace.db
                   14099: 
                   14100: 4. cdom: domain of course; default is current course domain from %env
                   14101: 
                   14102: 5. cnum: course number; default is current course number from %env
                   14103: 
                   14104: 6. idtype: set to concat if an additional digit is to be appended to the 
                   14105:    unix timestamp to form the suffix, if the plain timestamp is already
                   14106:    in use.  Default is to not do this, but simply increment the unix 
                   14107:    timestamp by 1 until a unique key is obtained.
                   14108: 
                   14109: 7. who: holder of locking key; defaults to user:domain for user.
                   14110: 
                   14111: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   14112:    retrying); default is 3.
                   14113: 
                   14114: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   14115: 
                   14116: Returns:
                   14117: 
                   14118: 1. suffix obtained (numeric)
                   14119: 
                   14120: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14121: 
                   14122: 3. error: contains (localized) error message if an error occurred.
                   14123: 
1.747     albertel 14124: 
1.608     albertel 14125: =back
                   14126: 
1.243     albertel 14127: =head2 HTTP Helper Routines
                   14128: 
                   14129: =over 4
                   14130: 
1.191     harris41 14131: =item *
                   14132: 
                   14133: escape() : unpack non-word characters into CGI-compatible hex codes
                   14134: 
                   14135: =item *
                   14136: 
                   14137: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14138: 
1.243     albertel 14139: =back
                   14140: 
                   14141: =head1 PRIVATE SUBROUTINES
                   14142: 
                   14143: =head2 Underlying communication routines (Shouldn't call)
                   14144: 
                   14145: =over 4
                   14146: 
                   14147: =item *
                   14148: 
                   14149: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14150: 
                   14151: =item *
                   14152: 
                   14153: reply() : uses subreply to send a message to remote machine, logs all failures
                   14154: 
                   14155: =item *
                   14156: 
                   14157: critical() : passes a critical message to another server; if cannot
                   14158: get through then place message in connection buffer directory and
                   14159: returns con_delayed, if incapable of saving message, returns
                   14160: con_failed
                   14161: 
                   14162: =item *
                   14163: 
                   14164: reconlonc() : tries to reconnect lonc client processes.
                   14165: 
                   14166: =back
                   14167: 
                   14168: =head2 Resource Access Logging
                   14169: 
                   14170: =over 4
                   14171: 
                   14172: =item *
                   14173: 
                   14174: flushcourselogs() : flush (save) buffer logs and access logs
                   14175: 
                   14176: =item *
                   14177: 
                   14178: courselog($what) : save message for course in hash
                   14179: 
                   14180: =item *
                   14181: 
                   14182: courseacclog($what) : save message for course using &courselog().  Perform
                   14183: special processing for specific resource types (problems, exams, quizzes, etc).
                   14184: 
1.191     harris41 14185: =item *
                   14186: 
                   14187: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14188: as a PerlChildExitHandler
1.243     albertel 14189: 
                   14190: =back
                   14191: 
                   14192: =head2 Other
                   14193: 
                   14194: =over 4
                   14195: 
                   14196: =item *
                   14197: 
                   14198: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14199: 
                   14200: =back
                   14201: 
                   14202: =cut
1.877     foxr     14203: 

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