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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1299  ! raeburn     4: # $Id: lonnet.pm,v 1.1298 2016/01/26 20:17:53 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1182    foxr       78: 
1.1173    foxr       79: use Encode;
                     80: 
1.1245    raeburn    81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     83:             %managerstab);
1.871     albertel   84: 
                     85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        88:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        89: 
1.1       albertel   90: use IO::Socket;
1.31      www        91: use GDBM_File;
1.208     albertel   92: use HTML::LCParser;
1.88      www        93: use Fcntl qw(:flock);
1.870     albertel   94: use Storable qw(thaw nfreeze);
1.1289    damieng    95: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   96: use Cache::Memcached;
1.676     albertel   97: use Digest::MD5;
1.790     albertel   98: use Math::Random;
1.1024    raeburn    99: use File::MMagic;
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1167    droeschl  103: use LONCAPA::Lond;
1.1117    foxr      104: 
1.1090    raeburn   105: use File::Copy;
1.676     albertel  106: 
1.195     www       107: my $readit;
1.1288    damieng   108: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  109: 
1.619     albertel  110: require Exporter;
                    111: 
                    112: our @ISA = qw (Exporter);
                    113: our @EXPORT = qw(%env);
                    114: 
1.449     matthew   115: 
1.1187    raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1187    raeburn   119:     sub write_log {
1.1188    raeburn   120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1184    raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   130:         my $logentry = { 
                    131:                           $id => {
                    132:                                    'exe_uname' => $env{'user.name'},
                    133:                                    'exe_udom'  => $env{'user.domain'},
                    134:                                    'exe_time'  => $now,
                    135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    136:                                    'delflag'   => $delflag,
                    137:                                    'logentry'  => $storehash,
                    138:                                    'uname'     => $uname,
                    139:                                    'udom'      => $udom,
                    140:                                   }
                    141:                        };
                    142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       143:     }
                    144: }
1.1       albertel  145: 
1.163     harris41  146: sub logtouch {
                    147:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  148:     unless (-e "$execdir/logs/lonnet.log") {	
                    149: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  150: 	close $fh;
                    151:     }
                    152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    154: }
                    155: 
1.1       albertel  156: sub logthis {
                    157:     my $message=shift;
                    158:     my $execdir=$perlvar{'lonDaemons'};
                    159:     my $now=time;
                    160:     my $local=localtime($now);
1.448     albertel  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    163: 	print $fh $logstring;
1.448     albertel  164: 	close($fh);
                    165:     }
1.1       albertel  166:     return 1;
                    167: }
                    168: 
                    169: sub logperm {
                    170:     my $message=shift;
                    171:     my $execdir=$perlvar{'lonDaemons'};
                    172:     my $now=time;
                    173:     my $local=localtime($now);
1.448     albertel  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    175: 	print $fh "$now:$message:$local\n";
                    176: 	close($fh);
                    177:     }
1.1       albertel  178:     return 1;
                    179: }
                    180: 
1.850     albertel  181: sub create_connection {
1.853     albertel  182:     my ($hostname,$lonid) = @_;
1.851     albertel  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  184: 				     Type    => SOCK_STREAM,
                    185: 				     Timeout => 10);
                    186:     return 0 if (!$client);
1.890     albertel  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  188:     my $result = <$client>;
                    189:     chomp($result);
                    190:     return 1 if ($result eq 'done');
                    191:     return 0;
                    192: }
                    193: 
1.983     raeburn   194: sub get_server_timezone {
                    195:     my ($cnum,$cdom) = @_;
                    196:     my $home=&homeserver($cnum,$cdom);
                    197:     if ($home ne 'no_host') {
                    198:         my $cachetime = 24*3600;
                    199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    200:         if (defined($cached)) {
                    201:             return $timezone;
                    202:         } else {
                    203:             my $timezone = &reply('servertimezone',$home);
                    204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    205:         }
                    206:     }
                    207: }
1.850     albertel  208: 
1.1106    raeburn   209: sub get_server_distarch {
                    210:     my ($lonhost,$ignore_cache) = @_;
                    211:     if (defined($lonhost)) {
                    212:         if (!defined(&hostname($lonhost))) {
                    213:             return;
                    214:         }
                    215:         my $cachetime = 12*3600;
                    216:         if (!$ignore_cache) {
                    217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    218:             if (defined($cached)) {
                    219:                 return $distarch;
                    220:             }
                    221:         }
                    222:         my $rep = &reply('serverdistarch',$lonhost);
                    223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    225:                 $rep eq '') {
                    226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    227:         }
                    228:     }
                    229:     return;
                    230: }
                    231: 
1.993     raeburn   232: sub get_server_loncaparev {
1.1073    raeburn   233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   234:     if (defined($lonhost)) {
                    235:         if (!defined(&hostname($lonhost))) {
                    236:             undef($lonhost);
                    237:         }
                    238:     }
                    239:     if (!defined($lonhost)) {
                    240:         if (defined(&domain($dom,'primary'))) {
                    241:             $lonhost=&domain($dom,'primary');
                    242:             if ($lonhost eq 'no_host') {
                    243:                 undef($lonhost);
                    244:             }
                    245:         }
                    246:     }
                    247:     if (defined($lonhost)) {
1.1073    raeburn   248:         my $cachetime = 12*3600;
                    249:         if (!$ignore_cache) {
                    250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    251:             if (defined($cached)) {
                    252:                 return $loncaparev;
                    253:             }
                    254:         }
                    255:         my ($answer,$loncaparev);
                    256:         my @ids=&current_machine_ids();
                    257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    258:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   260:                 $loncaparev = $1;
                    261:             }
                    262:         } else {
                    263:             $answer = &reply('serverloncaparev',$lonhost);
                    264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    265:                 if ($caller eq 'loncron') {
                    266:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   267:                     $ua->timeout(4);
1.1073    raeburn   268:                     my $protocol = $protocol{$lonhost};
                    269:                     $protocol = 'http' if ($protocol ne 'https');
                    270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    271:                     my $request=new HTTP::Request('GET',$url);
                    272:                     my $response=$ua->request($request);
                    273:                     unless ($response->is_error()) {
                    274:                         my $content = $response->content;
1.1081    raeburn   275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   276:                             $loncaparev = $1;
                    277:                         }
                    278:                     }
                    279:                 } else {
                    280:                     $loncaparev = $loncaparevs{$lonhost};
                    281:                 }
1.1081    raeburn   282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   283:                 $loncaparev = $1;
                    284:             }
1.993     raeburn   285:         }
1.1073    raeburn   286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   287:     }
                    288: }
                    289: 
1.1074    raeburn   290: sub get_server_homeID {
                    291:     my ($hostname,$ignore_cache,$caller) = @_;
                    292:     unless ($ignore_cache) {
                    293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    294:         if (defined($cached)) {
                    295:             return $serverhomeID;
                    296:         }
                    297:     }
                    298:     my $cachetime = 12*3600;
                    299:     my $serverhomeID;
                    300:     if ($caller eq 'loncron') { 
                    301:         my @machine_ids = &machine_ids($hostname);
                    302:         foreach my $id (@machine_ids) {
                    303:             my $response = &reply('serverhomeID',$id);
                    304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    305:                 $serverhomeID = $response;
                    306:                 last;
                    307:             }
                    308:         }
                    309:         if ($serverhomeID eq '') {
                    310:             $serverhomeID = $machine_ids[-1];
                    311:         }
                    312:     } else {
                    313:         $serverhomeID = $serverhomeIDs{$hostname};
                    314:     }
                    315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    316: }
                    317: 
1.1121    raeburn   318: sub get_remote_globals {
                    319:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   320:     my ($result,%returnhash,%whatneeded);
                    321:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   322:         foreach my $what (sort(keys(%{$whathash}))) {
                    323:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   324:             my ($response,$cached);
1.1121    raeburn   325:             unless ($ignore_cache) {
1.1125    raeburn   326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   327:             }
                    328:             if (defined($cached)) {
1.1125    raeburn   329:                 $returnhash{$what} = $response;
1.1121    raeburn   330:             } else {
1.1125    raeburn   331:                 $whatneeded{$what} = 1;
1.1121    raeburn   332:             }
                    333:         }
1.1125    raeburn   334:         if (keys(%whatneeded) == 0) {
                    335:             $result = 'ok';
                    336:         } else {
1.1121    raeburn   337:             my $requested = &freeze_escape(\%whatneeded);
                    338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    340:                 ($rep eq 'unknown_cmd')) {
                    341:                 $result = $rep;
                    342:             } else {
                    343:                 $result = 'ok';
1.1121    raeburn   344:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   345:                 foreach my $item (@pairs) {
                    346:                     my ($key,$value)=split(/=/,$item,2);
                    347:                     my $what = &unescape($key);
                    348:                     my $hashid = $lonhost.'-'.$what;
                    349:                     $returnhash{$what}=&thaw_unescape($value);
                    350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   351:                 }
                    352:             }
                    353:         }
                    354:     }
1.1125    raeburn   355:     return ($result,\%returnhash);
1.1121    raeburn   356: }
                    357: 
1.1124    raeburn   358: sub remote_devalidate_cache {
1.1241    raeburn   359:     my ($lonhost,$cachekeys) = @_;
                    360:     my $items;
                    361:     return unless (ref($cachekeys) eq 'ARRAY');
                    362:     my $cachestr = join('&',@{$cachekeys});
                    363:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   364:     return $response;
                    365: }
                    366: 
1.1       albertel  367: # -------------------------------------------------- Non-critical communication
                    368: sub subreply {
                    369:     my ($cmd,$server)=@_;
1.838     albertel  370:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      371:     #
                    372:     #  With loncnew process trimming, there's a timing hole between lonc server
                    373:     #  process exit and the master server picking up the listen on the AF_UNIX
                    374:     #  socket.  In that time interval, a lock file will exist:
                    375: 
                    376:     my $lockfile=$peerfile.".lock";
                    377:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   378: 	sleep(0.1);
1.549     foxr      379:     }
                    380:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      381:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      382:     #
1.550     foxr      383:     #   We'll give the connection a few tries before abandoning it.  If
                    384:     #   connection is not possible, we'll con_lost back to the client.
                    385:     #   
                    386:     my $client;
                    387:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    388: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    389: 				      Type    => SOCK_STREAM,
                    390: 				      Timeout => 10);
1.869     albertel  391: 	if ($client) {
1.550     foxr      392: 	    last;		# Connected!
1.850     albertel  393: 	} else {
1.853     albertel  394: 	    &create_connection(&hostname($server),$server);
1.550     foxr      395: 	}
1.1289    damieng   396:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      397:     }
                    398:     my $answer;
                    399:     if ($client) {
1.704     albertel  400: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      401: 	$answer=<$client>;
                    402: 	if (!$answer) { $answer="con_lost"; }
                    403: 	chomp($answer);
                    404:     } else {
                    405: 	$answer = 'con_lost';	# Failed connection.
                    406:     }
1.1       albertel  407:     return $answer;
                    408: }
                    409: 
                    410: sub reply {
                    411:     my ($cmd,$server)=@_;
1.838     albertel  412:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  413:     my $answer=subreply($cmd,$server);
1.65      www       414:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  415:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       416:                 " $cmd to $server returned $answer</font>");
                    417:     }
1.1       albertel  418:     return $answer;
                    419: }
                    420: 
                    421: # ----------------------------------------------------------- Send USR1 to lonc
                    422: 
                    423: sub reconlonc {
1.891     albertel  424:     my ($lonid) = @_;
                    425:     if ($lonid) {
1.1295    raeburn   426:         my $hostname = &hostname($lonid);
1.891     albertel  427: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    428: 	if ($hostname && -e $peerfile) {
                    429: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    430: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    431: 					     Type    => SOCK_STREAM,
                    432: 					     Timeout => 10);
                    433: 	    if ($client) {
                    434: 		print $client ("reset_retries\n");
                    435: 		my $answer=<$client>;
                    436: 		#reset just this one.
                    437: 	    }
                    438: 	}
                    439: 	return;
                    440:     }
                    441: 
1.836     www       442:     &logthis("Trying to reconnect lonc");
1.1       albertel  443:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  444:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  445: 	my $loncpid=<$fh>;
                    446:         chomp($loncpid);
                    447:         if (kill 0 => $loncpid) {
                    448: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    449:             kill USR1 => $loncpid;
                    450:             sleep 1;
1.1295    raeburn   451:         } else {
1.12      www       452: 	    &logthis(
1.672     albertel  453:                "<font color=\"blue\">WARNING:".
1.12      www       454:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  455:         }
                    456:     } else {
1.836     www       457: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  458:     }
                    459: }
                    460: 
                    461: # ------------------------------------------------------ Critical communication
1.12      www       462: 
1.1       albertel  463: sub critical {
                    464:     my ($cmd,$server)=@_;
1.838     albertel  465:     unless (&hostname($server)) {
1.672     albertel  466:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       467:                " Critical message to unknown server ($server)</font>");
                    468:         return 'no_such_host';
                    469:     }
1.1       albertel  470:     my $answer=reply($cmd,$server);
                    471:     if ($answer eq 'con_lost') {
1.1295    raeburn   472: 	&reconlonc($server);
1.589     albertel  473: 	my $answer=reply($cmd,$server);
1.1       albertel  474:         if ($answer eq 'con_lost') {
                    475:             my $now=time;
                    476:             my $middlename=$cmd;
1.5       www       477:             $middlename=substr($middlename,0,16);
1.1       albertel  478:             $middlename=~s/\W//g;
                    479:             my $dfilename=
1.305     www       480:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    481:             $dumpcount++;
1.1       albertel  482:             {
1.448     albertel  483: 		my $dfh;
                    484: 		if (open($dfh,">$dfilename")) {
                    485: 		    print $dfh "$cmd\n"; 
                    486: 		    close($dfh);
                    487: 		}
1.1       albertel  488:             }
1.1288    damieng   489:             sleep 1;
1.1       albertel  490:             my $wcmd='';
                    491:             {
1.448     albertel  492: 		my $dfh;
                    493: 		if (open($dfh,"<$dfilename")) {
                    494: 		    $wcmd=<$dfh>; 
                    495: 		    close($dfh);
                    496: 		}
1.1       albertel  497:             }
                    498:             chomp($wcmd);
1.7       www       499:             if ($wcmd eq $cmd) {
1.672     albertel  500: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       501:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  502:                 &logperm("D:$server:$cmd");
                    503: 	        return 'con_delayed';
                    504:             } else {
1.672     albertel  505:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       506:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  507:                 &logperm("F:$server:$cmd");
                    508:                 return 'con_failed';
                    509:             }
                    510:         }
                    511:     }
                    512:     return $answer;
1.405     albertel  513: }
                    514: 
1.755     albertel  515: # ------------------------------------------- check if return value is an error
                    516: 
                    517: sub error {
                    518:     my ($result) = @_;
1.756     albertel  519:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  520: 	if ($2 == 2) { return undef; }
                    521: 	return $1;
                    522:     }
                    523:     return undef;
                    524: }
                    525: 
1.783     albertel  526: sub convert_and_load_session_env {
                    527:     my ($lonidsdir,$handle)=@_;
                    528:     my @profile;
                    529:     {
1.917     albertel  530: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    531: 	if (!$opened) {
1.915     albertel  532: 	    return 0;
                    533: 	}
1.783     albertel  534: 	flock($idf,LOCK_SH);
                    535: 	@profile=<$idf>;
                    536: 	close($idf);
                    537:     }
                    538:     my %temp_env;
                    539:     foreach my $line (@profile) {
1.786     albertel  540: 	if ($line !~ m/=/) {
                    541: 	    return 0;
                    542: 	}
1.783     albertel  543: 	chomp($line);
                    544: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    545: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    546:     }
                    547:     unlink("$lonidsdir/$handle.id");
                    548:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    549: 	    0640)) {
                    550: 	%disk_env = %temp_env;
                    551: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    552: 	untie(%disk_env);
                    553:     }
1.786     albertel  554:     return 1;
1.783     albertel  555: }
                    556: 
1.374     www       557: # ------------------------------------------- Transfer profile into environment
1.780     albertel  558: my $env_loaded;
                    559: sub transfer_profile_to_env {
1.788     albertel  560:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    561:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       562: 
1.720     albertel  563:     if (!defined($lonidsdir)) {
                    564: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    565:     }
                    566:     if (!defined($handle)) {
                    567:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    568:     }
                    569: 
1.786     albertel  570:     my $convert;
                    571:     {
1.917     albertel  572:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    573: 	if (!$opened) {
1.915     albertel  574: 	    return;
                    575: 	}
1.786     albertel  576: 	flock($idf,LOCK_SH);
                    577: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    578: 		&GDBM_READER(),0640)) {
                    579: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    580: 	    untie(%disk_env);
                    581: 	} else {
                    582: 	    $convert = 1;
                    583: 	}
                    584:     }
                    585:     if ($convert) {
                    586: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    587: 	    &logthis("Failed to load session, or convert session.");
                    588: 	}
1.374     www       589:     }
1.783     albertel  590: 
1.786     albertel  591:     my %remove;
1.783     albertel  592:     while ( my $envname = each(%env) ) {
1.433     matthew   593:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    594:             if ($time < time-300) {
1.783     albertel  595:                 $remove{$key}++;
1.433     matthew   596:             }
                    597:         }
                    598:     }
1.783     albertel  599: 
1.619     albertel  600:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  601:     $env_loaded=1;
1.783     albertel  602:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   603:         &delenv($expired_key);
1.374     www       604:     }
1.1       albertel  605: }
                    606: 
1.916     albertel  607: # ---------------------------------------------------- Check for valid session 
                    608: sub check_for_valid_session {
1.1245    raeburn   609:     my ($r,$name,$userhashref) = @_;
1.916     albertel  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   611:     if ($name eq '') {
                    612:         $name = 'lonID';
                    613:     }
                    614:     my $lonid=$cookies{$name};
1.916     albertel  615:     return undef if (!$lonid);
                    616: 
                    617:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   618:     my $lonidsdir;
                    619:     if ($name eq 'lonDAV') {
                    620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    621:     } else {
                    622:         $lonidsdir=$r->dir_config('lonIDsDir');
                    623:     }
1.916     albertel  624:     return undef if (!-e "$lonidsdir/$handle.id");
                    625: 
1.917     albertel  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    627:     return undef if (!$opened);
1.916     albertel  628: 
                    629:     flock($idf,LOCK_SH);
                    630:     my %disk_env;
                    631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    632: 	    &GDBM_READER(),0640)) {
                    633: 	return undef;	
                    634:     }
                    635: 
                    636:     if (!defined($disk_env{'user.name'})
                    637: 	|| !defined($disk_env{'user.domain'})) {
                    638: 	return undef;
                    639:     }
1.1245    raeburn   640: 
                    641:     if (ref($userhashref) eq 'HASH') {
                    642:         $userhashref->{'name'} = $disk_env{'user.name'};
                    643:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212    raeburn   644:     }
1.1245    raeburn   645: 
1.916     albertel  646:     return $handle;
                    647: }
                    648: 
1.830     albertel  649: sub timed_flock {
                    650:     my ($file,$lock_type) = @_;
                    651:     my $failed=0;
                    652:     eval {
                    653: 	local $SIG{__DIE__}='DEFAULT';
                    654: 	local $SIG{ALRM}=sub {
                    655: 	    $failed=1;
                    656: 	    die("failed lock");
                    657: 	};
                    658: 	alarm(13);
                    659: 	flock($file,$lock_type);
                    660: 	alarm(0);
                    661:     };
                    662:     if ($failed) {
                    663: 	return undef;
                    664:     } else {
                    665: 	return 1;
                    666:     }
                    667: }
                    668: 
1.5       www       669: # ---------------------------------------------------------- Append Environment
                    670: 
                    671: sub appenv {
1.949     raeburn   672:     my ($newenv,$roles) = @_;
                    673:     if (ref($newenv) eq 'HASH') {
                    674:         foreach my $key (keys(%{$newenv})) {
                    675:             my $refused = 0;
                    676: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    677:                 $refused = 1;
                    678:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   679:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   680:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    681:                         $refused = 0;
                    682:                     }
                    683:                 }
                    684:             }
                    685:             if ($refused) {
                    686:                 &logthis("<font color=\"blue\">WARNING: ".
                    687:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    688:                          .'</font>');
                    689: 	        delete($newenv->{$key});
                    690:             } else {
                    691:                 $env{$key}=$newenv->{$key};
                    692:             }
                    693:         }
                    694:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    695:         if ($opened
                    696: 	    && &timed_flock($env_file,LOCK_EX)
                    697: 	    &&
                    698: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    699: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    700: 	    while (my ($key,$value) = each(%{$newenv})) {
                    701: 	        $disk_env{$key} = $value;
                    702: 	    }
                    703: 	    untie(%disk_env);
1.35      www       704:         }
1.191     harris41  705:     }
1.56      www       706:     return 'ok';
                    707: }
                    708: # ----------------------------------------------------- Delete from Environment
                    709: 
                    710: sub delenv {
1.1104    raeburn   711:     my ($delthis,$regexp,$roles) = @_;
                    712:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    713:         my $refused = 1;
                    714:         if (ref($roles) eq 'ARRAY') {
                    715:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    716:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    717:                 $refused = 0;
                    718:             }
                    719:         }
                    720:         if ($refused) {
                    721:             &logthis("<font color=\"blue\">WARNING: ".
                    722:                      "Attempt to delete from environment ".$delthis);
                    723:             return 'error';
                    724:         }
1.56      www       725:     }
1.917     albertel  726:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    727:     if ($opened
1.915     albertel  728: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  729: 	&&
                    730: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    731: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  732: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   733: 	    if ($regexp) {
                    734:                 if ($key=~/^$delthis/) {
                    735:                     delete($env{$key});
                    736:                     delete($disk_env{$key});
                    737:                 } 
                    738:             } else {
                    739:                 if ($key=~/^\Q$delthis\E/) {
                    740: 		    delete($env{$key});
                    741: 		    delete($disk_env{$key});
                    742: 	        }
                    743:             }
1.448     albertel  744: 	}
1.783     albertel  745: 	untie(%disk_env);
1.5       www       746:     }
                    747:     return 'ok';
1.369     albertel  748: }
                    749: 
1.790     albertel  750: sub get_env_multiple {
                    751:     my ($name) = @_;
                    752:     my @values;
                    753:     if (defined($env{$name})) {
                    754:         # exists is it an array
                    755:         if (ref($env{$name})) {
                    756:             @values=@{ $env{$name} };
                    757:         } else {
                    758:             $values[0]=$env{$name};
                    759:         }
                    760:     }
                    761:     return(@values);
                    762: }
                    763: 
1.958     www       764: # ------------------------------------------------------------------- Locking
                    765: 
                    766: sub set_lock {
                    767:     my ($text)=@_;
                    768:     $locknum++;
                    769:     my $id=$$.'-'.$locknum;
                    770:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    771:              'session.lock.'.$id => $text});
                    772:     return $id;
                    773: }
                    774: 
                    775: sub get_locks {
                    776:     my $num=0;
                    777:     my %texts=();
                    778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    779:        if ($lock=~/\w/) {
                    780:           $num++;
                    781:           $texts{$lock}=$env{'session.lock.'.$lock};
                    782:        }
                    783:    }
                    784:    return ($num,%texts);
                    785: }
                    786: 
                    787: sub remove_lock {
                    788:     my ($id)=@_;
                    789:     my $newlocks='';
                    790:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    791:        if (($lock=~/\w/) && ($lock ne $id)) {
                    792:           $newlocks.=','.$lock;
                    793:        }
                    794:     }
                    795:     &appenv({'session.locks' => $newlocks});
                    796:     &delenv('session.lock.'.$id);
                    797: }
                    798: 
                    799: sub remove_all_locks {
                    800:     my $activelocks=$env{'session.locks'};
                    801:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    802:        if ($lock=~/\w/) {
                    803:           &remove_lock($lock);
                    804:        }
                    805:     }
                    806: }
                    807: 
                    808: 
1.369     albertel  809: # ------------------------------------------ Find out current server userload
                    810: sub userload {
                    811:     my $numusers=0;
                    812:     {
                    813: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    814: 	my $filename;
                    815: 	my $curtime=time;
                    816: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  817: 	    next if ($filename eq '.' || $filename eq '..');
                    818: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  819: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  820: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  821: 	}
                    822: 	closedir(LONIDS);
                    823:     }
                    824:     my $userloadpercent=0;
                    825:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    826:     if ($maxuserload) {
1.371     albertel  827: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  828:     }
1.372     albertel  829:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  830:     return $userloadpercent;
1.283     www       831: }
                    832: 
1.1       albertel  833: # ------------------------------ Find server with least workload from spare.tab
1.11      www       834: 
1.1       albertel  835: sub spareserver {
1.1083    raeburn   836:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  837:     my $spare_server;
1.370     albertel  838:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  839:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    840:                                                      :  $userloadpercent;
1.1083    raeburn   841:     my ($uint_dom,$remotesessions);
                    842:     if (($udom ne '') && (&domain($udom) ne '')) {
                    843:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    844:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    845:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    846:         $remotesessions = $udomdefaults{'remotesessions'};
                    847:     }
1.1123    raeburn   848:     my $spareshash = &this_host_spares($udom);
                    849:     if (ref($spareshash) eq 'HASH') {
                    850:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    851:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   852:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    853:                                              $try_server));
1.1123    raeburn   854: 	        ($spare_server, $lowest_load) =
                    855: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    856:             }
1.1083    raeburn   857:         }
1.784     albertel  858: 
1.1123    raeburn   859:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    860: 
                    861:         if (!$found_server) {
                    862:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    863: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   864:                     next unless (&spare_can_host($udom,$uint_dom,
                    865:                                                  $remotesessions,$try_server));
1.1123    raeburn   866: 	            ($spare_server, $lowest_load) =
                    867: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    868:                 }
                    869: 	    }
                    870:         }
1.784     albertel  871:     }
                    872: 
                    873:     if (!$want_server_name) {
1.968     raeburn   874:         my $protocol = 'http';
                    875:         if ($protocol{$spare_server} eq 'https') {
                    876:             $protocol = $protocol{$spare_server};
                    877:         }
1.1001    raeburn   878:         if (defined($spare_server)) {
                    879:             my $hostname = &hostname($spare_server);
1.1083    raeburn   880:             if (defined($hostname)) {
1.1001    raeburn   881: 	        $spare_server = $protocol.'://'.$hostname;
                    882:             }
                    883:         }
1.784     albertel  884:     }
                    885:     return $spare_server;
                    886: }
                    887: 
                    888: sub compare_server_load {
1.1253    raeburn   889:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    890: 
                    891:     if ($required) {
                    892:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    893:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    894:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    895:         if (($major eq '' && $minor eq '') ||
                    896:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    897:             return ($spare_server,$lowest_load);
                    898:         }
                    899:     }
1.784     albertel  900: 
                    901:     my $loadans     = &reply('load',    $try_server);
                    902:     my $userloadans = &reply('userload',$try_server);
                    903: 
                    904:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   905: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  906:     }
                    907: 
                    908:     my $load;
                    909:     if ($loadans =~ /\d/) {
                    910: 	if ($userloadans =~ /\d/) {
                    911: 	    #both are numbers, pick the bigger one
                    912: 	    $load = ($loadans > $userloadans) ? $loadans 
                    913: 		                              : $userloadans;
1.411     albertel  914: 	} else {
1.784     albertel  915: 	    $load = $loadans;
1.411     albertel  916: 	}
1.784     albertel  917:     } else {
                    918: 	$load = $userloadans;
                    919:     }
                    920: 
                    921:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    922: 	$spare_server = $try_server;
                    923: 	$lowest_load  = $load;
1.370     albertel  924:     }
1.784     albertel  925:     return ($spare_server,$lowest_load);
1.202     matthew   926: }
1.914     albertel  927: 
                    928: # --------------------------- ask offload servers if user already has a session
                    929: sub find_existing_session {
                    930:     my ($udom,$uname) = @_;
1.1123    raeburn   931:     my $spareshash = &this_host_spares($udom);
                    932:     if (ref($spareshash) eq 'HASH') {
                    933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    936:             }
                    937:         }
                    938:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    939:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    940:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    941:             }
                    942:         }
1.914     albertel  943:     }
                    944:     return;
                    945: }
                    946: 
                    947: # -------------------------------- ask if server already has a session for user
                    948: sub has_user_session {
                    949:     my ($lonid,$udom,$uname) = @_;
                    950:     my $result = &reply(join(':','userhassession',
                    951: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    952:     return 1 if ($result eq 'ok');
                    953: 
                    954:     return 0;
                    955: }
                    956: 
1.1076    raeburn   957: # --------- determine least loaded server in a user's domain which allows login
                    958: 
                    959: sub choose_server {
1.1259    raeburn   960:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   961:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   962:     my %servers = &get_servers($udom);
1.1076    raeburn   963:     my $lowest_load = 30000;
1.1259    raeburn   964:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    965:     if ($skiploadbal) {
                    966:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    967:         unless (defined($cached)) {
                    968:             my $cachetime = 60*60*24;
                    969:             my %domconfig =
                    970:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    971:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    972:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    973:                                            $cachetime);
                    974:             }
                    975:         }
                    976:     }
1.1076    raeburn   977:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn   978:         if ($skiploadbal) {
                    979:             if (ref($balancers) eq 'HASH') {
                    980:                 next if (exists($balancers->{$lonhost}));
                    981:             }
                    982:         }   
1.1115    raeburn   983:         my $loginvia;
                    984:         if ($checkloginvia) {
                    985:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   986:             if ($loginvia) {
                    987:                 my ($server,$path) = split(/:/,$loginvia);
                    988:                 ($login_host, $lowest_load) =
1.1253    raeburn   989:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   990:                 if ($login_host eq $server) {
                    991:                     $portal_path = $path;
1.1151    raeburn   992:                     $isredirect = 1;
1.1116    raeburn   993:                 }
                    994:             } else {
                    995:                 ($login_host, $lowest_load) =
1.1253    raeburn   996:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn   997:                 if ($login_host eq $lonhost) {
                    998:                     $portal_path = '';
1.1151    raeburn   999:                     $isredirect = ''; 
1.1116    raeburn  1000:                 }
                   1001:             }
                   1002:         } else {
1.1076    raeburn  1003:             ($login_host, $lowest_load) =
1.1253    raeburn  1004:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1005:         }
                   1006:     }
                   1007:     if ($login_host ne '') {
1.1116    raeburn  1008:         $hostname = &hostname($login_host);
1.1076    raeburn  1009:     }
1.1151    raeburn  1010:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn  1011: }
                   1012: 
1.202     matthew  1013: # --------------------------------------------- Try to change a user's password
                   1014: 
                   1015: sub changepass {
1.799     raeburn  1016:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1017:     $currentpass = &escape($currentpass);
                   1018:     $newpass     = &escape($newpass);
1.1030    raeburn  1019:     my $lonhost = $perlvar{'lonHostID'};
                   1020:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1021: 		       $server);
                   1022:     if (! $answer) {
                   1023: 	&logthis("No reply on password change request to $server ".
                   1024: 		 "by $uname in domain $udom.");
                   1025:     } elsif ($answer =~ "^ok") {
                   1026:         &logthis("$uname in $udom successfully changed their password ".
                   1027: 		 "on $server.");
                   1028:     } elsif ($answer =~ "^pwchange_failure") {
                   1029: 	&logthis("$uname in $udom was unable to change their password ".
                   1030: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1031: 		 "or pwchange");
                   1032:     } elsif ($answer =~ "^non_authorized") {
                   1033:         &logthis("$uname in $udom did not get their password correct when ".
                   1034: 		 "attempting to change it on $server.");
                   1035:     } elsif ($answer =~ "^auth_mode_error") {
                   1036:         &logthis("$uname in $udom attempted to change their password despite ".
                   1037: 		 "not being locally or internally authenticated on $server.");
                   1038:     } elsif ($answer =~ "^unknown_user") {
                   1039:         &logthis("$uname in $udom attempted to change their password ".
                   1040: 		 "on $server but were unable to because $server is not ".
                   1041: 		 "their home server.");
                   1042:     } elsif ($answer =~ "^refused") {
                   1043: 	&logthis("$server refused to change $uname in $udom password because ".
                   1044: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1045:     } elsif ($answer =~ "invalid_client") {
                   1046:         &logthis("$server refused to change $uname in $udom password because ".
                   1047:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1048:     }
                   1049:     return $answer;
1.1       albertel 1050: }
                   1051: 
1.169     harris41 1052: # ----------------------- Try to determine user's current authentication scheme
                   1053: 
                   1054: sub queryauthenticate {
                   1055:     my ($uname,$udom)=@_;
1.456     albertel 1056:     my $uhome=&homeserver($uname,$udom);
                   1057:     if (!$uhome) {
                   1058: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1059: 	return 'no_host';
                   1060:     }
                   1061:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1062:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1063: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1064:     }
1.456     albertel 1065:     return $answer;
1.169     harris41 1066: }
                   1067: 
1.1       albertel 1068: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1069: 
1.1       albertel 1070: sub authenticate {
1.1073    raeburn  1071:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1072:     $upass=&escape($upass);
                   1073:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1074:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1075:     my $newhome;
1.836     www      1076:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1077: # Maybe the machine was offline and only re-appeared again recently?
                   1078:         &reconlonc();
                   1079: # One more
1.952     raeburn  1080: 	$uhome=&homeserver($uname,$udom,1);
                   1081:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1082:             if (defined(&domain($udom,'primary'))) {
                   1083:                 $newhome=&domain($udom,'primary');
                   1084:             }
                   1085:             if ($newhome ne '') {
                   1086:                 $uhome = $newhome;
                   1087:             }
                   1088:         }
1.836     www      1089: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1090: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1091: 	    return 'no_host';
                   1092:         }
1.1       albertel 1093:     }
1.1073    raeburn  1094:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1095:     if ($answer eq 'authorized') {
1.952     raeburn  1096:         if ($newhome) {
                   1097:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1098:             return 'no_account_on_host'; 
                   1099:         } else {
                   1100:             &logthis("User $uname at $udom authorized by $uhome");
                   1101:             return $uhome;
                   1102:         }
1.471     albertel 1103:     }
                   1104:     if ($answer eq 'non_authorized') {
                   1105: 	&logthis("User $uname at $udom rejected by $uhome");
                   1106: 	return 'no_host'; 
1.9       www      1107:     }
1.471     albertel 1108:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1109:     return 'no_host';
                   1110: }
                   1111: 
1.1073    raeburn  1112: sub can_host_session {
1.1074    raeburn  1113:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1114:     my $canhost = 1;
1.1074    raeburn  1115:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1116:     if (ref($remotesessions) eq 'HASH') {
                   1117:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1118:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1119:                 $canhost = 0;
                   1120:             } else {
                   1121:                 $canhost = 1;
                   1122:             }
                   1123:         }
                   1124:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1125:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1126:                 $canhost = 1;
                   1127:             } else {
                   1128:                 $canhost = 0;
                   1129:             }
                   1130:         }
                   1131:         if ($canhost) {
                   1132:             if ($remotesessions->{'version'} ne '') {
                   1133:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1134:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1135:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1136:                         my $major = $1;
                   1137:                         my $minor = $2;
                   1138:                         if (($major < $reqmajor ) ||
                   1139:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1140:                             $canhost = 0;
                   1141:                         }
                   1142:                     } else {
                   1143:                         $canhost = 0;
                   1144:                     }
                   1145:                 }
                   1146:             }
                   1147:         }
                   1148:     }
                   1149:     if ($canhost) {
                   1150:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1151:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1152:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1153:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1154:                 if (($uint_dom ne '') && 
                   1155:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1156:                     $canhost = 0;
                   1157:                 } else {
                   1158:                     $canhost = 1;
                   1159:                 }
                   1160:             }
                   1161:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1162:                 if (($uint_dom ne '') && 
                   1163:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1164:                     $canhost = 1;
                   1165:                 } else {
                   1166:                     $canhost = 0;
                   1167:                 }
                   1168:             }
                   1169:         }
                   1170:     }
                   1171:     return $canhost;
                   1172: }
                   1173: 
1.1083    raeburn  1174: sub spare_can_host {
                   1175:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1176:     my $canhost=1;
1.1279    raeburn  1177:     my $try_server_hostname = &hostname($try_server);
                   1178:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1179:     my $serverhomedom = &host_domain($serverhomeID);
                   1180:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1181:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1182:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1183:             $canhost = 0;
                   1184:         }
                   1185:     }
                   1186:     if (($canhost) && ($uint_dom)) {
                   1187:         my @intdoms;
                   1188:         my $internet_names = &get_internet_names($try_server);
                   1189:         if (ref($internet_names) eq 'ARRAY') {
                   1190:             @intdoms = @{$internet_names};
                   1191:         }
                   1192:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1193:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1194:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1195:                                          $remotesessions,
                   1196:                                          $defdomdefaults{'hostedsessions'});
                   1197:         }
1.1083    raeburn  1198:     }
                   1199:     return $canhost;
                   1200: }
                   1201: 
1.1123    raeburn  1202: sub this_host_spares {
                   1203:     my ($dom) = @_;
1.1126    raeburn  1204:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1205:     my @hosts = &current_machine_ids();
                   1206:     foreach my $lonhost (@hosts) {
                   1207:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1208:             $dom_in_use = $dom;
                   1209:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1210:             last;
                   1211:         }
                   1212:     }
1.1126    raeburn  1213:     if ($dom_in_use ne '') {
                   1214:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1215:     }
                   1216:     if (ref($result) ne 'HASH') {
                   1217:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1218:         $dom_in_use = &host_domain($lonhost_in_use);
                   1219:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1220:         if (ref($result) ne 'HASH') {
                   1221:             $result = \%spareid;
                   1222:         }
                   1223:     }
                   1224:     return $result;
                   1225: }
                   1226: 
                   1227: sub spares_for_offload  {
                   1228:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1229:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1230:     if (defined($cached)) {
                   1231:         return $result;
                   1232:     } else {
1.1126    raeburn  1233:         my $cachetime = 60*60*24;
                   1234:         my %domconfig =
                   1235:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1236:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1237:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1238:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1239:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1240:                 }
                   1241:             }
                   1242:         }
                   1243:     }
1.1126    raeburn  1244:     return;
1.1123    raeburn  1245: }
                   1246: 
1.1129    raeburn  1247: sub get_lonbalancer_config {
                   1248:     my ($servers) = @_;
                   1249:     my ($currbalancer,$currtargets);
                   1250:     if (ref($servers) eq 'HASH') {
                   1251:         foreach my $server (keys(%{$servers})) {
                   1252:             my %what = (
                   1253:                          spareid => 1,
                   1254:                          perlvar => 1,
                   1255:                        );
                   1256:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1257:             if ($result eq 'ok') {
                   1258:                 if (ref($returnhash) eq 'HASH') {
                   1259:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1260:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1261:                             $currbalancer = $server;
                   1262:                             $currtargets = {};
                   1263:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1264:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1265:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1266:                                 }
                   1267:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1268:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1269:                                 }
                   1270:                             }
                   1271:                             last;
                   1272:                         }
                   1273:                     }
                   1274:                 }
                   1275:             }
                   1276:         }
                   1277:     }
                   1278:     return ($currbalancer,$currtargets);
                   1279: }
                   1280: 
                   1281: sub check_loadbalancing {
                   1282:     my ($uname,$udom) = @_;
1.1191    raeburn  1283:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1284:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1285:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1286:     my @hosts = &current_machine_ids();
1.1129    raeburn  1287:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1288:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1289:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1290:     my $serverhomedom = &host_domain($lonhost);
                   1291: 
                   1292:     my $cachetime = 60*60*24;
                   1293: 
                   1294:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1295:         $dom_in_use = $udom;
                   1296:         $homeintdom = 1;
                   1297:     } else {
                   1298:         $dom_in_use = $serverhomedom;
                   1299:     }
                   1300:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1301:     unless (defined($cached)) {
                   1302:         my %domconfig =
                   1303:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1304:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1305:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1306:         }
                   1307:     }
                   1308:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1309:         ($is_balancer,$currtargets,$currrules) = 
                   1310:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1311:         if ($is_balancer) {
                   1312:             if (ref($currrules) eq 'HASH') {
                   1313:                 if ($homeintdom) {
                   1314:                     if ($uname ne '') {
                   1315:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1316:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1317:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1318:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1319:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1320:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1321:                             }
                   1322:                         }
                   1323:                         if ($rule_in_effect eq '') {
                   1324:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1325:                             if ($userenv{'inststatus'} ne '') {
                   1326:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1327:                                 my ($othertitle,$usertypes,$types) =
                   1328:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1329:                                 if (ref($types) eq 'ARRAY') {
                   1330:                                     foreach my $type (@{$types}) {
                   1331:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1332:                                             if (exists($currrules->{$type})) {
                   1333:                                                 $rule_in_effect = $currrules->{$type};
                   1334:                                             }
                   1335:                                         }
                   1336:                                     }
                   1337:                                 }
                   1338:                             } else {
                   1339:                                 if (exists($currrules->{'default'})) {
                   1340:                                     $rule_in_effect = $currrules->{'default'};
                   1341:                                 }
                   1342:                             }
                   1343:                         }
                   1344:                     } else {
                   1345:                         if (exists($currrules->{'default'})) {
                   1346:                             $rule_in_effect = $currrules->{'default'};
                   1347:                         }
                   1348:                     }
                   1349:                 } else {
                   1350:                     if ($currrules->{'_LC_external'} ne '') {
                   1351:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1352:                     }
                   1353:                 }
                   1354:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1355:                                                        $uname,$udom);
                   1356:             }
                   1357:         }
                   1358:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1359:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1360:         unless (defined($cached)) {
                   1361:             my %domconfig =
                   1362:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1363:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1364:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1365:             }
                   1366:         }
                   1367:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1368:             ($is_balancer,$currtargets,$currrules) = 
                   1369:                 &check_balancer_result($result,@hosts);
                   1370:             if ($is_balancer) {
1.1129    raeburn  1371:                 if (ref($currrules) eq 'HASH') {
                   1372:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1373:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1374:                     }
                   1375:                 }
                   1376:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1377:                                                        $uname,$udom);
                   1378:             }
                   1379:         } else {
                   1380:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1381:                 $is_balancer = 1;
                   1382:                 $offloadto = &this_host_spares($dom_in_use);
                   1383:             }
                   1384:         }
                   1385:     } else {
                   1386:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1387:             $is_balancer = 1;
                   1388:             $offloadto = &this_host_spares($dom_in_use);
                   1389:         }
                   1390:     }
1.1176    raeburn  1391:     if ($is_balancer) {
                   1392:         my $lowest_load = 30000;
                   1393:         if (ref($offloadto) eq 'HASH') {
                   1394:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1395:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1396:                     ($otherserver,$lowest_load) =
                   1397:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1398:                 }
1.1129    raeburn  1399:             }
1.1176    raeburn  1400:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1401: 
1.1176    raeburn  1402:             if (!$found_server) {
                   1403:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1404:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1405:                         ($otherserver,$lowest_load) =
                   1406:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1407:                     }
                   1408:                 }
                   1409:             }
                   1410:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1411:             if (@{$offloadto} == 1) {
                   1412:                 $otherserver = $offloadto->[0];
                   1413:             } elsif (@{$offloadto} > 1) {
                   1414:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1415:                     ($otherserver,$lowest_load) =
                   1416:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1417:                 }
                   1418:             }
                   1419:         }
1.1176    raeburn  1420:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1421:             $is_balancer = 0;
                   1422:             if ($uname ne '' && $udom ne '') {
                   1423:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1424:                     
                   1425:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1426:                              'user.loadbalcheck.time' => time});
                   1427:                 }
1.1129    raeburn  1428:             }
                   1429:         }
                   1430:     }
                   1431:     return ($is_balancer,$otherserver);
                   1432: }
                   1433: 
1.1191    raeburn  1434: sub check_balancer_result {
                   1435:     my ($result,@hosts) = @_;
                   1436:     my ($is_balancer,$currtargets,$currrules);
                   1437:     if (ref($result) eq 'HASH') {
                   1438:         if ($result->{'lonhost'} ne '') {
                   1439:             my $currbalancer = $result->{'lonhost'};
                   1440:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1441:                 $is_balancer = 1;
                   1442:                 $currtargets = $result->{'targets'};
                   1443:                 $currrules = $result->{'rules'};
                   1444:             }
                   1445:         } else {
                   1446:             foreach my $key (keys(%{$result})) {
                   1447:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1448:                     (ref($result->{$key}) eq 'HASH')) {
                   1449:                     $is_balancer = 1;
                   1450:                     $currrules = $result->{$key}{'rules'};
                   1451:                     $currtargets = $result->{$key}{'targets'};
                   1452:                     last;
                   1453:                 }
                   1454:             }
                   1455:         }
                   1456:     }
                   1457:     return ($is_balancer,$currtargets,$currrules);
                   1458: }
                   1459: 
1.1129    raeburn  1460: sub get_loadbalancer_targets {
                   1461:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1462:     my $offloadto;
1.1175    raeburn  1463:     if ($rule_in_effect eq 'none') {
                   1464:         return [$perlvar{'lonHostID'}];
                   1465:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1466:         $offloadto = $currtargets;
                   1467:     } else {
                   1468:         if ($rule_in_effect eq 'homeserver') {
                   1469:             my $homeserver = &homeserver($uname,$udom);
                   1470:             if ($homeserver ne 'no_host') {
                   1471:                 $offloadto = [$homeserver];
                   1472:             }
                   1473:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1474:             my %domconfig =
                   1475:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1476:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1477:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1478:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1479:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1480:                     }
                   1481:                 }
                   1482:             } else {
1.1178    raeburn  1483:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1484:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1485:                 if (&hostname($remotebalancer) ne '') {
                   1486:                     $offloadto = [$remotebalancer];
                   1487:                 }
                   1488:             }
                   1489:         } elsif (&hostname($rule_in_effect) ne '') {
                   1490:             $offloadto = [$rule_in_effect];
                   1491:         }
                   1492:     }
                   1493:     return $offloadto;
                   1494: }
                   1495: 
1.1127    raeburn  1496: sub internet_dom_servers {
                   1497:     my ($dom) = @_;
                   1498:     my (%uniqservers,%servers);
                   1499:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1500:     my @machinedoms = &machine_domains($primaryserver);
                   1501:     foreach my $mdom (@machinedoms) {
                   1502:         my %currservers = %servers;
                   1503:         my %server = &get_servers($mdom);
                   1504:         %servers = (%currservers,%server);
                   1505:     }
                   1506:     my %by_hostname;
                   1507:     foreach my $id (keys(%servers)) {
                   1508:         push(@{$by_hostname{$servers{$id}}},$id);
                   1509:     }
                   1510:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1511:         if (@{$by_hostname{$hostname}} > 1) {
                   1512:             my $match = 0;
                   1513:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1514:                 if (&host_domain($id) eq $dom) {
                   1515:                     $uniqservers{$id} = $hostname;
                   1516:                     $match = 1;
                   1517:                 }
                   1518:             }
                   1519:             unless ($match) {
                   1520:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1521:             }
                   1522:         } else {
                   1523:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1524:         }
                   1525:     }
                   1526:     return %uniqservers;
                   1527: }
                   1528: 
1.1       albertel 1529: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1530: 
1.599     albertel 1531: my %homecache;
1.1       albertel 1532: sub homeserver {
1.230     stredwic 1533:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1534:     my $index="$uname:$udom";
1.426     albertel 1535: 
1.599     albertel 1536:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1537: 
                   1538:     my %servers = &get_servers($udom,'library');
                   1539:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1540:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1541: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1542: 
                   1543: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1544: 	if ($answer eq 'found') {
                   1545: 	    delete($badServerCache{$tryserver}); 
                   1546: 	    return $homecache{$index}=$tryserver;
                   1547: 	} elsif ($answer eq 'no_host') {
                   1548: 	    $badServerCache{$tryserver}=1;
                   1549: 	}
1.1       albertel 1550:     }    
                   1551:     return 'no_host';
1.70      www      1552: }
                   1553: 
                   1554: # ------------------------------------- Find the usernames behind a list of IDs
                   1555: 
                   1556: sub idget {
                   1557:     my ($udom,@ids)=@_;
                   1558:     my %returnhash=();
                   1559:     
1.841     albertel 1560:     my %servers = &get_servers($udom,'library');
                   1561:     foreach my $tryserver (keys(%servers)) {
1.1299  ! raeburn  1562: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1563: 	$idlist=~tr/A-Z/a-z/; 
                   1564: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1565: 	my @answer=();
                   1566: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1567: 	    @answer=split(/\&/,$reply);
                   1568: 	}                    ;
                   1569: 	my $i;
                   1570: 	for ($i=0;$i<=$#ids;$i++) {
                   1571: 	    if ($answer[$i]) {
1.1299  ! raeburn  1572: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1573: 	    } 
                   1574: 	}
                   1575:     } 
1.70      www      1576:     return %returnhash;
                   1577: }
                   1578: 
                   1579: # ------------------------------------- Find the IDs behind a list of usernames
                   1580: 
                   1581: sub idrget {
                   1582:     my ($udom,@unames)=@_;
                   1583:     my %returnhash=();
1.800     albertel 1584:     foreach my $uname (@unames) {
                   1585:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1586:     }
1.70      www      1587:     return %returnhash;
                   1588: }
                   1589: 
                   1590: # ------------------------------- Store away a list of names and associated IDs
                   1591: 
                   1592: sub idput {
                   1593:     my ($udom,%ids)=@_;
                   1594:     my %servers=();
1.800     albertel 1595:     foreach my $uname (keys(%ids)) {
                   1596: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1597:         my $uhom=&homeserver($uname,$udom);
1.70      www      1598:         if ($uhom ne 'no_host') {
1.800     albertel 1599:             my $id=&escape($ids{$uname});
1.70      www      1600:             $id=~tr/A-Z/a-z/;
1.800     albertel 1601:             my $esc_unam=&escape($uname);
1.70      www      1602: 	    if ($servers{$uhom}) {
1.800     albertel 1603: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1604:             } else {
1.800     albertel 1605:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1606:             }
                   1607:         }
1.191     harris41 1608:     }
1.800     albertel 1609:     foreach my $server (keys(%servers)) {
                   1610:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1611:     }
1.344     www      1612: }
                   1613: 
1.1231    raeburn  1614: # ---------------------------------------- Delete unwanted IDs from ids.db file 
                   1615: 
                   1616: sub iddel {
                   1617:     my ($udom,$idshashref,$uhome)=@_;
                   1618:     my %result=();
                   1619:     unless (ref($idshashref) eq 'HASH') {
                   1620:         return %result;
                   1621:     }
                   1622:     my %servers=();
                   1623:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1624:         my $uhom;
                   1625:         if ($uhome) {
                   1626:             $uhom = $uhome;
                   1627:         } else {
                   1628:             $uhom=&homeserver($uname,$udom);
                   1629:         }
                   1630:         if ($uhom ne 'no_host') {
                   1631:             if ($servers{$uhom}) {
                   1632:                 $servers{$uhom}.='&'.&escape($id);
                   1633:             } else {
                   1634:                 $servers{$uhom}=&escape($id);
                   1635:             }
                   1636:         }
                   1637:     }
                   1638:     foreach my $server (keys(%servers)) {
                   1639:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1640:     }
                   1641:     return %result;
                   1642: }
                   1643: 
1.1023    raeburn  1644: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1645: sub dump_dom {
1.1165    droeschl 1646:     my ($namespace, $udom, $regexp) = @_;
                   1647: 
                   1648:     $udom ||= $env{'user.domain'};
                   1649: 
                   1650:     return () unless $udom;
                   1651: 
                   1652:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1653: }
                   1654: 
1.1023    raeburn  1655: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1656: 
                   1657: sub get_dom {
1.860     raeburn  1658:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1659:     return if ($udom eq 'public');
1.806     raeburn  1660:     my $items='';
                   1661:     foreach my $item (@$storearr) {
                   1662:         $items.=&escape($item).'&';
                   1663:     }
                   1664:     $items=~s/\&$//;
1.860     raeburn  1665:     if (!$udom) {
                   1666:         $udom=$env{'user.domain'};
1.1267    raeburn  1667:         return if ($udom eq 'public');
1.860     raeburn  1668:         if (defined(&domain($udom,'primary'))) {
                   1669:             $uhome=&domain($udom,'primary');
                   1670:         } else {
1.874     albertel 1671:             undef($uhome);
1.860     raeburn  1672:         }
                   1673:     } else {
                   1674:         if (!$uhome) {
                   1675:             if (defined(&domain($udom,'primary'))) {
                   1676:                 $uhome=&domain($udom,'primary');
                   1677:             }
                   1678:         }
                   1679:     }
                   1680:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1681:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1682:         my %returnhash;
1.875     albertel 1683:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1684:             return %returnhash;
                   1685:         }
1.806     raeburn  1686:         my @pairs=split(/\&/,$rep);
                   1687:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1688:             return @pairs;
                   1689:         }
                   1690:         my $i=0;
                   1691:         foreach my $item (@$storearr) {
                   1692:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1693:             $i++;
                   1694:         }
                   1695:         return %returnhash;
                   1696:     } else {
1.880     banghart 1697:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1698:     }
                   1699: }
                   1700: 
                   1701: # -------------------------------------------- put items in domain db files 
                   1702: 
                   1703: sub put_dom {
1.860     raeburn  1704:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1705:     if (!$udom) {
                   1706:         $udom=$env{'user.domain'};
                   1707:         if (defined(&domain($udom,'primary'))) {
                   1708:             $uhome=&domain($udom,'primary');
                   1709:         } else {
1.874     albertel 1710:             undef($uhome);
1.860     raeburn  1711:         }
                   1712:     } else {
                   1713:         if (!$uhome) {
                   1714:             if (defined(&domain($udom,'primary'))) {
                   1715:                 $uhome=&domain($udom,'primary');
                   1716:             }
                   1717:         }
                   1718:     } 
                   1719:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1720:         my $items='';
                   1721:         foreach my $item (keys(%$storehash)) {
                   1722:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1723:         }
                   1724:         $items=~s/\&$//;
                   1725:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1726:     } else {
1.860     raeburn  1727:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1728:     }
                   1729: }
                   1730: 
1.1023    raeburn  1731: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1732: sub newput_dom {
1.1023    raeburn  1733:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1734:     my $result;
                   1735:     if (!$udom) {
                   1736:         $udom=$env{'user.domain'};
                   1737:     }
1.1023    raeburn  1738:     if ($udom) {
                   1739:         my $uname = &get_domainconfiguser($udom);
                   1740:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1741:     }
                   1742:     return $result;
                   1743: }
                   1744: 
1.1023    raeburn  1745: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1746: sub del_dom {
1.1023    raeburn  1747:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1748:     if (ref($storearr) eq 'ARRAY') {
                   1749:         if (!$udom) {
                   1750:             $udom=$env{'user.domain'};
                   1751:         }
1.1023    raeburn  1752:         if ($udom) {
                   1753:             my $uname = &get_domainconfiguser($udom); 
                   1754:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1755:         }
                   1756:     }
                   1757: }
                   1758: 
1.1023    raeburn  1759: # ----------------------------------construct domainconfig user for a domain 
                   1760: sub get_domainconfiguser {
                   1761:     my ($udom) = @_;
                   1762:     return $udom.'-domainconfig';
                   1763: }
                   1764: 
1.837     raeburn  1765: sub retrieve_inst_usertypes {
                   1766:     my ($udom) = @_;
                   1767:     my (%returnhash,@order);
1.989     raeburn  1768:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1769:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1770:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  1771:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1772:     } else {
                   1773:         if (defined(&domain($udom,'primary'))) {
                   1774:             my $uhome=&domain($udom,'primary');
                   1775:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1776:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  1777:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1778:                 return (\%returnhash,\@order);
                   1779:             }
                   1780:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1781:             my @pairs=split(/\&/,$hashitems);
                   1782:             foreach my $item (@pairs) {
                   1783:                 my ($key,$value)=split(/=/,$item,2);
                   1784:                 $key = &unescape($key);
                   1785:                 next if ($key =~ /^error: 2 /);
                   1786:                 $returnhash{$key}=&thaw_unescape($value);
                   1787:             }
                   1788:             my @esc_order = split(/\&/,$orderitems);
                   1789:             foreach my $item (@esc_order) {
                   1790:                 push(@order,&unescape($item));
                   1791:             }
                   1792:         } else {
1.1256    raeburn  1793:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1794:         }
1.1256    raeburn  1795:         return (\%returnhash,\@order);
1.837     raeburn  1796:     }
                   1797: }
                   1798: 
1.868     raeburn  1799: sub is_domainimage {
                   1800:     my ($url) = @_;
                   1801:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1802:         if (&domain($1) ne '') {
                   1803:             return '1';
                   1804:         }
                   1805:     }
                   1806:     return;
                   1807: }
                   1808: 
1.899     raeburn  1809: sub inst_directory_query {
                   1810:     my ($srch) = @_;
                   1811:     my $udom = $srch->{'srchdomain'};
                   1812:     my %results;
                   1813:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1814:     my $outcome;
1.899     raeburn  1815:     if ($homeserver ne '') {
1.904     albertel 1816: 	my $queryid=&reply("querysend:instdirsearch:".
                   1817: 			   &escape($srch->{'srchby'}).':'.
                   1818: 			   &escape($srch->{'srchterm'}).':'.
                   1819: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1820: 	my $host=&hostname($homeserver);
                   1821: 	if ($queryid !~/^\Q$host\E\_/) {
                   1822: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1823: 	    return;
                   1824: 	}
                   1825: 	my $response = &get_query_reply($queryid);
                   1826: 	my $maxtries = 5;
                   1827: 	my $tries = 1;
                   1828: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1829: 	    $response = &get_query_reply($queryid);
                   1830: 	    $tries ++;
                   1831: 	}
                   1832: 
                   1833:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1834:             if ($response eq 'unavailable') {
                   1835:                 $outcome = $response;
                   1836:             } else {
                   1837:                 $outcome = 'ok';
                   1838:                 my @matches = split(/\n/,$response);
                   1839:                 foreach my $match (@matches) {
                   1840:                     my ($key,$value) = split(/=/,$match);
                   1841:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1842:                 }
1.899     raeburn  1843:             }
                   1844:         }
                   1845:     }
1.909     raeburn  1846:     return ($outcome,%results);
1.899     raeburn  1847: }
                   1848: 
                   1849: sub usersearch {
                   1850:     my ($srch) = @_;
                   1851:     my $dom = $srch->{'srchdomain'};
                   1852:     my %results;
                   1853:     my %libserv = &all_library();
                   1854:     my $query = 'usersearch';
                   1855:     foreach my $tryserver (keys(%libserv)) {
                   1856:         if (&host_domain($tryserver) eq $dom) {
                   1857:             my $host=&hostname($tryserver);
                   1858:             my $queryid=
1.911     raeburn  1859:                 &reply("querysend:".&escape($query).':'.
                   1860:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1861:                        &escape($srch->{'srchtype'}).':'.
                   1862:                        &escape($srch->{'srchterm'}),$tryserver);
                   1863:             if ($queryid !~/^\Q$host\E\_/) {
                   1864:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1865:                 next;
1.899     raeburn  1866:             }
                   1867:             my $reply = &get_query_reply($queryid);
                   1868:             my $maxtries = 1;
                   1869:             my $tries = 1;
                   1870:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1871:                 $reply = &get_query_reply($queryid);
                   1872:                 $tries ++;
                   1873:             }
                   1874:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1875:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1876:             } else {
1.911     raeburn  1877:                 my @matches;
                   1878:                 if ($reply =~ /\n/) {
                   1879:                     @matches = split(/\n/,$reply);
                   1880:                 } else {
                   1881:                     @matches = split(/\&/,$reply);
                   1882:                 }
1.899     raeburn  1883:                 foreach my $match (@matches) {
                   1884:                     my ($uname,$udom,%userhash);
1.911     raeburn  1885:                     foreach my $entry (split(/:/,$match)) {
                   1886:                         my ($key,$value) =
                   1887:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1888:                         $userhash{$key} = $value;
                   1889:                         if ($key eq 'username') {
                   1890:                             $uname = $value;
                   1891:                         } elsif ($key eq 'domain') {
                   1892:                             $udom = $value;
1.911     raeburn  1893:                         }
1.899     raeburn  1894:                     }
                   1895:                     $results{$uname.':'.$udom} = \%userhash;
                   1896:                 }
                   1897:             }
                   1898:         }
                   1899:     }
                   1900:     return %results;
                   1901: }
                   1902: 
1.912     raeburn  1903: sub get_instuser {
                   1904:     my ($udom,$uname,$id) = @_;
                   1905:     my $homeserver = &domain($udom,'primary');
                   1906:     my ($outcome,%results);
                   1907:     if ($homeserver ne '') {
                   1908:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1909:                            &escape($id).':'.&escape($udom),$homeserver);
                   1910:         my $host=&hostname($homeserver);
                   1911:         if ($queryid !~/^\Q$host\E\_/) {
                   1912:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1913:             return;
                   1914:         }
                   1915:         my $response = &get_query_reply($queryid);
                   1916:         my $maxtries = 5;
                   1917:         my $tries = 1;
                   1918:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1919:             $response = &get_query_reply($queryid);
                   1920:             $tries ++;
                   1921:         }
                   1922:         if (!&error($response) && $response ne 'refused') {
                   1923:             if ($response eq 'unavailable') {
                   1924:                 $outcome = $response;
                   1925:             } else {
                   1926:                 $outcome = 'ok';
                   1927:                 my @matches = split(/\n/,$response);
                   1928:                 foreach my $match (@matches) {
                   1929:                     my ($key,$value) = split(/=/,$match);
                   1930:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1931:                 }
                   1932:             }
                   1933:         }
                   1934:     }
                   1935:     my %userinfo;
                   1936:     if (ref($results{$uname}) eq 'HASH') {
                   1937:         %userinfo = %{$results{$uname}};
                   1938:     } 
                   1939:     return ($outcome,%userinfo);
                   1940: }
                   1941: 
1.1290    raeburn  1942: sub get_multiple_instusers {
                   1943:     my ($udom,$users,$caller) = @_;
                   1944:     my ($outcome,$results);
                   1945:     if (ref($users) eq 'HASH') {
                   1946:         my $count = keys(%{$users}); 
                   1947:         my $requested = &freeze_escape($users);
                   1948:         my $homeserver = &domain($udom,'primary');
                   1949:         if ($homeserver ne '') {
                   1950:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   1951:             my $host=&hostname($homeserver);
                   1952:             if ($queryid !~/^\Q$host\E\_/) {
                   1953:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   1954:                          ' for host: '.$homeserver.'in domain '.$udom);
                   1955:                 return ($outcome,$results);
                   1956:             }
                   1957:             my $response = &get_query_reply($queryid);
                   1958:             my $maxtries = 5;
                   1959:             if ($count > 100) {
                   1960:                 $maxtries = 1+int($count/20);
                   1961:             }
                   1962:             my $tries = 1;
                   1963:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   1964:                 $response = &get_query_reply($queryid);
                   1965:                 $tries ++;
                   1966:             }
                   1967:             if ($response eq '') {
                   1968:                 $results = {};
                   1969:                 foreach my $key (keys(%{$users})) {
                   1970:                     my ($uname,$id);
                   1971:                     if ($caller eq 'id') {
                   1972:                         $id = $key;
                   1973:                     } else {
                   1974:                         $uname = $key;
                   1975:                     }
                   1976:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  1977:                     $outcome = $resp;
1.1290    raeburn  1978:                     if ($resp eq 'ok') {
                   1979:                         %{$results} = (%{$results}, %info);
                   1980:                     } else {
                   1981:                         last;
                   1982:                     }
                   1983:                 }
                   1984:             } elsif(!&error($response) && ($response ne 'refused')) {
                   1985:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   1986:                     $outcome = $response;
                   1987:                 } else {
1.1291    raeburn  1988:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  1989:                     if ($outcome eq 'ok') {
                   1990:                         $results = &thaw_unescape($userdata); 
                   1991:                     }
                   1992:                 }
                   1993:             }
                   1994:         }
                   1995:     }
                   1996:     return ($outcome,$results);
                   1997: }
                   1998: 
1.912     raeburn  1999: sub inst_rulecheck {
1.923     raeburn  2000:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2001:     my %returnhash;
                   2002:     if ($udom ne '') {
                   2003:         if (ref($rules) eq 'ARRAY') {
                   2004:             @{$rules} = map {&escape($_);} (@{$rules});
                   2005:             my $rulestr = join(':',@{$rules});
                   2006:             my $homeserver=&domain($udom,'primary');
                   2007:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2008:                 my $response;
                   2009:                 if ($item eq 'username') {                
                   2010:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2011:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2012:                                               $homeserver));
1.923     raeburn  2013:                 } elsif ($item eq 'id') {
                   2014:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2015:                                               ':'.&escape($id).':'.$rulestr,
                   2016:                                               $homeserver));
1.945     raeburn  2017:                 } elsif ($item eq 'selfcreate') {
                   2018:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2019:                                                &escape($udom).':'.&escape($uname).
                   2020:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2021:                 }
1.912     raeburn  2022:                 if ($response ne 'refused') {
                   2023:                     my @pairs=split(/\&/,$response);
                   2024:                     foreach my $item (@pairs) {
                   2025:                         my ($key,$value)=split(/=/,$item,2);
                   2026:                         $key = &unescape($key);
                   2027:                         next if ($key =~ /^error: 2 /);
                   2028:                         $returnhash{$key}=&thaw_unescape($value);
                   2029:                     }
                   2030:                 }
                   2031:             }
                   2032:         }
                   2033:     }
                   2034:     return %returnhash;
                   2035: }
                   2036: 
                   2037: sub inst_userrules {
1.923     raeburn  2038:     my ($udom,$check) = @_;
1.912     raeburn  2039:     my (%ruleshash,@ruleorder);
                   2040:     if ($udom ne '') {
                   2041:         my $homeserver=&domain($udom,'primary');
                   2042:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2043:             my $response;
                   2044:             if ($check eq 'id') {
                   2045:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2046:                                  $homeserver);
1.943     raeburn  2047:             } elsif ($check eq 'email') {
                   2048:                 $response=&reply('instemailrules:'.&escape($udom),
                   2049:                                  $homeserver);
1.923     raeburn  2050:             } else {
                   2051:                 $response=&reply('instuserrules:'.&escape($udom),
                   2052:                                  $homeserver);
                   2053:             }
1.912     raeburn  2054:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2055:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2056:                 ($response ne 'no_such_host')) {
                   2057:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2058:                 my @pairs=split(/\&/,$hashitems);
                   2059:                 foreach my $item (@pairs) {
                   2060:                     my ($key,$value)=split(/=/,$item,2);
                   2061:                     $key = &unescape($key);
                   2062:                     next if ($key =~ /^error: 2 /);
                   2063:                     $ruleshash{$key}=&thaw_unescape($value);
                   2064:                 }
                   2065:                 my @esc_order = split(/\&/,$orderitems);
                   2066:                 foreach my $item (@esc_order) {
                   2067:                     push(@ruleorder,&unescape($item));
                   2068:                 }
                   2069:             }
                   2070:         }
                   2071:     }
                   2072:     return (\%ruleshash,\@ruleorder);
                   2073: }
                   2074: 
1.976     raeburn  2075: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2076: 
                   2077: sub get_domain_defaults {
1.1240    raeburn  2078:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2079:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2080:     my $cachetime = 60*60*24;
1.1240    raeburn  2081:     unless ($ignore_cache) {
                   2082:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2083:         if (defined($cached)) {
                   2084:             if (ref($result) eq 'HASH') {
                   2085:                 return %{$result};
                   2086:             }
1.943     raeburn  2087:         }
                   2088:     }
                   2089:     my %domdefaults;
                   2090:     my %domconfig =
1.989     raeburn  2091:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2092:                                   'requestcourses','inststatus',
1.1183    raeburn  2093:                                   'coursedefaults','usersessions',
1.1258    raeburn  2094:                                   'requestauthor','selfenrollment',
                   2095:                                   'coursecategories'],$domain);
1.1254    raeburn  2096:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2097:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2098:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2099:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2100:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2101:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2102:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2103:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2104:     } else {
                   2105:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2106:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2107:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2108:     }
1.976     raeburn  2109:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2110:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2111:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2112:         } else {
                   2113:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2114:         }
1.1177    raeburn  2115:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2116:         foreach my $item (@usertools) {
                   2117:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2118:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2119:             }
                   2120:         }
1.1229    raeburn  2121:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2122:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2123:         }
1.976     raeburn  2124:     }
1.985     raeburn  2125:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246    raeburn  2126:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2127:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2128:         }
                   2129:     }
1.1183    raeburn  2130:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2131:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2132:     }
1.989     raeburn  2133:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2134:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2135:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2136:         }
                   2137:     }
1.1047    raeburn  2138:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2139:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2140:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2141:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2142:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2143:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2144:         }
1.1254    raeburn  2145:         foreach my $type (@coursetypes) {
                   2146:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2147:                 unless ($type eq 'community') {
                   2148:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2149:                 }
                   2150:             }
                   2151:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2152:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2153:             }
1.1277    raeburn  2154:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2155:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2156:                     $domdefaults{$type.'postsubtimeout'} = 
                   2157:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2158:                 }
                   2159:             }
1.1230    raeburn  2160:         }
1.1286    raeburn  2161:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2162:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2163:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2164:                 if (@clonecodes) {
                   2165:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2166:                 }
                   2167:             }
                   2168:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2169:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2170:         }
1.1047    raeburn  2171:     }
1.1073    raeburn  2172:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2173:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2174:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2175:         }
                   2176:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2177:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2178:         }
1.1279    raeburn  2179:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2180:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2181:         }
1.1073    raeburn  2182:     }
1.1254    raeburn  2183:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2184:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2185:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2186:                             'approval','limit');
                   2187:             foreach my $type (@coursetypes) {
                   2188:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2189:                     my @mgrdc = ();
                   2190:                     foreach my $item (@settings) {
                   2191:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2192:                             push(@mgrdc,$item);
                   2193:                         }
                   2194:                     }
                   2195:                     if (@mgrdc) {
                   2196:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2197:                     }
                   2198:                 }
                   2199:             }
                   2200:         }
                   2201:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2202:             foreach my $type (@coursetypes) {
                   2203:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2204:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2205:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2206:                     }
                   2207:                 }
                   2208:             }
                   2209:         }
                   2210:     }
1.1258    raeburn  2211:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2212:         $domdefaults{'catauth'} = 'std';
                   2213:         $domdefaults{'catunauth'} = 'std';
                   2214:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2215:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2216:         }
                   2217:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2218:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2219:         }
                   2220:     }
1.1219    raeburn  2221:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2222:     return %domdefaults;
                   2223: }
                   2224: 
1.344     www      2225: # --------------------------------------------------- Assign a key to a student
                   2226: 
                   2227: sub assign_access_key {
1.364     www      2228: #
                   2229: # a valid key looks like uname:udom#comments
                   2230: # comments are being appended
                   2231: #
1.498     www      2232:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2233:     $kdom=
1.620     albertel 2234:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2235:     $knum=
1.620     albertel 2236:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2237:     $cdom=
1.620     albertel 2238:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2239:     $cnum=
1.620     albertel 2240:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2241:     $udom=$env{'user.name'} unless (defined($udom));
                   2242:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2243:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2244:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2245:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2246:                                                   # assigned to this person
                   2247:                                                   # - this should not happen,
1.345     www      2248:                                                   # unless something went wrong
                   2249:                                                   # the first time around
                   2250: # ready to assign
1.364     www      2251:         $logentry=$1.'; '.$logentry;
1.496     www      2252:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2253:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2254: # key now belongs to user
1.346     www      2255: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2256:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2257:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2258:                 return 'ok';
                   2259:             } else {
                   2260:                 return 
                   2261:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2262: 	    }
                   2263:         } else {
                   2264:             return 'error: Could not assign key, try again later.';
                   2265:         }
1.364     www      2266:     } elsif (!$existing{$ckey}) {
1.345     www      2267: # the key does not exist
                   2268: 	return 'error: The key does not exist';
                   2269:     } else {
                   2270: # the key is somebody else's
                   2271: 	return 'error: The key is already in use';
                   2272:     }
1.344     www      2273: }
                   2274: 
1.364     www      2275: # ------------------------------------------ put an additional comment on a key
                   2276: 
                   2277: sub comment_access_key {
                   2278: #
                   2279: # a valid key looks like uname:udom#comments
                   2280: # comments are being appended
                   2281: #
                   2282:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2283:     $cdom=
1.620     albertel 2284:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2285:     $cnum=
1.620     albertel 2286:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2287:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2288:     if ($existing{$ckey}) {
                   2289:         $existing{$ckey}.='; '.$logentry;
                   2290: # ready to assign
1.367     www      2291:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2292:                                                  $cdom,$cnum) eq 'ok') {
                   2293: 	    return 'ok';
                   2294:         } else {
                   2295: 	    return 'error: Count not store comment.';
                   2296:         }
                   2297:     } else {
                   2298: # the key does not exist
                   2299: 	return 'error: The key does not exist';
                   2300:     }
                   2301: }
                   2302: 
1.344     www      2303: # ------------------------------------------------------ Generate a set of keys
                   2304: 
                   2305: sub generate_access_keys {
1.364     www      2306:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2307:     $cdom=
1.620     albertel 2308:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2309:     $cnum=
1.620     albertel 2310:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2311:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2312:     unless (($cdom) && ($cnum)) { return 0; }
                   2313:     if ($number>10000) { return 0; }
                   2314:     sleep(2); # make sure don't get same seed twice
                   2315:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2316:     my $total=0;
                   2317:     for (my $i=1;$i<=$number;$i++) {
                   2318:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2319:                   sprintf("%lx",int(100000*rand)).'-'.
                   2320:                   sprintf("%lx",int(100000*rand));
                   2321:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2322:        $newkey=~s/0/h/g; # and also 0 and O
                   2323:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2324:        if ($existing{$newkey}) {
                   2325:            $i--;
                   2326:        } else {
1.364     www      2327: 	  if (&put('accesskeys',
                   2328:               { $newkey => '# generated '.localtime().
1.620     albertel 2329:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2330:                            '; '.$logentry },
                   2331: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2332:               $total++;
                   2333: 	  }
                   2334:        }
                   2335:     }
1.620     albertel 2336:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2337:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2338:     return $total;
                   2339: }
                   2340: 
                   2341: # ------------------------------------------------------- Validate an accesskey
                   2342: 
                   2343: sub validate_access_key {
                   2344:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2345:     $cdom=
1.620     albertel 2346:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2347:     $cnum=
1.620     albertel 2348:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2349:     $udom=$env{'user.domain'} unless (defined($udom));
                   2350:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2351:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2352:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2353: }
                   2354: 
                   2355: # ------------------------------------- Find the section of student in a course
1.652     albertel 2356: sub devalidate_getsection_cache {
                   2357:     my ($udom,$unam,$courseid)=@_;
                   2358:     my $hashid="$udom:$unam:$courseid";
                   2359:     &devalidate_cache_new('getsection',$hashid);
                   2360: }
1.298     matthew  2361: 
1.815     albertel 2362: sub courseid_to_courseurl {
                   2363:     my ($courseid) = @_;
                   2364:     #already url style courseid
                   2365:     return $courseid if ($courseid =~ m{^/});
                   2366: 
                   2367:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2368: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2369: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2370: 	return "/$cdom/$cnum";
                   2371:     }
                   2372: 
                   2373:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2374:     if (exists($courseinfo{'num'})) {
                   2375: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2376:     }
                   2377: 
                   2378:     return undef;
                   2379: }
                   2380: 
1.298     matthew  2381: sub getsection {
                   2382:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2383:     my $cachetime=1800;
1.551     albertel 2384: 
                   2385:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2386:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2387:     if (defined($cached)) { return $result; }
                   2388: 
1.298     matthew  2389:     my %Pending; 
                   2390:     my %Expired;
                   2391:     #
                   2392:     # Each role can either have not started yet (pending), be active, 
                   2393:     #    or have expired.
                   2394:     #
                   2395:     # If there is an active role, we are done.
                   2396:     #
                   2397:     # If there is more than one role which has not started yet, 
                   2398:     #     choose the one which will start sooner
                   2399:     # If there is one role which has not started yet, return it.
                   2400:     #
                   2401:     # If there is more than one expired role, choose the one which ended last.
                   2402:     # If there is a role which has expired, return it.
                   2403:     #
1.815     albertel 2404:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2405:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2406:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2407:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2408:         my $section=$1;
                   2409:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2410:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2411:         my $now=time;
1.548     albertel 2412:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2413:             $Expired{$end}=$section;
                   2414:             next;
                   2415:         }
1.548     albertel 2416:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2417:             $Pending{$start}=$section;
                   2418:             next;
                   2419:         }
1.599     albertel 2420:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2421:     }
                   2422:     #
                   2423:     # Presumedly there will be few matching roles from the above
                   2424:     # loop and the sorting time will be negligible.
                   2425:     if (scalar(keys(%Pending))) {
                   2426:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2427:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2428:     } 
                   2429:     if (scalar(keys(%Expired))) {
                   2430:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2431:         my $time = pop(@sorted);
1.599     albertel 2432:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2433:     }
1.599     albertel 2434:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2435: }
1.70      www      2436: 
1.599     albertel 2437: sub save_cache {
                   2438:     &purge_remembered();
1.722     albertel 2439:     #&Apache::loncommon::validate_page();
1.620     albertel 2440:     undef(%env);
1.780     albertel 2441:     undef($env_loaded);
1.599     albertel 2442: }
1.452     albertel 2443: 
1.599     albertel 2444: my $to_remember=-1;
                   2445: my %remembered;
                   2446: my %accessed;
                   2447: my $kicks=0;
                   2448: my $hits=0;
1.849     albertel 2449: sub make_key {
                   2450:     my ($name,$id) = @_;
1.872     albertel 2451:     if (length($id) > 65 
                   2452: 	&& length(&escape($id)) > 200) {
                   2453: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2454:     }
1.849     albertel 2455:     return &escape($name.':'.$id);
                   2456: }
                   2457: 
1.599     albertel 2458: sub devalidate_cache_new {
                   2459:     my ($name,$id,$debug) = @_;
                   2460:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2461:     $id=&make_key($name,$id);
1.599     albertel 2462:     $memcache->delete($id);
                   2463:     delete($remembered{$id});
                   2464:     delete($accessed{$id});
                   2465: }
                   2466: 
                   2467: sub is_cached_new {
                   2468:     my ($name,$id,$debug) = @_;
1.849     albertel 2469:     $id=&make_key($name,$id);
1.599     albertel 2470:     if (exists($remembered{$id})) {
1.1133    foxr     2471: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2472: 	$accessed{$id}=[&gettimeofday()];
                   2473: 	$hits++;
                   2474: 	return ($remembered{$id},1);
                   2475:     }
                   2476:     my $value = $memcache->get($id);
                   2477:     if (!(defined($value))) {
                   2478: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2479: 	return (undef,undef);
1.416     albertel 2480:     }
1.599     albertel 2481:     if ($value eq '__undef__') {
                   2482: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2483: 	$value=undef;
                   2484:     }
                   2485:     &make_room($id,$value,$debug);
                   2486:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2487:     return ($value,1);
                   2488: }
                   2489: 
                   2490: sub do_cache_new {
                   2491:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2492:     $id=&make_key($name,$id);
1.599     albertel 2493:     my $setvalue=$value;
                   2494:     if (!defined($setvalue)) {
                   2495: 	$setvalue='__undef__';
                   2496:     }
1.623     albertel 2497:     if (!defined($time) ) {
                   2498: 	$time=600;
                   2499:     }
1.599     albertel 2500:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2501:     my $result = $memcache->set($id,$setvalue,$time);
                   2502:     if (! $result) {
1.872     albertel 2503: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2504: 	$memcache->disconnect_all();
1.872     albertel 2505:     }
1.600     albertel 2506:     # need to make a copy of $value
1.919     albertel 2507:     &make_room($id,$value,$debug);
1.599     albertel 2508:     return $value;
                   2509: }
                   2510: 
                   2511: sub make_room {
                   2512:     my ($id,$value,$debug)=@_;
1.919     albertel 2513: 
                   2514:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2515:                                     : $value;
1.599     albertel 2516:     if ($to_remember<0) { return; }
                   2517:     $accessed{$id}=[&gettimeofday()];
                   2518:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2519:     my $to_kick;
                   2520:     my $max_time=0;
                   2521:     foreach my $other (keys(%accessed)) {
                   2522: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2523: 	    $to_kick=$other;
                   2524: 	    $max_time=&tv_interval($accessed{$other});
                   2525: 	}
                   2526:     }
                   2527:     delete($remembered{$to_kick});
                   2528:     delete($accessed{$to_kick});
                   2529:     $kicks++;
                   2530:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2531:     return;
                   2532: }
                   2533: 
1.599     albertel 2534: sub purge_remembered {
1.604     albertel 2535:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2536:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2537:     undef(%remembered);
                   2538:     undef(%accessed);
1.428     albertel 2539: }
1.70      www      2540: # ------------------------------------- Read an entry from a user's environment
                   2541: 
                   2542: sub userenvironment {
                   2543:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2544:     my $items;
                   2545:     foreach my $item (@what) {
                   2546:         $items.=&escape($item).'&';
                   2547:     }
                   2548:     $items=~s/\&$//;
1.70      www      2549:     my %returnhash=();
1.1009    raeburn  2550:     my $uhome = &homeserver($unam,$udom);
                   2551:     unless ($uhome eq 'no_host') {
                   2552:         my @answer=split(/\&/, 
                   2553:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2554:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2555:             return %returnhash;
                   2556:         }
1.1009    raeburn  2557:         my $i;
                   2558:         for ($i=0;$i<=$#what;$i++) {
                   2559: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2560:         }
1.70      www      2561:     }
                   2562:     return %returnhash;
1.1       albertel 2563: }
                   2564: 
1.617     albertel 2565: # ---------------------------------------------------------- Get a studentphoto
                   2566: sub studentphoto {
                   2567:     my ($udom,$unam,$ext) = @_;
                   2568:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2569:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2570:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2571:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2572:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2573:             } else {
                   2574:                 my ($result,$perm_reqd)=
1.707     albertel 2575: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2576:                 if ($result eq 'ok') {
                   2577:                     if (!($perm_reqd eq 'yes')) {
                   2578:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2579:                     }
                   2580:                 }
                   2581:             }
                   2582:         }
                   2583:     } else {
                   2584:         my ($result,$perm_reqd) = 
1.707     albertel 2585: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2586:         if ($result eq 'ok') {
                   2587:             if (!($perm_reqd eq 'yes')) {
                   2588:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2589:             }
                   2590:         }
                   2591:     }
                   2592:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2593: }
                   2594: 
                   2595: sub retrievestudentphoto {
                   2596:     my ($udom,$unam,$ext,$type) = @_;
                   2597:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2598:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2599:     if ($ret eq 'ok') {
                   2600:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2601:         if ($type eq 'thumbnail') {
                   2602:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2603:         }
                   2604:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2605:         return $tokenurl;
                   2606:     } else {
                   2607:         if ($type eq 'thumbnail') {
                   2608:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2609:         } else { 
                   2610:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2611:         }
1.617     albertel 2612:     }
                   2613: }
                   2614: 
1.263     www      2615: # -------------------------------------------------------------------- New chat
                   2616: 
                   2617: sub chatsend {
1.724     raeburn  2618:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2619:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2620:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2621:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2622:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2623: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2624: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2625: }
                   2626: 
                   2627: # ------------------------------------------ Find current version of a resource
                   2628: 
                   2629: sub getversion {
                   2630:     my $fname=&clutter(shift);
1.1189    raeburn  2631:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2632:     return &currentversion(&filelocation('',$fname));
                   2633: }
                   2634: 
                   2635: sub currentversion {
                   2636:     my $fname=shift;
                   2637:     my $author=$fname;
                   2638:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2639:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2640:     my $home=&homeserver($uname,$udom);
1.292     www      2641:     if ($home eq 'no_host') { 
                   2642:         return -1; 
                   2643:     }
1.1112    www      2644:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2645:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2646: 	return -1;
                   2647:     }
1.1112    www      2648:     return $answer;
1.263     www      2649: }
                   2650: 
1.1111    www      2651: #
                   2652: # Return special version number of resource if set by override, empty otherwise
                   2653: #
                   2654: sub usedversion {
                   2655:     my $fname=shift;
                   2656:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2657:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2658:     if ($urlversion) { return $urlversion; }
                   2659:     return '';
                   2660: }
                   2661: 
1.1       albertel 2662: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2663: 
1.1       albertel 2664: sub subscribe {
                   2665:     my $fname=shift;
1.761     raeburn  2666:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2667:     $fname=~s/[\n\r]//g;
1.1       albertel 2668:     my $author=$fname;
                   2669:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2670:     my ($udom,$uname)=split(/\//,$author);
                   2671:     my $home=homeserver($uname,$udom);
1.335     albertel 2672:     if ($home eq 'no_host') {
                   2673:         return 'not_found';
1.1       albertel 2674:     }
                   2675:     my $answer=reply("sub:$fname",$home);
1.64      www      2676:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2677: 	$answer.=' by '.$home;
                   2678:     }
1.1       albertel 2679:     return $answer;
                   2680: }
                   2681:     
1.8       www      2682: # -------------------------------------------------------------- Replicate file
                   2683: 
                   2684: sub repcopy {
                   2685:     my $filename=shift;
1.23      www      2686:     $filename=~s/\/+/\//g;
1.1142    raeburn  2687:     my $londocroot = $perlvar{'lonDocRoot'};
                   2688:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2689:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2690:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2691: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2692: 	return &repcopy_userfile($filename);
                   2693:     }
1.532     albertel 2694:     $filename=~s/[\n\r]//g;
1.8       www      2695:     my $transname="$filename.in.transfer";
1.828     www      2696: # FIXME: this should flock
1.607     raeburn  2697:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2698:     my $remoteurl=subscribe($filename);
1.64      www      2699:     if ($remoteurl =~ /^con_lost by/) {
                   2700: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2701:            return 'unavailable';
1.8       www      2702:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2703: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2704: 	   return 'not_found';
1.64      www      2705:     } elsif ($remoteurl =~ /^rejected by/) {
                   2706: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2707:            return 'forbidden';
1.20      www      2708:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2709:            return 'ok';
1.8       www      2710:     } else {
1.290     www      2711:         my $author=$filename;
                   2712:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2713:         my ($udom,$uname)=split(/\//,$author);
                   2714:         my $home=homeserver($uname,$udom);
                   2715:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2716:            my @parts=split(/\//,$filename);
                   2717:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2718:            if ($path ne "$londocroot/res") {
1.8       www      2719:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2720: 	       return 'bad_request';
1.8       www      2721:            }
                   2722:            my $count;
                   2723:            for ($count=5;$count<$#parts;$count++) {
                   2724:                $path.="/$parts[$count]";
                   2725:                if ((-e $path)!=1) {
                   2726: 		   mkdir($path,0777);
                   2727:                }
                   2728:            }
                   2729:            my $ua=new LWP::UserAgent;
                   2730:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2731:            my $response=$ua->request($request,$transname);
                   2732:            if ($response->is_error()) {
                   2733: 	       unlink($transname);
                   2734:                my $message=$response->status_line;
1.672     albertel 2735:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2736:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2737:                return 'unavailable';
1.8       www      2738:            } else {
1.16      www      2739: 	       if ($remoteurl!~/\.meta$/) {
                   2740:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2741:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2742:                   if ($mresponse->is_error()) {
                   2743: 		      unlink($filename.'.meta');
                   2744:                       &logthis(
1.672     albertel 2745:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2746:                   }
                   2747: 	       }
1.8       www      2748:                rename($transname,$filename);
1.607     raeburn  2749:                return 'ok';
1.8       www      2750:            }
1.290     www      2751:        }
1.8       www      2752:     }
1.330     www      2753: }
                   2754: 
                   2755: # ------------------------------------------------ Get server side include body
                   2756: sub ssi_body {
1.381     albertel 2757:     my ($filelink,%form)=@_;
1.606     matthew  2758:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2759:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2760:     }
1.953     www      2761:     my $output='';
                   2762:     my $response;
1.980     raeburn  2763:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2764:        ($output,$response)=&externalssi($filelink);
1.953     www      2765:     } else {
1.1004    droeschl 2766:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2767:        $filelink .= 'inhibitmenu=yes';
1.953     www      2768:        ($output,$response)=&ssi($filelink,%form);
                   2769:     }
1.778     albertel 2770:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2771:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2772:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2773:     if (wantarray) {
                   2774:         return ($output, $response);
                   2775:     } else {
                   2776:         return $output;
                   2777:     }
1.8       www      2778: }
                   2779: 
1.15      www      2780: # --------------------------------------------------------- Server Side Include
                   2781: 
1.782     albertel 2782: sub absolute_url {
                   2783:     my ($host_name) = @_;
                   2784:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2785:     if ($host_name eq '') {
                   2786: 	$host_name = $ENV{'SERVER_NAME'};
                   2787:     }
                   2788:     return $protocol.$host_name;
                   2789: }
                   2790: 
1.942     foxr     2791: #
                   2792: #   Server side include.
                   2793: # Parameters:
                   2794: #  fn     Possibly encrypted resource name/id.
                   2795: #  form   Hash that describes how the rendering should be done
                   2796: #         and other things.
1.944     foxr     2797: # Returns:
1.950     raeburn  2798: #   Scalar context: The content of the response.
                   2799: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2800: #     
1.15      www      2801: sub ssi {
                   2802: 
1.944     foxr     2803:     my ($fn,%form)=@_;
1.15      www      2804:     my $ua=new LWP::UserAgent;
1.23      www      2805:     my $request;
1.711     albertel 2806: 
                   2807:     $form{'no_update_last_known'}=1;
1.895     albertel 2808:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2809:     if (%form) {
1.782     albertel 2810:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 2811:       $request->content(join('&',map { 
                   2812:             my $name = escape($_);
                   2813:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   2814:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   2815:             : &escape($form{$_}) );    
                   2816:         } keys(%form)));
1.23      www      2817:     } else {
1.782     albertel 2818:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2819:     }
                   2820: 
1.15      www      2821:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2822:     my $response= $ua->request($request);
1.1182    foxr     2823:     my $content = $response->content;
                   2824: 
                   2825: 
1.944     foxr     2826:     if (wantarray) {
1.1173    foxr     2827: 	return ($content, $response);
1.944     foxr     2828:     } else {
1.1173    foxr     2829: 	return $content;
1.942     foxr     2830:     }
1.324     www      2831: }
                   2832: 
                   2833: sub externalssi {
                   2834:     my ($url)=@_;
                   2835:     my $ua=new LWP::UserAgent;
                   2836:     my $request=new HTTP::Request('GET',$url);
                   2837:     my $response=$ua->request($request);
1.954     raeburn  2838:     if (wantarray) {
                   2839:         return ($response->content, $response);
                   2840:     } else {
                   2841:         return $response->content;
                   2842:     }
1.15      www      2843: }
1.254     www      2844: 
1.492     albertel 2845: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2846: 
                   2847: sub allowuploaded {
                   2848:     my ($srcurl,$url)=@_;
                   2849:     $url=&clutter(&declutter($url));
                   2850:     my $dir=$url;
                   2851:     $dir=~s/\/[^\/]+$//;
                   2852:     my %httpref=();
                   2853:     my $httpurl=&hreflocation('',$url);
                   2854:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2855:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2856: }
1.477     raeburn  2857: 
1.1193    raeburn  2858: #
                   2859: # Determine if the current user should be able to edit a particular resource,
                   2860: # when viewing in course context.
                   2861: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2862: #     Functions.
                   2863: # (b) When displaying folder contents in course editor, used to determine if
                   2864: #     "Edit" link will be displayed alongside resource.
                   2865: #
1.1196    raeburn  2866: #  input: six args -- filename (decluttered), course number, course domain,
                   2867: #                   url, symb (if registered) and group (if this is a group
                   2868: #                   item -- e.g., bulletin board, group page etc.).
                   2869: #  output: array of five scalars -- 
1.1193    raeburn  2870: #          $cfile -- url for file editing if editable on current server
                   2871: #          $home -- homeserver of resource (i.e., for author if published,
                   2872: #                                           or course if uploaded.).
                   2873: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  2874: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   2875: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  2876: #
                   2877: 
                   2878: sub can_edit_resource {
1.1194    raeburn  2879:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2880:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2881: #
                   2882: # For aboutme pages user can only edit his/her own.
                   2883: #
1.1199    raeburn  2884:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  2885:         my ($sdom,$sname) = ($1,$2);
                   2886:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2887:             $home = $env{'user.home'};
                   2888:             $cfile = $resurl;
                   2889:             if ($env{'form.forceedit'}) {
                   2890:                 $forceview = 1;
                   2891:             } else {
                   2892:                 $forceedit = 1;
                   2893:             }
                   2894:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2895:         } else {
                   2896:             return;
                   2897:         }
                   2898:     }
                   2899: 
                   2900:     if ($env{'request.course.id'}) {
                   2901:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2902:         if ($group ne '') {
                   2903: # if this is a group homepage or group bulletin board, check group privs
                   2904:             my $allowed = 0;
1.1197    raeburn  2905:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2906:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  2907:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  2908:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2909:                     $allowed = 1;
                   2910:                 }
1.1197    raeburn  2911:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2912:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2913:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  2914:                     $allowed = 1;
                   2915:                 }
                   2916:             }
                   2917:             if ($allowed) {
                   2918:                 $home=&homeserver($cnum,$cdom);
                   2919:                 if ($env{'form.forceedit'}) {
                   2920:                     $forceview = 1;
                   2921:                 } else {
                   2922:                     $forceedit = 1;
                   2923:                 }
                   2924:                 $cfile = $resurl;
                   2925:             } else {
                   2926:                 return;
                   2927:             }
                   2928:         } else {
1.1208    raeburn  2929:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2930:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2931:                     return;
                   2932:                 }
                   2933:             } elsif (!$crsedit) {
1.1194    raeburn  2934: #
                   2935: # No edit allowed where CC has switched to student role.
                   2936: #
                   2937:                 return;
                   2938:             }
                   2939:         }
                   2940:     }
                   2941: 
1.1193    raeburn  2942:     if ($file ne '') {
                   2943:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  2944:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2945:                 $uploaded = 1;
                   2946:                 $incourse = 1;
1.1193    raeburn  2947:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2948:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  2949:                     if ($env{'form.forceedit'}) {
                   2950:                         $forceview = 1;
                   2951:                     } else {
                   2952:                         $forceedit = 1;
                   2953:                     }
1.1194    raeburn  2954:                 }
                   2955:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2956:                 $incourse = 1;
                   2957:                 if ($env{'form.forceedit'}) {
                   2958:                     $forceview = 1;
                   2959:                 } else {
                   2960:                     $forceedit = 1;
                   2961:                 }
                   2962:                 $cfile = $resurl;
                   2963:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   2964:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2965:                     $incourse = 1;
                   2966:                     if ($env{'form.forceedit'}) {
                   2967:                         $forceview = 1;
                   2968:                     } else {
                   2969:                         $forceedit = 1;
                   2970:                     }
                   2971:                     $cfile = $resurl;
1.1199    raeburn  2972:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  2973:                     $incourse = 1;
                   2974:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  2975:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  2976:                     $incourse = 1;
1.1199    raeburn  2977:                     if ($env{'form.forceedit'}) {
                   2978:                         $forceview = 1;
                   2979:                     } else {
                   2980:                         $forceedit = 1;
                   2981:                     }
                   2982:                     $cfile = $resurl;
1.1298    raeburn  2983:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
                   2984:                     $incourse = 1;
                   2985:                     if ($env{'form.forceedit'}) {
                   2986:                         $forceview = 1;
                   2987:                     } else {
                   2988:                         $forceedit = 1;
                   2989:                     }
                   2990:                     $cfile = $resurl;
1.1208    raeburn  2991:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2992:                     $incourse = 1;
                   2993:                     if ($env{'form.forceedit'}) {
                   2994:                         $forceview = 1;
                   2995:                     } else {
                   2996:                         $forceedit = 1;
                   2997:                     }
                   2998:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  2999:                 }
                   3000:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3001:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3002:                 if (&is_on_map($template)) { 
                   3003:                     $incourse = 1;
                   3004:                     $forceview = 1;
                   3005:                     $cfile = $template;
1.1193    raeburn  3006:                 }
1.1199    raeburn  3007:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3008:                     $incourse = 1;
                   3009:                     if ($env{'form.forceedit'}) {
                   3010:                         $forceview = 1;
                   3011:                     } else {
                   3012:                         $forceedit = 1;
                   3013:                     }
                   3014:                     $cfile = $resurl;
1.1298    raeburn  3015:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3016:                 $incourse = 1;
                   3017:                 if ($env{'form.forceedit'}) {
                   3018:                     $forceview = 1;
                   3019:                 } else {
                   3020:                     $forceedit = 1;
                   3021:                 }
                   3022:                 $cfile = $resurl;
1.1199    raeburn  3023:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3024:                 $incourse = 1;
                   3025:                 $forceview = 1;
                   3026:                 if ($symb) {
                   3027:                     my ($map,$id,$res)=&decode_symb($symb);
                   3028:                     $env{'request.symb'} = $symb;
                   3029:                     $cfile = &clutter($res);
                   3030:                 } else {
                   3031:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3032:                     my $escfile = &unescape($cfile);
                   3033:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3034:                         $cfile = '/adm/wrapper'.$escfile;
                   3035:                     } else {
                   3036:                         $escfile =~ s{^http://}{};
                   3037:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3038:                     }
1.1199    raeburn  3039:                 }
1.1234    raeburn  3040:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3041:                 if ($env{'form.forceedit'}) {
                   3042:                     $forceview = 1;
                   3043:                 } else {
                   3044:                     $forceedit = 1;
                   3045:                 }
                   3046:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3047:             }
                   3048:         }
1.1194    raeburn  3049:         if ($uploaded || $incourse) {
                   3050:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3051:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3052:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3053:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3054:             # Check that the user has permission to edit this resource
                   3055:             my $setpriv = 1;
                   3056:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3057:             if (defined($cfudom)) {
                   3058:                 $home=&homeserver($cfuname,$cfudom);
                   3059:                 $cfile=$file;
                   3060:             }
                   3061:         }
1.1194    raeburn  3062:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3063:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3064:             my @ids=&current_machine_ids();
                   3065:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3066:                 $switchserver=1;
                   3067:             }
                   3068:         }
                   3069:     }
1.1194    raeburn  3070:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3071: }
                   3072: 
                   3073: sub is_course_upload {
                   3074:     my ($file,$cnum,$cdom) = @_;
                   3075:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3076:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3077:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3078:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3079:         return 1;
                   3080:     }
                   3081:     return;
                   3082: }
                   3083: 
1.1194    raeburn  3084: sub in_course {
1.1195    raeburn  3085:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3086:     if ($hideprivileged) {
                   3087:         my $skipuser;
1.1219    raeburn  3088:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3089:         my @possdoms = ($cdom);  
                   3090:         if ($coursehash{'checkforpriv'}) { 
                   3091:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3092:         }
                   3093:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3094:             $skipuser = 1;
                   3095:             if ($coursehash{'nothideprivileged'}) {
                   3096:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3097:                     my $user;
                   3098:                     if ($item =~ /:/) {
                   3099:                         $user = $item;
                   3100:                     } else {
                   3101:                         $user = join(':',split(/[\@]/,$item));
                   3102:                     }
                   3103:                     if ($user eq $uname.':'.$udom) {
                   3104:                         undef($skipuser);
                   3105:                         last;
                   3106:                     }
                   3107:                 }
                   3108:             }
                   3109:             if ($skipuser) {
                   3110:                 return 0;
                   3111:             }
                   3112:         }
                   3113:     }
1.1194    raeburn  3114:     $type ||= 'any';
                   3115:     if (!defined($cdom) || !defined($cnum)) {
                   3116:         my $cid  = $env{'request.course.id'};
                   3117:         $cdom = $env{'course.'.$cid.'.domain'};
                   3118:         $cnum = $env{'course.'.$cid.'.num'};
                   3119:     }
                   3120:     my $typesref;
1.1195    raeburn  3121:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3122:         $typesref = ['active','previous','future'];
                   3123:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3124:         $typesref = [$type];
                   3125:     }
                   3126:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3127:                               $typesref,undef,[$cdom]);
                   3128:     my ($tmp) = keys(%roles);
                   3129:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3130:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3131:     if (@course_roles > 0) {
                   3132:         return 1;
                   3133:     }
                   3134:     return 0;
                   3135: }
                   3136: 
1.478     albertel 3137: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3138: # input: action, courseID, current domain, intended
1.637     raeburn  3139: #        path to file, source of file, instruction to parse file for objects,
                   3140: #        ref to hash for embedded objects,
                   3141: #        ref to hash for codebase of java objects.
1.1095    raeburn  3142: #        reference to scalar to accommodate mime type determined
                   3143: #          from File::MMagic if $parser = parse.
1.637     raeburn  3144: #
1.485     raeburn  3145: # output: url to file (if action was uploaddoc), 
                   3146: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3147: #
1.478     albertel 3148: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3149: # course.
1.477     raeburn  3150: #
1.478     albertel 3151: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3152: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3153: #          course's home server.
1.477     raeburn  3154: #
1.478     albertel 3155: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3156: #          be copied from $source (current location) to 
                   3157: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3158: #         and will then be copied to
                   3159: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3160: #         course's home server.
1.485     raeburn  3161: #
1.481     raeburn  3162: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3163: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3164: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3165: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3166: #         in course's home server.
1.637     raeburn  3167: #
1.477     raeburn  3168: 
                   3169: sub process_coursefile {
1.1095    raeburn  3170:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3171:         $mimetype)=@_;
1.477     raeburn  3172:     my $fetchresult;
1.638     albertel 3173:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3174:     if ($action eq 'propagate') {
1.638     albertel 3175:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3176: 			     $home);
1.481     raeburn  3177:     } else {
1.477     raeburn  3178:         my $fpath = '';
                   3179:         my $fname = $file;
1.478     albertel 3180:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3181:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3182:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3183:         if ($action eq 'copy') {
                   3184:             if ($source eq '') {
                   3185:                 $fetchresult = 'no source file';
                   3186:                 return $fetchresult;
                   3187:             } else {
                   3188:                 my $destination = $filepath.'/'.$fname;
                   3189:                 rename($source,$destination);
                   3190:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3191:                                  $home);
1.481     raeburn  3192:             }
                   3193:         } elsif ($action eq 'uploaddoc') {
                   3194:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3195:             print $fh $env{'form.'.$source};
1.481     raeburn  3196:             close($fh);
1.637     raeburn  3197:             if ($parser eq 'parse') {
1.1024    raeburn  3198:                 my $mm = new File::MMagic;
1.1095    raeburn  3199:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3200:                 if ($type eq 'text/html') {
1.1024    raeburn  3201:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3202:                     unless ($parse_result eq 'ok') {
                   3203:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3204:                     }
1.637     raeburn  3205:                 }
1.1095    raeburn  3206:                 if (ref($mimetype)) {
                   3207:                     $$mimetype = $type;
                   3208:                 } 
1.637     raeburn  3209:             }
1.477     raeburn  3210:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3211:                                  $home);
1.481     raeburn  3212:             if ($fetchresult eq 'ok') {
                   3213:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3214:             } else {
                   3215:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3216:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3217:                 return '/adm/notfound.html';
                   3218:             }
1.477     raeburn  3219:         }
                   3220:     }
1.485     raeburn  3221:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3222:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3223:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3224:     }
                   3225:     return $fetchresult;
                   3226: }
                   3227: 
1.637     raeburn  3228: sub build_filepath {
                   3229:     my ($fpath) = @_;
                   3230:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3231:     unless ($fpath eq '') {
                   3232:         my @parts=split('/',$fpath);
                   3233:         foreach my $part (@parts) {
                   3234:             $filepath.= '/'.$part;
                   3235:             if ((-e $filepath)!=1) {
                   3236:                 mkdir($filepath,0777);
                   3237:             }
                   3238:         }
                   3239:     }
                   3240:     return $filepath;
                   3241: }
                   3242: 
                   3243: sub store_edited_file {
1.638     albertel 3244:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3245:     my $file = $primary_url;
                   3246:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3247:     my $fpath = '';
                   3248:     my $fname = $file;
                   3249:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3250:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3251:     my $filepath = &build_filepath($fpath);
                   3252:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3253:     print $fh $content;
                   3254:     close($fh);
1.638     albertel 3255:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3256:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3257: 			  $home);
1.637     raeburn  3258:     if ($$fetchresult eq 'ok') {
                   3259:         return '/uploaded/'.$fpath.'/'.$fname;
                   3260:     } else {
1.638     albertel 3261:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3262: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3263:         return '/adm/notfound.html';
                   3264:     }
                   3265: }
                   3266: 
1.531     albertel 3267: sub clean_filename {
1.831     albertel 3268:     my ($fname,$args)=@_;
1.315     www      3269: # Replace Windows backslashes by forward slashes
1.257     www      3270:     $fname=~s/\\/\//g;
1.831     albertel 3271:     if (!$args->{'keep_path'}) {
                   3272:         # Get rid of everything but the actual filename
                   3273: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3274:     }
1.315     www      3275: # Replace spaces by underscores
                   3276:     $fname=~s/\s+/\_/g;
                   3277: # Replace all other weird characters by nothing
1.831     albertel 3278:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3279: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3280: # numbers
                   3281:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3282:     return $fname;
                   3283: }
1.1051    raeburn  3284: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3285: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3286: # image with the same aspect ratio as the original, but with dimensions which do 
                   3287: # not exceed $resizewidth and $resizeheight.
                   3288:  
1.984     neumanie 3289: sub resizeImage {
1.1051    raeburn  3290:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3291:     my $ima = Image::Magick->new;
                   3292:     my $resized;
                   3293:     if (-e $img_path) {
                   3294:         $ima->Read($img_path);
                   3295:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3296:             my $width = $ima->Get('width');
                   3297:             my $height = $ima->Get('height');
                   3298:             if ($width > $resizewidth) {
                   3299: 	        my $factor = $width/$resizewidth;
                   3300:                 my $newheight = $height/$factor;
                   3301:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3302:                 $resized = 1;
                   3303:             }
                   3304:         }
                   3305:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3306:             my $width = $ima->Get('width');
                   3307:             my $height = $ima->Get('height');
                   3308:             if ($height > $resizeheight) {
                   3309:                 my $factor = $height/$resizeheight;
                   3310:                 my $newwidth = $width/$factor;
                   3311:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3312:                 $resized = 1;
                   3313:             }
                   3314:         }
                   3315:         if ($resized) {
                   3316:             $ima->Write($img_path);
                   3317:         }
                   3318:     }
                   3319:     return;
1.977     amueller 3320: }
                   3321: 
1.608     albertel 3322: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3323: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3324: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3325: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3326: #                                    canceloverwrite, or ''. 
                   3327: #                   if 'coursedoc': upload to the current course
                   3328: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3329: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3330: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3331: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3332: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3333: #        $allfiles - reference to hash for embedded objects
                   3334: #        $codebase - reference to hash for codebase of java objects
                   3335: #        $desuname - username for permanent storage of uploaded file
                   3336: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3337: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3338: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3339: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3340: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3341: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3342: #                    from File::MMagic.
1.858     raeburn  3343: # 
1.686     albertel 3344: # output: url of file in userspace, or error: <message> 
                   3345: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3346: 
1.531     albertel 3347: sub userfileupload {
1.1090    raeburn  3348:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3349:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3350:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3351:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3352:     $fname=&clean_filename($fname);
1.1090    raeburn  3353:     # See if there is anything left
1.257     www      3354:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3355:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3356:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3357:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3358:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3359:         my $now = time;
1.1090    raeburn  3360:         my $filepath;
1.1095    raeburn  3361:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3362:              $filepath = 'tmp/helprequests/'.$now;
                   3363:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3364:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3365:                          '_'.$env{'user.domain'}.'/pending';
                   3366:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3367:             my ($docuname,$docudom);
                   3368:             if ($destudom) {
                   3369:                 $docudom = $destudom;
                   3370:             } else {
                   3371:                 $docudom = $env{'user.domain'};
                   3372:             }
                   3373:             if ($destuname) {
                   3374:                 $docuname = $destuname;
                   3375:             } else {
                   3376:                 $docuname = $env{'user.name'};
                   3377:             }
                   3378:             if (exists($env{'form.group'})) {
                   3379:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3380:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3381:             }
                   3382:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3383:             if ($context eq 'canceloverwrite') {
                   3384:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3385:                 if (-e  $tempfile) {
                   3386:                     my @info = stat($tempfile);
                   3387:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3388:                         unlink($tempfile);
                   3389:                     }
                   3390:                 }
                   3391:                 return;
1.523     raeburn  3392:             }
                   3393:         }
1.1090    raeburn  3394:         # Create the directory if not present
1.741     raeburn  3395:         my @parts=split(/\//,$filepath);
                   3396:         my $fullpath = $perlvar{'lonDaemons'};
                   3397:         for (my $i=0;$i<@parts;$i++) {
                   3398:             $fullpath .= '/'.$parts[$i];
                   3399:             if ((-e $fullpath)!=1) {
                   3400:                 mkdir($fullpath,0777);
                   3401:             }
                   3402:         }
                   3403:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3404:         print $fh $env{'form.'.$formname};
                   3405:         close($fh);
1.1090    raeburn  3406:         if ($context eq 'existingfile') {
                   3407:             my @info = stat($fullpath.'/'.$fname);
                   3408:             return ($fullpath.'/'.$fname,$info[9]);
                   3409:         } else {
                   3410:             return $fullpath.'/'.$fname;
                   3411:         }
1.523     raeburn  3412:     }
1.995     raeburn  3413:     if ($subdir eq 'scantron') {
                   3414:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3415:     } else {
1.995     raeburn  3416:         $fname="$subdir/$fname";
                   3417:     }
1.1090    raeburn  3418:     if ($context eq 'coursedoc') {
1.638     albertel 3419: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3420: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3421:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3422:             return &finishuserfileupload($docuname,$docudom,
                   3423: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3424: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3425:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3426:         } else {
1.1218    raeburn  3427:             if ($env{'form.folder'}) {
                   3428:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3429:             }
1.638     albertel 3430:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3431: 				       $fname,$formname,$parser,
1.1095    raeburn  3432: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3433:         }
1.719     banghart 3434:     } elsif (defined($destuname)) {
                   3435:         my $docuname=$destuname;
                   3436:         my $docudom=$destudom;
1.860     raeburn  3437: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3438: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3439:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3440:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3441:     } else {
1.638     albertel 3442:         my $docuname=$env{'user.name'};
                   3443:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3444:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3445:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3446:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3447:         }
1.860     raeburn  3448: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3449: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3450:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3451:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3452:     }
1.271     www      3453: }
                   3454: 
                   3455: sub finishuserfileupload {
1.860     raeburn  3456:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3457:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3458:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3459:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3460:   
1.860     raeburn  3461:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3462:     $file=$fname;
                   3463:     if ($fname=~m|/|) {
                   3464:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3465: 	$path.=$fnamepath.'/';
                   3466:     }
1.259     www      3467:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3468:     my $count;
                   3469:     for ($count=4;$count<=$#parts;$count++) {
                   3470:         $filepath.="/$parts[$count]";
                   3471:         if ((-e $filepath)!=1) {
                   3472: 	    mkdir($filepath,0777);
                   3473:         }
                   3474:     }
1.984     neumanie 3475: 
1.258     www      3476: # Save the file
                   3477:     {
1.701     albertel 3478: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3479: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3480: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3481: 	    return '/adm/notfound.html';
                   3482: 	}
1.1090    raeburn  3483:         if ($context eq 'overwrite') {
1.1117    foxr     3484:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3485:             my $target = $filepath.'/'.$file;
                   3486:             if (-e $source) {
                   3487:                 my @info = stat($source);
                   3488:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3489:                     unless (&File::Copy::move($source,$target)) {
                   3490:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3491:                         return "Moving from $source failed";
                   3492:                     }
                   3493:                 } else {
                   3494:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3495:                 }
                   3496:             } else {
                   3497:                 return "Temporary file: $source missing";
                   3498:             }
                   3499:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3500: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3501: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3502: 	    return '/adm/notfound.html';
                   3503: 	}
1.570     albertel 3504: 	close(FH);
1.1051    raeburn  3505:         if ($resizewidth && $resizeheight) {
                   3506:             my $mm = new File::MMagic;
                   3507:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3508:             if ($mime_type =~ m{^image/}) {
                   3509: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3510:             }  
1.977     amueller 3511: 	}
1.258     www      3512:     }
1.1152    raeburn  3513:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3514:         if (ref($mimetype)) {
                   3515:             if ($$mimetype eq '') {
                   3516:                 my $mm = new File::MMagic;
                   3517:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3518:                 $$mimetype = $type;
                   3519:             }
                   3520:         }
                   3521:     }
1.637     raeburn  3522:     if ($parser eq 'parse') {
1.1152    raeburn  3523:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3524:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3525:                                                        $allfiles,$codebase);
                   3526:             unless ($parse_result eq 'ok') {
                   3527:                 &logthis('Failed to parse '.$filepath.$file.
                   3528: 	   	         ' for embedded media: '.$parse_result); 
                   3529:             }
1.637     raeburn  3530:         }
                   3531:     }
1.860     raeburn  3532:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3533:         my $input = $filepath.'/'.$file;
                   3534:         my $output = $filepath.'/'.'tn-'.$file;
                   3535:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3536:         system("convert -sample $thumbsize $input $output");
                   3537:         if (-e $filepath.'/'.'tn-'.$file) {
                   3538:             $fetchthumb  = 1; 
                   3539:         }
                   3540:     }
1.858     raeburn  3541:  
1.259     www      3542: # Notify homeserver to grep it
                   3543: #
1.984     neumanie 3544:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3545:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3546:     if ($fetchresult eq 'ok') {
1.860     raeburn  3547:         if ($fetchthumb) {
                   3548:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3549:             if ($thumbresult ne 'ok') {
                   3550:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3551:                          $docuhome.': '.$thumbresult);
                   3552:             }
                   3553:         }
1.259     www      3554: #
1.258     www      3555: # Return the URL to it
1.494     albertel 3556:         return '/uploaded/'.$path.$file;
1.263     www      3557:     } else {
1.494     albertel 3558:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3559: 		 ': '.$fetchresult);
1.263     www      3560:         return '/adm/notfound.html';
1.858     raeburn  3561:     }
1.493     albertel 3562: }
                   3563: 
1.637     raeburn  3564: sub extract_embedded_items {
1.961     raeburn  3565:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3566:     my @state = ();
1.1164    raeburn  3567:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3568:     my %javafiles = (
                   3569:                       codebase => '',
                   3570:                       code => '',
                   3571:                       archive => ''
                   3572:                     );
                   3573:     my %mediafiles = (
                   3574:                       src => '',
                   3575:                       movie => '',
                   3576:                      );
1.648     raeburn  3577:     my $p;
                   3578:     if ($content) {
                   3579:         $p = HTML::LCParser->new($content);
                   3580:     } else {
1.961     raeburn  3581:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3582:     }
1.641     albertel 3583:     while (my $t=$p->get_token()) {
1.640     albertel 3584: 	if ($t->[0] eq 'S') {
                   3585: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3586: 	    push(@state, $tagname);
1.648     raeburn  3587:             if (lc($tagname) eq 'allow') {
                   3588:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3589:             }
1.640     albertel 3590: 	    if (lc($tagname) eq 'img') {
                   3591: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3592: 	    }
1.886     albertel 3593: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3594:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3595:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3596:                 }
1.886     albertel 3597: 	    }
1.645     raeburn  3598:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3599:                 my $src;
1.645     raeburn  3600:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3601:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3602:                 } else {
1.1164    raeburn  3603:                     if ($attr->{'src'} ne '') {
                   3604:                         $src = $attr->{'src'};
                   3605:                         &add_filetype($allfiles,$src,'src');
                   3606:                     }
                   3607:                 }
                   3608:                 my $text = $p->get_trimmed_text();
                   3609:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3610:                     my @swfargs = split(/,/,$1);
                   3611:                     foreach my $item (@swfargs) {
                   3612:                         $item =~ s/["']//g;
                   3613:                         $item =~ s/^\s+//;
                   3614:                         $item =~ s/\s+$//;
                   3615:                     }
                   3616:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3617:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3618:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3619:                         } else {
                   3620:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3621:                         }
                   3622:                     }
1.645     raeburn  3623:                 }
                   3624:             }
                   3625:             if (lc($tagname) eq 'link') {
                   3626:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3627:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3628:                 }
                   3629:             }
1.640     albertel 3630: 	    if (lc($tagname) eq 'object' ||
                   3631: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3632: 		foreach my $item (keys(%javafiles)) {
                   3633: 		    $javafiles{$item} = '';
                   3634: 		}
1.1164    raeburn  3635:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3636:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3637:                 }
1.640     albertel 3638: 	    }
                   3639: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3640: 		my $name = lc($attr->{'name'});
                   3641: 		foreach my $item (keys(%javafiles)) {
                   3642: 		    if ($name eq $item) {
                   3643: 			$javafiles{$item} = $attr->{'value'};
                   3644: 			last;
                   3645: 		    }
                   3646: 		}
1.1164    raeburn  3647:                 my $pathfrom;
1.640     albertel 3648: 		foreach my $item (keys(%mediafiles)) {
                   3649: 		    if ($name eq $item) {
1.1164    raeburn  3650:                         $pathfrom = $attr->{'value'};
                   3651:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3652: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3653: 			last;
                   3654: 		    }
                   3655: 		}
1.1164    raeburn  3656:                 if ($name eq 'flashvars') {
                   3657:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3658:                 }
                   3659:                 if ($pathfrom ne '') {
                   3660:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3661:                                          $pathfrom);
                   3662:                 }
1.640     albertel 3663: 	    }
                   3664: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3665: 		foreach my $item (keys(%javafiles)) {
                   3666: 		    if ($attr->{$item}) {
                   3667: 			$javafiles{$item} = $attr->{$item};
                   3668: 			last;
                   3669: 		    }
                   3670: 		}
                   3671: 		foreach my $item (keys(%mediafiles)) {
                   3672: 		    if ($attr->{$item}) {
                   3673: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3674: 			last;
                   3675: 		    }
                   3676: 		}
1.1164    raeburn  3677:                 if (lc($tagname) eq 'embed') {
                   3678:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3679:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3680:                                              $attr->{'src'});
                   3681:                     }
                   3682:                 }
1.640     albertel 3683: 	    }
1.1243    raeburn  3684:             if (lc($tagname) eq 'iframe') {
                   3685:                 my $src = $attr->{'src'} ;
                   3686:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3687:                     &add_filetype($allfiles,$src,'src');
                   3688:                 } elsif ($src =~ m{^/}) {
                   3689:                     if ($env{'request.course.id'}) {
                   3690:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3691:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3692:                         my $url = &hreflocation('',$fullpath);
                   3693:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3694:                             my $relpath = $1;
                   3695:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3696:                                 &add_filetype($allfiles,$1,'src');
                   3697:                             }
                   3698:                         }
                   3699:                     }
                   3700:                 }
                   3701:             }
1.1164    raeburn  3702:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3703:                 pop(@state);
1.1164    raeburn  3704:             }
1.640     albertel 3705: 	} elsif ($t->[0] eq 'E') {
                   3706: 	    my ($tagname) = ($t->[1]);
                   3707: 	    if ($javafiles{'codebase'} ne '') {
                   3708: 		$javafiles{'codebase'} .= '/';
                   3709: 	    }  
                   3710: 	    if (lc($tagname) eq 'applet' ||
                   3711: 		lc($tagname) eq 'object' ||
                   3712: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3713: 		) {
                   3714: 		foreach my $item (keys(%javafiles)) {
                   3715: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3716: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3717: 			&add_filetype($allfiles,$file,$item);
                   3718: 		    }
                   3719: 		}
                   3720: 	    } 
                   3721: 	    pop @state;
                   3722: 	}
                   3723:     }
1.1164    raeburn  3724:     foreach my $id (sort(keys(%flashvars))) {
                   3725:         if ($shockwave{$id} ne '') {
                   3726:             my @pairs = split(/\&/,$flashvars{$id});
                   3727:             foreach my $pair (@pairs) {
                   3728:                 my ($key,$value) = split(/\=/,$pair);
                   3729:                 if ($key eq 'thumb') {
                   3730:                     &add_filetype($allfiles,$value,$key);
                   3731:                 } elsif ($key eq 'content') {
                   3732:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3733:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3734:                     if ($ext ne '') {
                   3735:                         &add_filetype($allfiles,$path.$value,$ext);
                   3736:                     }
                   3737:                 }
                   3738:             }
                   3739:         }
                   3740:     }
1.637     raeburn  3741:     return 'ok';
                   3742: }
                   3743: 
1.639     albertel 3744: sub add_filetype {
                   3745:     my ($allfiles,$file,$type)=@_;
                   3746:     if (exists($allfiles->{$file})) {
                   3747: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3748: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3749: 	}
                   3750:     } else {
                   3751: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3752:     }
                   3753: }
                   3754: 
1.1164    raeburn  3755: sub embedded_dependency {
                   3756:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3757:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3758:         if (($identifier ne '') &&
                   3759:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3760:             ($pathfrom ne '')) {
                   3761:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3762:             foreach my $dep (@{$related->{$identifier}}) {
                   3763:                 &add_filetype($allfiles,$path.$dep,'object');
                   3764:             }
                   3765:         }
                   3766:     }
                   3767:     return;
                   3768: }
                   3769: 
1.493     albertel 3770: sub removeuploadedurl {
1.984     neumanie 3771:     my ($url)=@_;	
                   3772:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3773:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3774: }
                   3775: 
                   3776: sub removeuserfile {
                   3777:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3778:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3779:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3780:     if ($result eq 'ok') {	
1.798     raeburn  3781:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3782:             my $metafile = $fname.'.meta';
                   3783:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3784: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3785:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3786:             my $sqlresult = 
1.823     albertel 3787:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3788:                                         'portfolio_metadata',$group,
                   3789:                                         'delete');
1.798     raeburn  3790:         }
                   3791:     }
                   3792:     return $result;
1.257     www      3793: }
1.15      www      3794: 
1.530     albertel 3795: sub mkdiruserfile {
                   3796:     my ($docuname,$docudom,$dir)=@_;
                   3797:     my $home=&homeserver($docuname,$docudom);
                   3798:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3799: }
                   3800: 
1.531     albertel 3801: sub renameuserfile {
                   3802:     my ($docuname,$docudom,$old,$new)=@_;
                   3803:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3804:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3805:                         &escape("$old").':'.&escape("$new"),$home);
                   3806:     if ($result eq 'ok') {
                   3807:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3808:             my $oldmeta = $old.'.meta';
                   3809:             my $newmeta = $new.'.meta';
                   3810:             my $metaresult = 
                   3811:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3812: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3813:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3814:             my $sqlresult = 
1.823     albertel 3815:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3816:                                         'portfolio_metadata',$group,
                   3817:                                         'delete');
1.798     raeburn  3818:         }
                   3819:     }
                   3820:     return $result;
1.531     albertel 3821: }
                   3822: 
1.14      www      3823: # ------------------------------------------------------------------------- Log
                   3824: 
                   3825: sub log {
                   3826:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3827:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3828: }
                   3829: 
                   3830: # ------------------------------------------------------------------ Course Log
1.352     www      3831: #
                   3832: # This routine flushes several buffers of non-mission-critical nature
                   3833: #
1.157     www      3834: 
                   3835: sub flushcourselogs {
1.352     www      3836:     &logthis('Flushing log buffers');
                   3837: #
                   3838: # course logs
                   3839: # This is a log of all transactions in a course, which can be used
                   3840: # for data mining purposes
                   3841: #
                   3842: # It also collects the courseid database, which lists last transaction
                   3843: # times and course titles for all courseids
                   3844: #
                   3845:     my %courseidbuffer=();
1.921     raeburn  3846:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3847:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3848: 		          &escape($courselogs{$crsid}),
                   3849: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3850: 	    delete $courselogs{$crsid};
                   3851:         } else {
                   3852:             &logthis('Failed to flush log buffer for '.$crsid);
                   3853:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3854:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3855:                         " exceeded maximum size, deleting.</font>");
                   3856:                delete $courselogs{$crsid};
                   3857:             }
1.352     www      3858:         }
1.920     raeburn  3859:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3860:             'description' => $coursedescrbuf{$crsid},
                   3861:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3862:             'type'        => $coursetypebuf{$crsid},
                   3863:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3864:         };
1.191     harris41 3865:     }
1.352     www      3866: #
                   3867: # Write course id database (reverse lookup) to homeserver of courses 
                   3868: # Is used in pickcourse
                   3869: #
1.840     albertel 3870:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3871:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3872:                                     $courseidbuffer{$crs_home},
                   3873:                                     $crs_home,'timeonly');
1.352     www      3874:     }
                   3875: #
                   3876: # File accesses
                   3877: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3878: #
1.449     matthew  3879:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3880:         if ($entry =~ /___count$/) {
                   3881:             my ($dom,$name);
1.807     albertel 3882:             ($dom,$name,undef)=
1.811     albertel 3883: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3884:             if (! defined($dom) || $dom eq '' || 
                   3885:                 ! defined($name) || $name eq '') {
1.620     albertel 3886:                 my $cid = $env{'request.course.id'};
                   3887:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3888:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3889:             }
1.450     matthew  3890:             my $value = $accesshash{$entry};
                   3891:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3892:             my %temphash=($url => $value);
1.449     matthew  3893:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3894:             if ($result eq 'ok') {
                   3895:                 delete $accesshash{$entry};
                   3896:             }
                   3897:         } else {
1.811     albertel 3898:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3899:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3900:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3901:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3902:                 delete $accesshash{$entry};
                   3903:             }
1.185     www      3904:         }
1.191     harris41 3905:     }
1.352     www      3906: #
                   3907: # Roles
                   3908: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3909: #
1.800     albertel 3910:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3911:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3912: 	    split(/\:/,$entry);
                   3913:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3914:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3915:                 $rudom,$runame) eq 'ok') {
                   3916: 	    delete $userrolehash{$entry};
                   3917:         }
                   3918:     }
1.662     raeburn  3919: #
                   3920: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3921: #
                   3922:     my %domrolebuffer = ();
1.1000    raeburn  3923:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3924:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3925:         if ($domrolebuffer{$rudom}) {
                   3926:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3927:                       '='.&escape($domainrolehash{$entry});
                   3928:         } else {
                   3929:             $domrolebuffer{$rudom}.=&escape($entry).
                   3930:                       '='.&escape($domainrolehash{$entry});
                   3931:         }
                   3932:         delete $domainrolehash{$entry};
                   3933:     }
                   3934:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3935: 	my %servers = &get_servers($dom,'library');
                   3936: 	foreach my $tryserver (keys(%servers)) {
                   3937: 	    unless (&reply('domroleput:'.$dom.':'.
                   3938: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3939: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3940: 	    }
1.662     raeburn  3941:         }
                   3942:     }
1.186     www      3943:     $dumpcount++;
1.157     www      3944: }
                   3945: 
                   3946: sub courselog {
                   3947:     my $what=shift;
1.158     www      3948:     $what=time.':'.$what;
1.620     albertel 3949:     unless ($env{'request.course.id'}) { return ''; }
                   3950:     $coursedombuf{$env{'request.course.id'}}=
                   3951:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3952:     $coursenumbuf{$env{'request.course.id'}}=
                   3953:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3954:     $coursehombuf{$env{'request.course.id'}}=
                   3955:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3956:     $coursedescrbuf{$env{'request.course.id'}}=
                   3957:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3958:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3959:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3960:     $courseownerbuf{$env{'request.course.id'}}=
                   3961:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3962:     $coursetypebuf{$env{'request.course.id'}}=
                   3963:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3964:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3965: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3966:     } else {
1.620     albertel 3967: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3968:     }
1.620     albertel 3969:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3970: 	&flushcourselogs();
                   3971:     }
1.158     www      3972: }
                   3973: 
                   3974: sub courseacclog {
                   3975:     my $fnsymb=shift;
1.620     albertel 3976:     unless ($env{'request.course.id'}) { return ''; }
                   3977:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3978:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3979:         $what.=':POST';
1.583     matthew  3980:         # FIXME: Probably ought to escape things....
1.800     albertel 3981: 	foreach my $key (keys(%env)) {
                   3982:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3983:                 my $formitem = $1;
                   3984:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3985:                     $what.=':'.$formitem.'='.$env{$key};
                   3986:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3987:                     $what.=':'.$formitem.'='.$env{$key};
                   3988:                 }
1.158     www      3989:             }
1.191     harris41 3990:         }
1.583     matthew  3991:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3992:         # FIXME: We should not be depending on a form parameter that someone
                   3993:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3994:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3995:             $what.= ':POST';
                   3996:             # FIXME: Probably ought to escape things....
                   3997:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3998:                                  'crsdiscuss') {
1.620     albertel 3999:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4000:             }
                   4001:         }
1.158     www      4002:     }
                   4003:     &courselog($what);
1.149     www      4004: }
                   4005: 
1.185     www      4006: sub countacc {
                   4007:     my $url=&declutter(shift);
1.458     matthew  4008:     return if (! defined($url) || $url eq '');
1.620     albertel 4009:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4010: #
                   4011: # Mark that this url was used in this course
                   4012: #
1.620     albertel 4013:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4014: #
                   4015: # Increase the access count for this resource in this child process
                   4016: #
1.281     www      4017:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4018:     $accesshash{$key}++;
1.185     www      4019: }
1.349     www      4020: 
1.361     www      4021: sub linklog {
                   4022:     my ($from,$to)=@_;
                   4023:     $from=&declutter($from);
                   4024:     $to=&declutter($to);
                   4025:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4026:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4027: }
1.1160    www      4028: 
                   4029: sub statslog {
                   4030:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4031:     if ($users<2) { return; }
                   4032:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4033:             'course'       => $env{'request.course.id'},
                   4034:             'sections'     => '"all"',
                   4035:             'num_students' => $users,
                   4036:             'part'         => $part,
                   4037:             'symb'         => $symb,
                   4038:             'mean_tries'   => $av_attempts,
                   4039:             'deg_of_diff'  => $degdiff});
                   4040:     foreach my $key (keys(%dynstore)) {
                   4041:         $accesshash{$key}=$dynstore{$key};
                   4042:     }
                   4043: }
1.361     www      4044:   
1.349     www      4045: sub userrolelog {
                   4046:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4047:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4048:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4049:        $userrolehash
                   4050:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4051:                     =$tend.':'.$tstart;
1.662     raeburn  4052:     }
1.1169    droeschl 4053:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4054:        $userrolehash
                   4055:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4056:                     =$tend.':'.$tstart;
                   4057:     }
1.1169    droeschl 4058:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  4059:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4060:        $domainrolehash
                   4061:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4062:                     = $tend.':'.$tstart;
                   4063:     }
1.351     www      4064: }
                   4065: 
1.957     raeburn  4066: sub courserolelog {
                   4067:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4068:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4069:         my $cdom = $1;
                   4070:         my $cnum = $2;
                   4071:         my $sec = $3;
                   4072:         my $namespace = 'rolelog';
                   4073:         my %storehash = (
                   4074:                            role    => $trole,
                   4075:                            start   => $tstart,
                   4076:                            end     => $tend,
                   4077:                            selfenroll => $selfenroll,
                   4078:                            context    => $context,
                   4079:                         );
                   4080:         if ($trole eq 'gr') {
                   4081:             $namespace = 'groupslog';
                   4082:             $storehash{'group'} = $sec;
                   4083:         } else {
                   4084:             $storehash{'section'} = $sec;
                   4085:         }
1.1188    raeburn  4086:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4087:                    $domain,$cnum,$cdom);
1.1184    raeburn  4088:         if (($trole ne 'st') || ($sec ne '')) {
                   4089:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4090:         }
                   4091:     }
                   4092:     return;
                   4093: }
                   4094: 
1.1184    raeburn  4095: sub domainrolelog {
                   4096:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4097:     if ($area =~ m{^/($match_domain)/$}) {
                   4098:         my $cdom = $1;
                   4099:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4100:         my $namespace = 'rolelog';
                   4101:         my %storehash = (
                   4102:                            role    => $trole,
                   4103:                            start   => $tstart,
                   4104:                            end     => $tend,
                   4105:                            context => $context,
                   4106:                         );
1.1188    raeburn  4107:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4108:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4109:     }
                   4110:     return;
                   4111: 
                   4112: }
                   4113: 
                   4114: sub coauthorrolelog {
                   4115:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4116:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4117:         my $audom = $1;
                   4118:         my $auname = $2;
                   4119:         my $namespace = 'rolelog';
                   4120:         my %storehash = (
                   4121:                            role    => $trole,
                   4122:                            start   => $tstart,
                   4123:                            end     => $tend,
                   4124:                            context => $context,
                   4125:                         );
1.1188    raeburn  4126:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4127:                    $domain,$auname,$audom);
1.1184    raeburn  4128:     }
                   4129:     return;
                   4130: }
                   4131: 
1.351     www      4132: sub get_course_adv_roles {
1.948     raeburn  4133:     my ($cid,$codes) = @_;
1.620     albertel 4134:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4135:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4136:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4137:     my %nothide=();
1.800     albertel 4138:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4139:         if ($user !~ /:/) {
                   4140: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4141:         } else {
                   4142:             $nothide{$user}=1;
                   4143:         }
1.470     www      4144:     }
1.1219    raeburn  4145:     my @possdoms = ($coursehash{'domain'});
                   4146:     if ($coursehash{'checkforpriv'}) {
                   4147:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4148:     }
1.351     www      4149:     my %returnhash=();
                   4150:     my %dumphash=
                   4151:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4152:     my $now=time;
1.997     raeburn  4153:     my %privileged;
1.1000    raeburn  4154:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4155: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4156:         if (($tstart) && ($tstart<0)) { next; }
                   4157:         if (($tend) && ($tend<$now)) { next; }
                   4158:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4159:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4160: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4161:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4162:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4163: 	if ($role eq 'cr') { next; }
1.948     raeburn  4164:         if ($codes) {
                   4165:             if ($section) { $role .= ':'.$section; }
                   4166:             if ($returnhash{$role}) {
                   4167:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4168:             } else {
                   4169:                 $returnhash{$role}=$username.':'.$domain;
                   4170:             }
1.351     www      4171:         } else {
1.988     raeburn  4172:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4173:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4174:             if ($returnhash{$key}) {
                   4175: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4176:             } else {
                   4177:                 $returnhash{$key}=$username.':'.$domain;
                   4178:             }
1.351     www      4179:         }
1.948     raeburn  4180:     }
1.400     www      4181:     return %returnhash;
                   4182: }
                   4183: 
                   4184: sub get_my_roles {
1.937     raeburn  4185:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4186:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4187:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4188:     my (%dumphash,%nothide);
1.1086    raeburn  4189:     if ($context eq 'userroles') {
1.1166    raeburn  4190:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4191:     } else {
1.1219    raeburn  4192:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4193:         if ($hidepriv) {
                   4194:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4195:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4196:                 if ($user !~ /:/) {
                   4197:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4198:                 } else {
                   4199:                     $nothide{$user} = 1;
                   4200:                 }
                   4201:             }
                   4202:         }
1.858     raeburn  4203:     }
1.400     www      4204:     my %returnhash=();
                   4205:     my $now=time;
1.999     raeburn  4206:     my %privileged;
1.800     albertel 4207:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4208:         my ($role,$tend,$tstart);
                   4209:         if ($context eq 'userroles') {
1.1149    raeburn  4210:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4211: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4212:         } else {
                   4213:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4214:         }
1.400     www      4215:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4216:         my $status = 'active';
1.939     raeburn  4217:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4218:             $status = 'previous';
                   4219:         } 
                   4220:         if (($tstart) && ($now<$tstart)) {
                   4221:             $status = 'future';
                   4222:         }
                   4223:         if (ref($types) eq 'ARRAY') {
                   4224:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4225:                 next;
                   4226:             } 
                   4227:         } else {
                   4228:             if ($status ne 'active') {
                   4229:                 next;
                   4230:             }
                   4231:         }
1.867     raeburn  4232:         my ($rolecode,$username,$domain,$section,$area);
                   4233:         if ($context eq 'userroles') {
1.1186    raeburn  4234:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4235:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4236:         } else {
                   4237:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4238:         }
1.832     raeburn  4239:         if (ref($roledoms) eq 'ARRAY') {
                   4240:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4241:                 next;
                   4242:             }
                   4243:         }
                   4244:         if (ref($roles) eq 'ARRAY') {
                   4245:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4246:                 if ($role =~ /^cr\//) {
                   4247:                     if (!grep(/^cr$/,@{$roles})) {
                   4248:                         next;
                   4249:                     }
1.1104    raeburn  4250:                 } elsif ($role =~ /^gr\//) {
                   4251:                     if (!grep(/^gr$/,@{$roles})) {
                   4252:                         next;
                   4253:                     }
1.922     raeburn  4254:                 } else {
                   4255:                     next;
                   4256:                 }
1.832     raeburn  4257:             }
1.867     raeburn  4258:         }
1.937     raeburn  4259:         if ($hidepriv) {
1.1219    raeburn  4260:             my @privroles = ('dc','su');
1.999     raeburn  4261:             if ($context eq 'userroles') {
1.1219    raeburn  4262:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4263:             } else {
1.1219    raeburn  4264:                 my $possdoms = [$domain];
                   4265:                 if (ref($roledoms) eq 'ARRAY') {
                   4266:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4267:                 }
1.1219    raeburn  4268:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4269:                     if (!$nothide{$username.':'.$domain}) {
                   4270:                         next;
                   4271:                     }
                   4272:                 }
1.937     raeburn  4273:             }
                   4274:         }
1.933     raeburn  4275:         if ($withsec) {
                   4276:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4277:                 $tstart.':'.$tend;
                   4278:         } else {
                   4279:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4280:         }
1.832     raeburn  4281:     }
1.373     www      4282:     return %returnhash;
1.399     www      4283: }
                   4284: 
                   4285: # ----------------------------------------------------- Frontpage Announcements
                   4286: #
                   4287: #
                   4288: 
                   4289: sub postannounce {
                   4290:     my ($server,$text)=@_;
1.844     albertel 4291:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4292:     unless ($text=~/\w/) { $text=''; }
                   4293:     return &reply('setannounce:'.&escape($text),$server);
                   4294: }
                   4295: 
                   4296: sub getannounce {
1.448     albertel 4297: 
                   4298:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4299: 	my $announcement='';
1.800     albertel 4300: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4301: 	close($fh);
1.399     www      4302: 	if ($announcement=~/\w/) { 
                   4303: 	    return 
                   4304:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4305:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4306: 	} else {
                   4307: 	    return '';
                   4308: 	}
                   4309:     } else {
                   4310: 	return '';
                   4311:     }
1.351     www      4312: }
1.353     www      4313: 
                   4314: # ---------------------------------------------------------- Course ID routines
                   4315: # Deal with domain's nohist_courseid.db files
                   4316: #
                   4317: 
                   4318: sub courseidput {
1.921     raeburn  4319:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4320:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4321:     my $outcome;
                   4322:     if ($caller eq 'timeonly') {
                   4323:         my $cids = '';
                   4324:         foreach my $item (keys(%$storehash)) {
                   4325:             $cids.=&escape($item).'&';
                   4326:         }
                   4327:         $cids=~s/\&$//;
                   4328:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4329:                           $coursehome);       
                   4330:     } else {
                   4331:         my $items = '';
                   4332:         foreach my $item (keys(%$storehash)) {
                   4333:             $items.= &escape($item).'='.
                   4334:                      &freeze_escape($$storehash{$item}).'&';
                   4335:         }
                   4336:         $items=~s/\&$//;
                   4337:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4338:                           $coursehome);
1.918     raeburn  4339:     }
                   4340:     if ($outcome eq 'unknown_cmd') {
                   4341:         my $what;
                   4342:         foreach my $cid (keys(%$storehash)) {
                   4343:             $what .= &escape($cid).'=';
1.921     raeburn  4344:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4345:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4346:             }
                   4347:             $what =~ s/\:$/&/;
                   4348:         }
                   4349:         $what =~ s/\&$//;  
                   4350:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4351:     } else {
                   4352:         return $outcome;
                   4353:     }
1.353     www      4354: }
                   4355: 
                   4356: sub courseiddump {
1.921     raeburn  4357:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4358:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4359:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4360:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4361:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4362:     my $as_hash = 1;
                   4363:     my %returnhash;
                   4364:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4365:     my %libserv = &all_library();
                   4366:     foreach my $tryserver (keys(%libserv)) {
                   4367:         if ( (  $hostidflag == 1 
                   4368: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4369: 	     || (!defined($hostidflag)) ) {
                   4370: 
1.918     raeburn  4371: 	    if (($domfilter eq '') ||
                   4372: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4373:                 my $rep;
                   4374:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4375:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4376:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4377:                                 &escape($descfilter), &escape($instcodefilter), 
                   4378:                                 &escape($ownerfilter), &escape($coursefilter),
                   4379:                                 &escape($typefilter), &escape($regexp_ok), 
                   4380:                                 $as_hash, &escape($selfenrollonly), 
                   4381:                                 &escape($catfilter), $showhidden, $caller, 
                   4382:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4383:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  4384:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4385:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 4386:                 } else {
                   4387:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4388:                              $sincefilter.':'.&escape($descfilter).':'.
                   4389:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4390:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4391:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4392:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4393:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4394:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4395:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  4396:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4397:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 4398:                 }
                   4399:                      
1.918     raeburn  4400:                 my @pairs=split(/\&/,$rep);
                   4401:                 foreach my $item (@pairs) {
                   4402:                     my ($key,$value)=split(/\=/,$item,2);
                   4403:                     $key = &unescape($key);
                   4404:                     next if ($key =~ /^error: 2 /);
                   4405:                     my $result = &thaw_unescape($value);
                   4406:                     if (ref($result) eq 'HASH') {
                   4407:                         $returnhash{$key}=$result;
                   4408:                     } else {
1.921     raeburn  4409:                         my @responses = split(/:/,$value);
                   4410:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4411:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4412:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4413:                         }
1.1008    raeburn  4414:                     }
1.353     www      4415:                 }
                   4416:             }
                   4417:         }
                   4418:     }
                   4419:     return %returnhash;
                   4420: }
                   4421: 
1.1055    raeburn  4422: sub courselastaccess {
                   4423:     my ($cdom,$cnum,$hostidref) = @_;
                   4424:     my %returnhash;
                   4425:     if ($cdom && $cnum) {
                   4426:         my $chome = &homeserver($cnum,$cdom);
                   4427:         if ($chome ne 'no_host') {
                   4428:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4429:             &extract_lastaccess(\%returnhash,$rep);
                   4430:         }
                   4431:     } else {
                   4432:         if (!$cdom) { $cdom=''; }
                   4433:         my %libserv = &all_library();
                   4434:         foreach my $tryserver (keys(%libserv)) {
                   4435:             if (ref($hostidref) eq 'ARRAY') {
                   4436:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4437:             } 
                   4438:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4439:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4440:                 &extract_lastaccess(\%returnhash,$rep);
                   4441:             }
                   4442:         }
                   4443:     }
                   4444:     return %returnhash;
                   4445: }
                   4446: 
                   4447: sub extract_lastaccess {
                   4448:     my ($returnhash,$rep) = @_;
                   4449:     if (ref($returnhash) eq 'HASH') {
                   4450:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4451:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4452:                  $rep eq '') {
                   4453:             my @pairs=split(/\&/,$rep);
                   4454:             foreach my $item (@pairs) {
                   4455:                 my ($key,$value)=split(/\=/,$item,2);
                   4456:                 $key = &unescape($key);
                   4457:                 next if ($key =~ /^error: 2 /);
                   4458:                 $returnhash->{$key} = &thaw_unescape($value);
                   4459:             }
                   4460:         }
                   4461:     }
                   4462:     return;
                   4463: }
                   4464: 
1.658     raeburn  4465: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4466: 
                   4467: sub dcmailput {
1.685     raeburn  4468:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4469:     my $status = &Apache::lonnet::critical(
1.740     www      4470:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4471:        &escape($message),$server);
1.662     raeburn  4472:     return $status;
                   4473: }
                   4474: 
1.658     raeburn  4475: sub dcmaildump {
                   4476:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4477:     my %returnhash=();
1.846     albertel 4478: 
                   4479:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4480:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4481:                                                          &escape($enddate).':';
                   4482: 	my @esc_senders=map { &escape($_)} @$senders;
                   4483: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4484: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4485:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4486:             if (($key) && ($value)) {
                   4487:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4488:             }
                   4489:         }
                   4490:     }
                   4491:     return %returnhash;
                   4492: }
1.662     raeburn  4493: # ---------------------------------------------------------- Domain roles
                   4494: 
                   4495: sub get_domain_roles {
                   4496:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4497:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4498:         $startdate = '.';
                   4499:     }
1.1018    raeburn  4500:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4501:         $enddate = '.';
                   4502:     }
1.922     raeburn  4503:     my $rolelist;
                   4504:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4505:         $rolelist = join('&',@{$roles});
1.922     raeburn  4506:     }
1.662     raeburn  4507:     my %personnel = ();
1.841     albertel 4508: 
                   4509:     my %servers = &get_servers($dom,'library');
                   4510:     foreach my $tryserver (keys(%servers)) {
                   4511: 	%{$personnel{$tryserver}}=();
                   4512: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4513: 					    &escape($startdate).':'.
                   4514: 					    &escape($enddate).':'.
                   4515: 					    &escape($rolelist), $tryserver))) {
                   4516: 	    my ($key,$value) = split(/\=/,$line,2);
                   4517: 	    if (($key) && ($value)) {
                   4518: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4519: 	    }
                   4520: 	}
1.662     raeburn  4521:     }
                   4522:     return %personnel;
                   4523: }
1.658     raeburn  4524: 
1.1057    www      4525: # ----------------------------------------------------------- Interval timing 
1.149     www      4526: 
1.1153    www      4527: {
                   4528: # Caches needed for speedup of navmaps
                   4529: # We don't want to cache this for very long at all (5 seconds at most)
                   4530: # 
                   4531: # The user for whom we cache
                   4532: my $cachedkey='';
                   4533: # The cached times for this user
                   4534: my %cachedtimes=();
                   4535: # When this was last done
1.1282    raeburn  4536: my $cachedtime='';
1.1153    www      4537: 
                   4538: sub load_all_first_access {
1.1154    raeburn  4539:     my ($uname,$udom)=@_;
1.1156    www      4540:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4541:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4542:         return;
                   4543:     }
                   4544:     $cachedtime=time;
                   4545:     $cachedkey=$uname.':'.$udom;
                   4546:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4547: }
                   4548: 
1.504     albertel 4549: sub get_first_access {
1.1162    raeburn  4550:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4551:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4552:     if ($argsymb) { $symb=$argsymb; }
                   4553:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4554:     if ($argmap) { $map = $argmap; }
1.926     albertel 4555:     if ($type eq 'course') {
                   4556: 	$res='course';
                   4557:     } elsif ($type eq 'map') {
1.588     albertel 4558: 	$res=&symbread($map);
                   4559:     } else {
                   4560: 	$res=$symb;
                   4561:     }
1.1153    www      4562:     &load_all_first_access($uname,$udom);
                   4563:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4564: }
                   4565: 
                   4566: sub set_first_access {
1.1162    raeburn  4567:     my ($type,$interval)=@_;
1.790     albertel 4568:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4569:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4570:     if ($type eq 'course') {
                   4571: 	$res='course';
                   4572:     } elsif ($type eq 'map') {
1.588     albertel 4573: 	$res=&symbread($map);
                   4574:     } else {
                   4575: 	$res=$symb;
                   4576:     }
1.1153    www      4577:     $cachedkey='';
1.1162    raeburn  4578:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4579:     if (!$firstaccess) {
1.1162    raeburn  4580:         my $start = time;
                   4581: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4582:                           $udom,$uname);
                   4583:         if ($putres eq 'ok') {
                   4584:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4585:                  $udom,$uname); 
                   4586:             &appenv(
                   4587:                      {
                   4588:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4589:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4590:                      }
                   4591:                   );
                   4592:         }
                   4593:         return $putres;
1.505     albertel 4594:     }
                   4595:     return 'already_set';
1.504     albertel 4596: }
1.1153    www      4597: }
1.1282    raeburn  4598: 
1.110     www      4599: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4600: 
                   4601: sub expirespread {
                   4602:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4603:     my $cid=$env{'request.course.id'}; 
1.110     www      4604:     if ($cid) {
                   4605:        my $now=time;
                   4606:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4607:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4608:                             $env{'course.'.$cid.'.num'}.
1.110     www      4609: 	        	    ':nohist_expirationdates:'.
                   4610:                             &escape($key).'='.$now,
1.620     albertel 4611:                             $env{'course.'.$cid.'.home'})
1.110     www      4612:     }
                   4613:     return 'ok';
1.14      www      4614: }
                   4615: 
1.109     www      4616: # ----------------------------------------------------- Devalidate Spreadsheets
                   4617: 
                   4618: sub devalidate {
1.325     www      4619:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4620:     my $cid=$env{'request.course.id'}; 
1.109     www      4621:     if ($cid) {
1.391     matthew  4622:         # delete the stored spreadsheets for
                   4623:         # - the student level sheet of this user in course's homespace
                   4624:         # - the assessment level sheet for this resource 
                   4625:         #   for this user in user's homespace
1.553     albertel 4626: 	# - current conditional state info
1.325     www      4627: 	my $key=$uname.':'.$udom.':';
1.109     www      4628:         my $status=
1.299     matthew  4629: 	    &del('nohist_calculatedsheets',
1.391     matthew  4630: 		 [$key.'studentcalc:'],
1.620     albertel 4631: 		 $env{'course.'.$cid.'.domain'},
                   4632: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4633: 		.' '.
                   4634: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4635: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4636:         unless ($status eq 'ok ok') {
                   4637:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4638:                     $uname.' at '.$udom.' for '.
1.109     www      4639: 		    $symb.': '.$status);
1.133     albertel 4640:         }
1.553     albertel 4641: 	&delenv('user.state.'.$cid);
1.109     www      4642:     }
                   4643: }
                   4644: 
1.265     albertel 4645: sub get_scalar {
                   4646:     my ($string,$end) = @_;
                   4647:     my $value;
                   4648:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4649: 	$value = $1;
                   4650:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4651: 	$value = $1;
                   4652:     }
                   4653:     return &unescape($value);
                   4654: }
                   4655: 
                   4656: sub array2str {
                   4657:   my (@array) = @_;
                   4658:   my $result=&arrayref2str(\@array);
                   4659:   $result=~s/^__ARRAY_REF__//;
                   4660:   $result=~s/__END_ARRAY_REF__$//;
                   4661:   return $result;
                   4662: }
                   4663: 
1.204     albertel 4664: sub arrayref2str {
                   4665:   my ($arrayref) = @_;
1.265     albertel 4666:   my $result='__ARRAY_REF__';
1.204     albertel 4667:   foreach my $elem (@$arrayref) {
1.265     albertel 4668:     if(ref($elem) eq 'ARRAY') {
                   4669:       $result.=&arrayref2str($elem).'&';
                   4670:     } elsif(ref($elem) eq 'HASH') {
                   4671:       $result.=&hashref2str($elem).'&';
                   4672:     } elsif(ref($elem)) {
                   4673:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4674:     } else {
                   4675:       $result.=&escape($elem).'&';
                   4676:     }
                   4677:   }
                   4678:   $result=~s/\&$//;
1.265     albertel 4679:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4680:   return $result;
                   4681: }
                   4682: 
1.168     albertel 4683: sub hash2str {
1.204     albertel 4684:   my (%hash) = @_;
                   4685:   my $result=&hashref2str(\%hash);
1.265     albertel 4686:   $result=~s/^__HASH_REF__//;
                   4687:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4688:   return $result;
                   4689: }
                   4690: 
                   4691: sub hashref2str {
                   4692:   my ($hashref)=@_;
1.265     albertel 4693:   my $result='__HASH_REF__';
1.800     albertel 4694:   foreach my $key (sort(keys(%$hashref))) {
                   4695:     if (ref($key) eq 'ARRAY') {
                   4696:       $result.=&arrayref2str($key).'=';
                   4697:     } elsif (ref($key) eq 'HASH') {
                   4698:       $result.=&hashref2str($key).'=';
                   4699:     } elsif (ref($key)) {
1.265     albertel 4700:       $result.='=';
1.800     albertel 4701:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4702:     } else {
1.1132    raeburn  4703: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4704:     }
                   4705: 
1.800     albertel 4706:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4707:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4708:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4709:       $result.=&hashref2str($hashref->{$key}).'&';
                   4710:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4711:        $result.='&';
1.800     albertel 4712:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4713:     } else {
1.800     albertel 4714:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4715:     }
                   4716:   }
1.168     albertel 4717:   $result=~s/\&$//;
1.265     albertel 4718:   $result .= '__END_HASH_REF__';
1.168     albertel 4719:   return $result;
                   4720: }
                   4721: 
                   4722: sub str2hash {
1.265     albertel 4723:     my ($string)=@_;
                   4724:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4725:     return %$hash;
                   4726: }
                   4727: 
                   4728: sub str2hashref {
1.168     albertel 4729:   my ($string) = @_;
1.265     albertel 4730: 
                   4731:   my %hash;
                   4732: 
                   4733:   if($string !~ /^__HASH_REF__/) {
                   4734:       if (! ($string eq '' || !defined($string))) {
                   4735: 	  $hash{'error'}='Not hash reference';
                   4736:       }
                   4737:       return (\%hash, $string);
                   4738:   }
                   4739: 
                   4740:   $string =~ s/^__HASH_REF__//;
                   4741: 
                   4742:   while($string !~ /^__END_HASH_REF__/) {
                   4743:       #key
                   4744:       my $key='';
                   4745:       if($string =~ /^__HASH_REF__/) {
                   4746:           ($key, $string)=&str2hashref($string);
                   4747:           if(defined($key->{'error'})) {
                   4748:               $hash{'error'}='Bad data';
                   4749:               return (\%hash, $string);
                   4750:           }
                   4751:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4752:           ($key, $string)=&str2arrayref($string);
                   4753:           if($key->[0] eq 'Array reference error') {
                   4754:               $hash{'error'}='Bad data';
                   4755:               return (\%hash, $string);
                   4756:           }
                   4757:       } else {
                   4758:           $string =~ s/^(.*?)=//;
1.267     albertel 4759: 	  $key=&unescape($1);
1.265     albertel 4760:       }
                   4761:       $string =~ s/^=//;
                   4762: 
                   4763:       #value
                   4764:       my $value='';
                   4765:       if($string =~ /^__HASH_REF__/) {
                   4766:           ($value, $string)=&str2hashref($string);
                   4767:           if(defined($value->{'error'})) {
                   4768:               $hash{'error'}='Bad data';
                   4769:               return (\%hash, $string);
                   4770:           }
                   4771:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4772:           ($value, $string)=&str2arrayref($string);
                   4773:           if($value->[0] eq 'Array reference error') {
                   4774:               $hash{'error'}='Bad data';
                   4775:               return (\%hash, $string);
                   4776:           }
                   4777:       } else {
                   4778: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4779:       }
                   4780:       $string =~ s/^&//;
                   4781: 
                   4782:       $hash{$key}=$value;
1.204     albertel 4783:   }
1.265     albertel 4784: 
                   4785:   $string =~ s/^__END_HASH_REF__//;
                   4786: 
                   4787:   return (\%hash, $string);
1.204     albertel 4788: }
                   4789: 
                   4790: sub str2array {
1.265     albertel 4791:     my ($string)=@_;
                   4792:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4793:     return @$array;
                   4794: }
                   4795: 
                   4796: sub str2arrayref {
1.204     albertel 4797:   my ($string) = @_;
1.265     albertel 4798:   my @array;
                   4799: 
                   4800:   if($string !~ /^__ARRAY_REF__/) {
                   4801:       if (! ($string eq '' || !defined($string))) {
                   4802: 	  $array[0]='Array reference error';
                   4803:       }
                   4804:       return (\@array, $string);
                   4805:   }
                   4806: 
                   4807:   $string =~ s/^__ARRAY_REF__//;
                   4808: 
                   4809:   while($string !~ /^__END_ARRAY_REF__/) {
                   4810:       my $value='';
                   4811:       if($string =~ /^__HASH_REF__/) {
                   4812:           ($value, $string)=&str2hashref($string);
                   4813:           if(defined($value->{'error'})) {
                   4814:               $array[0] ='Array reference error';
                   4815:               return (\@array, $string);
                   4816:           }
                   4817:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4818:           ($value, $string)=&str2arrayref($string);
                   4819:           if($value->[0] eq 'Array reference error') {
                   4820:               $array[0] ='Array reference error';
                   4821:               return (\@array, $string);
                   4822:           }
                   4823:       } else {
                   4824: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4825:       }
                   4826:       $string =~ s/^&//;
                   4827: 
                   4828:       push(@array, $value);
1.191     harris41 4829:   }
1.265     albertel 4830: 
                   4831:   $string =~ s/^__END_ARRAY_REF__//;
                   4832: 
                   4833:   return (\@array, $string);
1.168     albertel 4834: }
                   4835: 
1.167     albertel 4836: # -------------------------------------------------------------------Temp Store
                   4837: 
1.168     albertel 4838: sub tmpreset {
                   4839:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4840:   if (!$symb) {
                   4841:     $symb=&symbread();
1.620     albertel 4842:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4843:   }
                   4844:   $symb=escape($symb);
                   4845: 
1.620     albertel 4846:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4847:   $namespace=~s/\//\_/g;
                   4848:   $namespace=~s/\W//g;
                   4849: 
1.620     albertel 4850:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4851:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4852:   if ($domain eq 'public' && $stuname eq 'public') {
                   4853:       $stuname=$ENV{'REMOTE_ADDR'};
                   4854:   }
1.1117    foxr     4855:   my $path=LONCAPA::tempdir();
1.168     albertel 4856:   my %hash;
                   4857:   if (tie(%hash,'GDBM_File',
                   4858: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4859: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4860:     foreach my $key (keys(%hash)) {
1.180     albertel 4861:       if ($key=~ /:$symb/) {
1.168     albertel 4862: 	delete($hash{$key});
                   4863:       }
                   4864:     }
                   4865:   }
                   4866: }
                   4867: 
1.167     albertel 4868: sub tmpstore {
1.168     albertel 4869:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4870: 
                   4871:   if (!$symb) {
                   4872:     $symb=&symbread();
1.620     albertel 4873:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4874:   }
                   4875:   $symb=escape($symb);
                   4876: 
                   4877:   if (!$namespace) {
                   4878:     # I don't think we would ever want to store this for a course.
                   4879:     # it seems this will only be used if we don't have a course.
1.620     albertel 4880:     #$namespace=$env{'request.course.id'};
1.168     albertel 4881:     #if (!$namespace) {
1.620     albertel 4882:       $namespace=$env{'request.state'};
1.168     albertel 4883:     #}
                   4884:   }
                   4885:   $namespace=~s/\//\_/g;
                   4886:   $namespace=~s/\W//g;
1.620     albertel 4887:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4888:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4889:   if ($domain eq 'public' && $stuname eq 'public') {
                   4890:       $stuname=$ENV{'REMOTE_ADDR'};
                   4891:   }
1.168     albertel 4892:   my $now=time;
                   4893:   my %hash;
1.1117    foxr     4894:   my $path=LONCAPA::tempdir();
1.168     albertel 4895:   if (tie(%hash,'GDBM_File',
                   4896: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4897: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4898:     $hash{"version:$symb"}++;
                   4899:     my $version=$hash{"version:$symb"};
                   4900:     my $allkeys=''; 
                   4901:     foreach my $key (keys(%$storehash)) {
                   4902:       $allkeys.=$key.':';
1.591     albertel 4903:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4904:     }
                   4905:     $hash{"$version:$symb:timestamp"}=$now;
                   4906:     $allkeys.='timestamp';
                   4907:     $hash{"$version:keys:$symb"}=$allkeys;
                   4908:     if (untie(%hash)) {
                   4909:       return 'ok';
                   4910:     } else {
                   4911:       return "error:$!";
                   4912:     }
                   4913:   } else {
                   4914:     return "error:$!";
                   4915:   }
                   4916: }
1.167     albertel 4917: 
1.168     albertel 4918: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4919: 
1.168     albertel 4920: sub tmprestore {
                   4921:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4922: 
1.168     albertel 4923:   if (!$symb) {
                   4924:     $symb=&symbread();
1.620     albertel 4925:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4926:   }
                   4927:   $symb=escape($symb);
                   4928: 
1.620     albertel 4929:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4930: 
1.620     albertel 4931:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4932:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4933:   if ($domain eq 'public' && $stuname eq 'public') {
                   4934:       $stuname=$ENV{'REMOTE_ADDR'};
                   4935:   }
1.168     albertel 4936:   my %returnhash;
                   4937:   $namespace=~s/\//\_/g;
                   4938:   $namespace=~s/\W//g;
                   4939:   my %hash;
1.1117    foxr     4940:   my $path=LONCAPA::tempdir();
1.168     albertel 4941:   if (tie(%hash,'GDBM_File',
                   4942: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4943: 	  &GDBM_READER(),0640)) {
1.168     albertel 4944:     my $version=$hash{"version:$symb"};
                   4945:     $returnhash{'version'}=$version;
                   4946:     my $scope;
                   4947:     for ($scope=1;$scope<=$version;$scope++) {
                   4948:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4949:       my @keys=split(/:/,$vkeys);
                   4950:       my $key;
                   4951:       $returnhash{"$scope:keys"}=$vkeys;
                   4952:       foreach $key (@keys) {
1.591     albertel 4953: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4954: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4955:       }
                   4956:     }
1.168     albertel 4957:     if (!(untie(%hash))) {
                   4958:       return "error:$!";
                   4959:     }
                   4960:   } else {
                   4961:     return "error:$!";
                   4962:   }
                   4963:   return %returnhash;
1.167     albertel 4964: }
                   4965: 
1.9       www      4966: # ----------------------------------------------------------------------- Store
                   4967: 
                   4968: sub store {
1.1269    raeburn  4969:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      4970:     my $home='';
                   4971: 
1.168     albertel 4972:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4973: 
1.213     www      4974:     $symb=&symbclean($symb);
1.122     albertel 4975:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4976: 
1.620     albertel 4977:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4978:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4979: 
                   4980:     &devalidate($symb,$stuname,$domain);
1.109     www      4981: 
                   4982:     $symb=escape($symb);
1.187     www      4983:     if (!$namespace) { 
1.620     albertel 4984:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4985:           return ''; 
                   4986:        } 
                   4987:     }
1.620     albertel 4988:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4989: 
                   4990:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4991:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4992: 
1.12      www      4993:     my $namevalue='';
1.800     albertel 4994:     foreach my $key (keys(%$storehash)) {
                   4995:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4996:     }
1.12      www      4997:     $namevalue=~s/\&$//;
1.187     www      4998:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  4999:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5000: }
                   5001: 
1.47      www      5002: # -------------------------------------------------------------- Critical Store
                   5003: 
                   5004: sub cstore {
1.1269    raeburn  5005:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5006:     my $home='';
                   5007: 
1.168     albertel 5008:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5009: 
1.213     www      5010:     $symb=&symbclean($symb);
1.122     albertel 5011:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5012: 
1.620     albertel 5013:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5014:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5015: 
                   5016:     &devalidate($symb,$stuname,$domain);
1.109     www      5017: 
                   5018:     $symb=escape($symb);
1.187     www      5019:     if (!$namespace) { 
1.620     albertel 5020:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5021:           return ''; 
                   5022:        } 
                   5023:     }
1.620     albertel 5024:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5025: 
                   5026:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5027:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5028: 
1.47      www      5029:     my $namevalue='';
1.800     albertel 5030:     foreach my $key (keys(%$storehash)) {
                   5031:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5032:     }
1.47      www      5033:     $namevalue=~s/\&$//;
1.187     www      5034:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5035:     return critical
1.1269    raeburn  5036:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5037: }
                   5038: 
1.9       www      5039: # --------------------------------------------------------------------- Restore
                   5040: 
                   5041: sub restore {
1.124     www      5042:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5043:     my $home='';
                   5044: 
1.168     albertel 5045:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5046: 
1.122     albertel 5047:     if (!$symb) {
1.1224    raeburn  5048:         return if ($namespace eq 'courserequests');
                   5049:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5050:     } else {
1.1224    raeburn  5051:         unless ($namespace eq 'courserequests') {
                   5052:             $symb=&escape(&symbclean($symb));
                   5053:         }
1.122     albertel 5054:     }
1.188     www      5055:     if (!$namespace) { 
1.620     albertel 5056:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5057:           return ''; 
                   5058:        } 
                   5059:     }
1.620     albertel 5060:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5061:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5062:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5063:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5064: 
1.12      www      5065:     my %returnhash=();
1.800     albertel 5066:     foreach my $line (split(/\&/,$answer)) {
                   5067: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5068:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5069:     }
1.75      www      5070:     my $version;
                   5071:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5072:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5073:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5074:        }
1.75      www      5075:     }
1.13      www      5076:     return %returnhash;
1.34      www      5077: }
                   5078: 
                   5079: # ---------------------------------------------------------- Course Description
1.1118    foxr     5080: #
                   5081: #  
1.34      www      5082: 
                   5083: sub coursedescription {
1.731     albertel 5084:     my ($courseid,$args)=@_;
1.34      www      5085:     $courseid=~s/^\///;
1.49      www      5086:     $courseid=~s/\_/\//g;
1.34      www      5087:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5088:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5089:     my $normalid=$cdomain.'_'.$cnum;
                   5090:     # need to always cache even if we get errors otherwise we keep 
                   5091:     # trying and trying and trying to get the course description.
                   5092:     my %envhash=();
                   5093:     my %returnhash=();
1.731     albertel 5094:     
                   5095:     my $expiretime=600;
                   5096:     if ($env{'request.course.id'} eq $normalid) {
                   5097: 	$expiretime=120;
                   5098:     }
                   5099: 
                   5100:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5101:     if (!$args->{'freshen_cache'}
                   5102: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5103: 	foreach my $key (keys(%env)) {
                   5104: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5105: 	    my ($setting) = $1;
                   5106: 	    $returnhash{$setting} = $env{$key};
                   5107: 	}
                   5108: 	return %returnhash;
                   5109:     }
                   5110: 
1.1118    foxr     5111:     # get the data again
                   5112: 
1.731     albertel 5113:     if (!$args->{'one_time'}) {
                   5114: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5115:     }
1.811     albertel 5116: 
1.34      www      5117:     if ($chome ne 'no_host') {
1.302     albertel 5118:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5119:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5120: 	   my $username = $env{'user.name'}; # Defult username
                   5121: 	   if(defined $args->{'user'}) {
                   5122: 	       $username = $args->{'user'};
                   5123: 	   }
1.129     albertel 5124:            $returnhash{'home'}= $chome;
                   5125: 	   $returnhash{'domain'} = $cdomain;
                   5126: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5127:            if (!defined($returnhash{'type'})) {
                   5128:                $returnhash{'type'} = 'Course';
                   5129:            }
1.130     albertel 5130:            while (my ($name,$value) = each %returnhash) {
1.53      www      5131:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5132:            }
1.270     www      5133:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5134:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5135: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5136:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5137:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5138:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5139:        }
                   5140:     }
1.731     albertel 5141:     if (!$args->{'one_time'}) {
1.949     raeburn  5142: 	&appenv(\%envhash);
1.731     albertel 5143:     }
1.302     albertel 5144:     return %returnhash;
1.461     www      5145: }
                   5146: 
1.1080    raeburn  5147: sub update_released_required {
                   5148:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5149:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5150:         $cid = $env{'request.course.id'};
                   5151:         $cdom = $env{'course.'.$cid.'.domain'};
                   5152:         $cnum = $env{'course.'.$cid.'.num'};
                   5153:         $chome = $env{'course.'.$cid.'.home'};
                   5154:     }
                   5155:     if ($needsrelease) {
                   5156:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5157:         my $needsupdate;
                   5158:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5159:             $needsupdate = 1;
                   5160:         } else {
                   5161:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5162:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5163:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5164:                 $needsupdate = 1;
                   5165:             }
                   5166:         }
                   5167:         if ($needsupdate) {
                   5168:             my %needshash = (
                   5169:                              'internal.releaserequired' => $needsrelease,
                   5170:                             );
                   5171:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5172:             if ($putresult eq 'ok') {
                   5173:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5174:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5175:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5176:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5177:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5178:                 }
                   5179:             }
                   5180:         }
                   5181:     }
                   5182:     return;
                   5183: }
                   5184: 
1.461     www      5185: # -------------------------------------------------See if a user is privileged
                   5186: 
                   5187: sub privileged {
1.1219    raeburn  5188:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5189:     my $now = time;
1.1219    raeburn  5190:     my $roles;
                   5191:     if (ref($possroles) eq 'ARRAY') {
                   5192:         $roles = $possroles; 
                   5193:     } else {
                   5194:         $roles = ['dc','su'];
                   5195:     }
                   5196:     if (ref($possdomains) eq 'ARRAY') {
                   5197:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5198:         foreach my $dom (@{$possdomains}) {
                   5199:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5200:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5201:                 foreach my $role (@{$roles}) {
                   5202:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5203:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5204:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5205:                             return 1 unless (($end && $end < $now) ||
                   5206:                                              ($start && $start > $now));
                   5207:                         }
                   5208:                     }
                   5209:                 }
                   5210:             }
                   5211:         }
                   5212:     } else {
                   5213:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5214:         my $now = time;
1.1170    droeschl 5215: 
1.1275    musolffc 5216:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5217:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5218:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5219:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5220:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5221:             }
1.1219    raeburn  5222:         }
                   5223:     }
                   5224:     return 0;
                   5225: }
1.1170    droeschl 5226: 
1.1219    raeburn  5227: sub privileged_by_domain {
                   5228:     my ($domains,$roles) = @_;
                   5229:     my %privileged = ();
                   5230:     my $cachetime = 60*60*24;
                   5231:     my $now = time;
                   5232:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5233:         return %privileged;
                   5234:     }
                   5235:     foreach my $dom (@{$domains}) {
                   5236:         next if (ref($privileged{$dom}) eq 'HASH');
                   5237:         my $needroles;
                   5238:         foreach my $role (@{$roles}) {
                   5239:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5240:             if (defined($cached)) {
                   5241:                 if (ref($result) eq 'HASH') {
                   5242:                     $privileged{$dom}{$role} = $result;
                   5243:                 }
                   5244:             } else {
                   5245:                 $needroles = 1;
                   5246:             }
                   5247:         }
                   5248:         if ($needroles) {
                   5249:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5250:             $privileged{$dom} = {};
                   5251:             foreach my $server (keys(%dompersonnel)) {
                   5252:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5253:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5254:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5255:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5256:                         next if ($end && $end < $now);
                   5257:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5258:                             $dompersonnel{$server}{$item};
                   5259:                     }
                   5260:                 }
                   5261:             }
                   5262:             if (ref($privileged{$dom}) eq 'HASH') {
                   5263:                 foreach my $role (@{$roles}) {
                   5264:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5265:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5266:                     } else {
                   5267:                         my %hash = ();
                   5268:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5269:                     }
                   5270:                 }
                   5271:             }
                   5272:         }
                   5273:     }
                   5274:     return %privileged;
1.9       www      5275: }
1.1       albertel 5276: 
1.103     harris41 5277: # -------------------------------------------------------- Get user privileges
1.11      www      5278: 
                   5279: sub rolesinit {
1.1169    droeschl 5280:     my ($domain, $username) = @_;
                   5281:     my %userroles = ('user.login.time' => time);
                   5282:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5283: 
                   5284:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5285:     # also, blocking can be triggered by an activating timer
                   5286:     # it's saved in the user's %env.
                   5287:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5288:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5289:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5290:         %timerintchk, %timerintenv);
                   5291: 
1.1162    raeburn  5292:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5293:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5294:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5295:     }
1.1169    droeschl 5296: 
1.1162    raeburn  5297:     foreach my $key (keys(%timerinterval)) {
                   5298:         my ($cid,$rest) = split(/\0/,$key);
                   5299:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5300:     }
1.1169    droeschl 5301: 
1.11      www      5302:     my %allroles=();
1.1162    raeburn  5303:     my %allgroups=();
1.11      www      5304: 
1.1274    raeburn  5305:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5306:         my $role = $rolesdump{$area};
                   5307:         $area =~ s/\_\w\w$//;
                   5308: 
                   5309:         my ($trole, $tend, $tstart, $group_privs);
                   5310: 
                   5311:         if ($role =~ /^cr/) {
                   5312:         # Custom role, defined by a user 
                   5313:         # e.g., user.role.cr/msu/smith/mynewrole
                   5314:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5315:                 $trole = $1;
                   5316:                 ($tend, $tstart) = split('_', $2);
                   5317:             } else {
                   5318:                 $trole = $role;
                   5319:             }
                   5320:         } elsif ($role =~ m|^gr/|) {
                   5321:         # Role of member in a group, defined within a course/community
                   5322:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5323:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5324:             next if $tstart eq '-1';
                   5325:             ($trole, $group_privs) = split(/\//, $trole);
                   5326:             $group_privs = &unescape($group_privs);
                   5327:         } else {
                   5328:         # Just a normal role, defined in roles.tab
                   5329:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5330:         }
                   5331: 
                   5332:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5333:                  $username);
                   5334:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5335: 
                   5336:         # role expired or not available yet?
                   5337:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5338:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5339: 
                   5340:         next if $area eq '' or $trole eq '';
                   5341: 
                   5342:         my $spec = "$trole.$area";
                   5343:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5344: 
                   5345:         if ($trole =~ /^cr\//) {
                   5346:         # Custom role, defined by a user
                   5347:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5348:         } elsif ($trole eq 'gr') {
                   5349:         # Role of a member in a group, defined within a course/community
                   5350:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5351:             next;
                   5352:         } else {
                   5353:         # Normal role, defined in roles.tab
                   5354:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5355:         }
                   5356: 
                   5357:         my $cid = $tdomain.'_'.$trest;
                   5358:         unless ($firstaccchk{$cid}) {
                   5359:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5360:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5361:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5362:                         $coursetimerstarts{$cid}{$item}; 
                   5363:                 }
                   5364:             }
                   5365:             $firstaccchk{$cid} = 1;
                   5366:         }
                   5367:         unless ($timerintchk{$cid}) {
                   5368:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5369:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5370:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5371:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5372:                 }
1.12      www      5373:             }
1.1169    droeschl 5374:             $timerintchk{$cid} = 1;
1.191     harris41 5375:         }
1.11      www      5376:     }
1.1169    droeschl 5377: 
                   5378:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5379:         \%allroles, \%allgroups);
                   5380:     $env{'user.adv'} = $userroles{'user.adv'};
                   5381: 
1.1162    raeburn  5382:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5383: }
                   5384: 
1.567     raeburn  5385: sub set_arearole {
1.1215    raeburn  5386:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5387:     unless ($nolog) {
1.567     raeburn  5388: # log the associated role with the area
1.1215    raeburn  5389:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5390:     }
1.743     albertel 5391:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5392: }
                   5393: 
                   5394: sub custom_roleprivs {
                   5395:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5396:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5397:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5398:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5399:         my ($rdummy,$roledef)=
                   5400:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5401:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5402:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5403:             if (defined($syspriv)) {
1.1043    raeburn  5404:                 if ($trest =~ /^$match_community$/) {
                   5405:                     $syspriv =~ s/bre\&S//; 
                   5406:                 }
1.567     raeburn  5407:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5408:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5409:             }
                   5410:             if ($tdomain ne '') {
                   5411:                 if (defined($dompriv)) {
                   5412:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5413:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5414:                 }
                   5415:                 if (($trest ne '') && (defined($coursepriv))) {
                   5416:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5417:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5418:                 }
                   5419:             }
                   5420:         }
                   5421:     }
                   5422: }
                   5423: 
1.678     raeburn  5424: sub group_roleprivs {
                   5425:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5426:     my $access = 1;
                   5427:     my $now = time;
                   5428:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5429:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5430:     if ($access) {
1.811     albertel 5431:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5432:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5433:     }
                   5434: }
1.567     raeburn  5435: 
                   5436: sub standard_roleprivs {
                   5437:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5438:     if (defined($pr{$trole.':s'})) {
                   5439:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5440:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5441:     }
                   5442:     if ($tdomain ne '') {
                   5443:         if (defined($pr{$trole.':d'})) {
                   5444:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5445:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5446:         }
                   5447:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5448:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5449:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5450:         }
                   5451:     }
                   5452: }
                   5453: 
                   5454: sub set_userprivs {
1.1064    raeburn  5455:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5456:     my $author=0;
                   5457:     my $adv=0;
1.678     raeburn  5458:     my %grouproles = ();
                   5459:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5460:         my @groupkeys; 
1.1000    raeburn  5461:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5462:             push(@groupkeys,$role);
                   5463:         }
                   5464:         if (ref($groups_roles) eq 'HASH') {
                   5465:             foreach my $key (keys(%{$groups_roles})) {
                   5466:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5467:                     push(@groupkeys,$key);
                   5468:                 }
                   5469:             }
                   5470:         }
                   5471:         if (@groupkeys > 0) {
                   5472:             foreach my $role (@groupkeys) {
                   5473:                 my ($trole,$area,$sec,$extendedarea);
                   5474:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5475:                     $trole = $1;
                   5476:                     $area = $2;
                   5477:                     $sec = $3;
                   5478:                     $extendedarea = $area.$sec;
                   5479:                     if (exists($$allgroups{$area})) {
                   5480:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5481:                             my $spec = $trole.'.'.$extendedarea;
                   5482:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5483:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5484:                         }
1.678     raeburn  5485:                     }
                   5486:                 }
                   5487:             }
                   5488:         }
                   5489:     }
1.800     albertel 5490:     foreach my $group (keys(%grouproles)) {
                   5491:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5492:     }
1.800     albertel 5493:     foreach my $role (keys(%{$allroles})) {
                   5494:         my %thesepriv;
1.941     raeburn  5495:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5496:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5497:             if ($item ne '') {
                   5498:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5499:                 if ($restrictions eq '') {
                   5500:                     $thesepriv{$privilege}='F';
                   5501:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5502:                     $thesepriv{$privilege}.=$restrictions;
                   5503:                 }
                   5504:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5505:             }
                   5506:         }
                   5507:         my $thesestr='';
1.1104    raeburn  5508:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5509: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5510: 	}
                   5511:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5512:     }
                   5513:     return ($author,$adv);
                   5514: }
                   5515: 
1.994     raeburn  5516: sub role_status {
1.1104    raeburn  5517:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5518:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5519:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5520:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5521:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5522:             $$where = '/'.$two;
1.994     raeburn  5523:             $$trolecode=$$role.'.'.$$where;
                   5524:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5525:             $$tstatus='is';
1.1104    raeburn  5526:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5527:                 $$tstatus='future';
1.1034    raeburn  5528:                 if ($$tstart<$now) {
                   5529:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5530:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5531:                             my (%allroles,%allgroups,$group_privs,
                   5532:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5533:                             my %userroles = (
                   5534:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5535:                             );
1.1064    raeburn  5536:                             @rolecodes = ('cm'); 
1.1002    raeburn  5537:                             my $spec=$$role.'.'.$$where;
                   5538:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5539:                             if ($$role =~ /^cr\//) {
                   5540:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5541:                                 push(@rolecodes,'cr');
1.1002    raeburn  5542:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5543:                                 push(@rolecodes,$$role);
1.1002    raeburn  5544:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5545:                                                     $env{'user.name'});
1.1064    raeburn  5546:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5547:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5548:                                 $group_privs = &unescape($group_privs);
                   5549:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5550:                                 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  5551:                                 &get_groups_roles($tdomain,$trest,
                   5552:                                                   \%course_roles,\@rolecodes,
                   5553:                                                   \%groups_roles);
1.1002    raeburn  5554:                             } else {
1.1064    raeburn  5555:                                 push(@rolecodes,$$role);
1.1002    raeburn  5556:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5557:                             }
1.1064    raeburn  5558:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5559:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5560:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5561:                         }
                   5562:                     }
1.1034    raeburn  5563:                     $$tstatus = 'is';
1.1002    raeburn  5564:                 }
1.994     raeburn  5565:             }
                   5566:             if ($$tend) {
1.1104    raeburn  5567:                 if ($$tend<$update) {
1.994     raeburn  5568:                     $$tstatus='expired';
                   5569:                 } elsif ($$tend<$now) {
                   5570:                     $$tstatus='will_not';
                   5571:                 }
                   5572:             }
                   5573:         }
                   5574:     }
                   5575: }
                   5576: 
1.1104    raeburn  5577: sub get_groups_roles {
                   5578:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5579:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5580:                   (ref($rolecodes) eq 'ARRAY') && 
                   5581:                   (ref($groups_roles) eq 'HASH')); 
                   5582:     if (keys(%{$cdom_courseroles}) > 0) {
                   5583:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5584:         if ($cdom ne '' && $cnum ne '') {
                   5585:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5586:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5587:                     my $crsrole = $1;
                   5588:                     my $crssec = $2;
                   5589:                     if ($crsrole =~ /^cr/) {
                   5590:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5591:                             push(@{$rolecodes},'cr');
                   5592:                         }
                   5593:                     } else {
                   5594:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5595:                             push(@{$rolecodes},$crsrole);
                   5596:                         }
                   5597:                     }
                   5598:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5599:                     if ($crssec ne '') {
                   5600:                         $rolekey .= "/$crssec";
                   5601:                     }
                   5602:                     $rolekey .= './';
                   5603:                     $groups_roles->{$rolekey} = $rolecodes;
                   5604:                 }
                   5605:             }
                   5606:         }
                   5607:     }
                   5608:     return;
                   5609: }
                   5610: 
                   5611: sub delete_env_groupprivs {
                   5612:     my ($where,$courseroles,$possroles) = @_;
                   5613:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5614:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5615:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5616:         %{$courseroles->{$udom}} =
                   5617:             &get_my_roles('','','userroles',['active'],
                   5618:                           $possroles,[$udom],1);
                   5619:     }
                   5620:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5621:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5622:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5623:             my $area = '/'.$cdom.'/'.$cnum;
                   5624:             my $privkey = "user.priv.$crsrole.$area";
                   5625:             if ($crssec ne '') {
                   5626:                 $privkey .= '/'.$crssec;
                   5627:             }
                   5628:             $privkey .= ".$area/$group";
                   5629:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5630:         }
                   5631:     }
                   5632:     return;
                   5633: }
                   5634: 
1.994     raeburn  5635: sub check_adhoc_privs {
1.1104    raeburn  5636:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5637:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5638:     my $setprivs;
1.994     raeburn  5639:     if ($env{$cckey}) {
                   5640:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5641:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5642:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5643:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5644:             $setprivs = 1;
1.994     raeburn  5645:         }
                   5646:     } else {
1.1088    raeburn  5647:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5648:         $setprivs = 1;
1.994     raeburn  5649:     }
1.1185    raeburn  5650:     return $setprivs;
1.994     raeburn  5651: }
                   5652: 
                   5653: sub set_adhoc_privileges {
                   5654: # role can be cc or ca
1.1088    raeburn  5655:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5656:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5657:     my $spec = $role.'.'.$area;
                   5658:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5659:                                   $env{'user.name'},1);
1.994     raeburn  5660:     my %ccrole = ();
                   5661:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5662:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5663:     &appenv(\%userroles,[$role,'cm']);
                   5664:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5665:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5666:         &appenv( {'request.role'        => $spec,
                   5667:                   'request.role.domain' => $dcdom,
                   5668:                   'request.course.sec'  => ''
                   5669:                  }
                   5670:                );
                   5671:         my $tadv=0;
                   5672:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5673:         &appenv({'request.role.adv'    => $tadv});
                   5674:     }
1.994     raeburn  5675: }
                   5676: 
1.12      www      5677: # --------------------------------------------------------------- get interface
                   5678: 
                   5679: sub get {
1.131     albertel 5680:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5681:    my $items='';
1.800     albertel 5682:    foreach my $item (@$storearr) {
                   5683:        $items.=&escape($item).'&';
1.191     harris41 5684:    }
1.12      www      5685:    $items=~s/\&$//;
1.620     albertel 5686:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5687:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5688:    my $uhome=&homeserver($uname,$udomain);
                   5689: 
1.133     albertel 5690:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5691:    my @pairs=split(/\&/,$rep);
1.273     albertel 5692:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5693:      return @pairs;
                   5694:    }
1.15      www      5695:    my %returnhash=();
1.42      www      5696:    my $i=0;
1.800     albertel 5697:    foreach my $item (@$storearr) {
                   5698:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5699:       $i++;
1.191     harris41 5700:    }
1.15      www      5701:    return %returnhash;
1.27      www      5702: }
                   5703: 
                   5704: # --------------------------------------------------------------- del interface
                   5705: 
                   5706: sub del {
1.133     albertel 5707:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5708:    my $items='';
1.800     albertel 5709:    foreach my $item (@$storearr) {
                   5710:        $items.=&escape($item).'&';
1.191     harris41 5711:    }
1.984     neumanie 5712: 
1.27      www      5713:    $items=~s/\&$//;
1.620     albertel 5714:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5715:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5716:    my $uhome=&homeserver($uname,$udomain);
                   5717:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5718: }
                   5719: 
                   5720: # -------------------------------------------------------------- dump interface
                   5721: 
1.1180    droeschl 5722: sub unserialize {
                   5723:     my ($rep, $escapedkeys) = @_;
                   5724: 
                   5725:     return {} if $rep =~ /^error/;
                   5726: 
                   5727:     my %returnhash=();
1.1252    raeburn  5728: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 5729: 	    my ($key, $value) = split(/=/, $item, 2);
                   5730: 	    $key = unescape($key) unless $escapedkeys;
                   5731: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  5732: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 5733: 	}
                   5734:     #return %returnhash;
                   5735:     return \%returnhash;
                   5736: }        
                   5737: 
                   5738: # see Lond::dump_with_regexp
                   5739: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5740: sub dump {
1.1180    droeschl 5741:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5742:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5743:     if (!$uname) { $uname=$env{'user.name'}; }
                   5744:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5745: 
1.1266    raeburn  5746:     if ($regexp) {
                   5747:         $regexp=&escape($regexp);
                   5748:     } else {
                   5749:         $regexp='.';
                   5750:     }
1.1180    droeschl 5751:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5752:         # user is hosted on this machine
1.1266    raeburn  5753:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5754:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5755:         return %{unserialize($reply, $escapedkeys)};
                   5756:     }
1.1166    raeburn  5757:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5758:     my @pairs=split(/\&/,$rep);
                   5759:     my %returnhash=();
1.1098    foxr     5760:     if (!($rep =~ /^error/ )) {
                   5761: 	foreach my $item (@pairs) {
                   5762: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5763:         $key = unescape($key) unless $escapedkeys;
                   5764:         #$key = &unescape($key);
1.1098    foxr     5765: 	    next if ($key =~ /^error: 2 /);
                   5766: 	    $returnhash{$key}=&thaw_unescape($value);
                   5767: 	}
1.755     albertel 5768:     }
                   5769:     return %returnhash;
1.407     www      5770: }
                   5771: 
1.1098    foxr     5772: 
1.717     albertel 5773: # --------------------------------------------------------- dumpstore interface
                   5774: 
                   5775: sub dumpstore {
                   5776:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5777:    # same as dump but keys must be escaped. They may contain colon separated
                   5778:    # lists of values that may themself contain colons (e.g. symbs).
                   5779:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5780: }
                   5781: 
1.407     www      5782: # -------------------------------------------------------------- keys interface
                   5783: 
                   5784: sub getkeys {
                   5785:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5786:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5787:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5788:    my $uhome=&homeserver($uname,$udomain);
                   5789:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5790:    my @keyarray=();
1.800     albertel 5791:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5792:       next if ($key =~ /^error: 2 /);
1.800     albertel 5793:       push(@keyarray,&unescape($key));
1.407     www      5794:    }
                   5795:    return @keyarray;
1.318     matthew  5796: }
                   5797: 
1.319     matthew  5798: # --------------------------------------------------------------- currentdump
                   5799: sub currentdump {
1.328     matthew  5800:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5801:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5802:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5803:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5804:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5805:    my $rep;
                   5806: 
                   5807:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5808:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5809:                    $courseid)));
                   5810:    } else {
                   5811:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5812:    }
                   5813: 
1.318     matthew  5814:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5815:    #
1.318     matthew  5816:    my %returnhash=();
1.319     matthew  5817:    #
                   5818:    if ($rep eq "unknown_cmd") { 
                   5819:        # an old lond will not know currentdump
                   5820:        # Do a dump and make it look like a currentdump
1.822     albertel 5821:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5822:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5823:        my %hash = @tmp;
                   5824:        @tmp=();
1.424     matthew  5825:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5826:    } else {
                   5827:        my @pairs=split(/\&/,$rep);
1.800     albertel 5828:        foreach my $pair (@pairs) {
                   5829:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5830:            my ($symb,$param) = split(/:/,$key);
                   5831:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5832:                                                         &thaw_unescape($value);
1.319     matthew  5833:        }
1.191     harris41 5834:    }
1.12      www      5835:    return %returnhash;
1.424     matthew  5836: }
                   5837: 
                   5838: sub convert_dump_to_currentdump{
                   5839:     my %hash = %{shift()};
                   5840:     my %returnhash;
                   5841:     # Code ripped from lond, essentially.  The only difference
                   5842:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5843:     # we might run in to problems with parameter names =~ /^v\./
                   5844:     while (my ($key,$value) = each(%hash)) {
                   5845:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5846: 	$symb  = &unescape($symb);
                   5847: 	$param = &unescape($param);
1.424     matthew  5848:         next if ($v eq 'version' || $symb eq 'keys');
                   5849:         next if (exists($returnhash{$symb}) &&
                   5850:                  exists($returnhash{$symb}->{$param}) &&
                   5851:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5852:         $returnhash{$symb}->{$param}=$value;
                   5853:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5854:     }
                   5855:     #
                   5856:     # Remove all of the keys in the hashes which keep track of
                   5857:     # the version of the parameter.
                   5858:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5859:         # use a foreach because we are going to delete from the hash.
                   5860:         foreach my $key (keys(%$param_hash)) {
                   5861:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5862:         }
                   5863:     }
                   5864:     return \%returnhash;
1.12      www      5865: }
                   5866: 
1.627     albertel 5867: # ------------------------------------------------------ critical inc interface
                   5868: 
                   5869: sub cinc {
                   5870:     return &inc(@_,'critical');
                   5871: }
                   5872: 
1.449     matthew  5873: # --------------------------------------------------------------- inc interface
                   5874: 
                   5875: sub inc {
1.627     albertel 5876:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5877:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5878:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5879:     my $uhome=&homeserver($uname,$udomain);
                   5880:     my $items='';
                   5881:     if (! ref($store)) {
                   5882:         # got a single value, so use that instead
                   5883:         $items = &escape($store).'=&';
                   5884:     } elsif (ref($store) eq 'SCALAR') {
                   5885:         $items = &escape($$store).'=&';        
                   5886:     } elsif (ref($store) eq 'ARRAY') {
                   5887:         $items = join('=&',map {&escape($_);} @{$store});
                   5888:     } elsif (ref($store) eq 'HASH') {
                   5889:         while (my($key,$value) = each(%{$store})) {
                   5890:             $items.= &escape($key).'='.&escape($value).'&';
                   5891:         }
                   5892:     }
                   5893:     $items=~s/\&$//;
1.627     albertel 5894:     if ($critical) {
                   5895: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5896:     } else {
                   5897: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5898:     }
1.449     matthew  5899: }
                   5900: 
1.12      www      5901: # --------------------------------------------------------------- put interface
                   5902: 
                   5903: sub put {
1.134     albertel 5904:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5905:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5906:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5907:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5908:    my $items='';
1.800     albertel 5909:    foreach my $item (keys(%$storehash)) {
                   5910:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5911:    }
1.12      www      5912:    $items=~s/\&$//;
1.134     albertel 5913:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5914: }
                   5915: 
1.631     albertel 5916: # ------------------------------------------------------------ newput interface
                   5917: 
                   5918: sub newput {
                   5919:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5920:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5921:    if (!$uname) { $uname=$env{'user.name'}; }
                   5922:    my $uhome=&homeserver($uname,$udomain);
                   5923:    my $items='';
                   5924:    foreach my $key (keys(%$storehash)) {
                   5925:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5926:    }
                   5927:    $items=~s/\&$//;
                   5928:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5929: }
                   5930: 
                   5931: # ---------------------------------------------------------  putstore interface
                   5932: 
1.524     raeburn  5933: sub putstore {
1.1269    raeburn  5934:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 5935:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5936:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5937:    my $uhome=&homeserver($uname,$udomain);
                   5938:    my $items='';
1.715     albertel 5939:    foreach my $key (keys(%$storehash)) {
                   5940:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5941:    }
1.715     albertel 5942:    $items=~s/\&$//;
1.716     albertel 5943:    my $esc_symb=&escape($symb);
                   5944:    my $esc_v=&escape($version);
1.715     albertel 5945:    my $reply =
1.716     albertel 5946:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5947: 	      $uhome);
1.1269    raeburn  5948:    if (($tolog) && ($reply eq 'ok')) {
                   5949:        my $namevalue='';
                   5950:        foreach my $key (keys(%{$storehash})) {
                   5951:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   5952:        }
                   5953:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   5954:                      '&host='.&escape($perlvar{'lonHostID'}).
                   5955:                      '&version='.$esc_v.
                   5956:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   5957:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   5958:    }
1.715     albertel 5959:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5960:        # gfall back to way things use to be done
1.715     albertel 5961:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5962: 			    $uname);
1.524     raeburn  5963:    }
1.715     albertel 5964:    return $reply;
                   5965: }
                   5966: 
                   5967: sub old_putstore {
1.716     albertel 5968:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5969:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5970:     if (!$uname) { $uname=$env{'user.name'}; }
                   5971:     my $uhome=&homeserver($uname,$udomain);
                   5972:     my %newstorehash;
1.800     albertel 5973:     foreach my $item (keys(%$storehash)) {
                   5974: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5975: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5976:     }
                   5977:     my $items='';
                   5978:     my %allitems = ();
1.800     albertel 5979:     foreach my $item (keys(%newstorehash)) {
                   5980: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5981: 	    my $key = $1.':keys:'.$2;
                   5982: 	    $allitems{$key} .= $3.':';
                   5983: 	}
1.800     albertel 5984: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5985:     }
1.800     albertel 5986:     foreach my $item (keys(%allitems)) {
                   5987: 	$allitems{$item} =~ s/\:$//;
                   5988: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5989:     }
                   5990:     $items=~s/\&$//;
                   5991:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5992: }
                   5993: 
1.47      www      5994: # ------------------------------------------------------ critical put interface
                   5995: 
                   5996: sub cput {
1.134     albertel 5997:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5998:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5999:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6000:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6001:    my $items='';
1.800     albertel 6002:    foreach my $item (keys(%$storehash)) {
                   6003:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6004:    }
1.47      www      6005:    $items=~s/\&$//;
1.134     albertel 6006:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6007: }
                   6008: 
                   6009: # -------------------------------------------------------------- eget interface
                   6010: 
                   6011: sub eget {
1.133     albertel 6012:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6013:    my $items='';
1.800     albertel 6014:    foreach my $item (@$storearr) {
                   6015:        $items.=&escape($item).'&';
1.191     harris41 6016:    }
1.12      www      6017:    $items=~s/\&$//;
1.620     albertel 6018:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6019:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6020:    my $uhome=&homeserver($uname,$udomain);
                   6021:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6022:    my @pairs=split(/\&/,$rep);
                   6023:    my %returnhash=();
1.42      www      6024:    my $i=0;
1.800     albertel 6025:    foreach my $item (@$storearr) {
                   6026:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6027:       $i++;
1.191     harris41 6028:    }
1.12      www      6029:    return %returnhash;
                   6030: }
                   6031: 
1.667     albertel 6032: # ------------------------------------------------------------ tmpput interface
                   6033: sub tmpput {
1.802     raeburn  6034:     my ($storehash,$server,$context)=@_;
1.667     albertel 6035:     my $items='';
1.800     albertel 6036:     foreach my $item (keys(%$storehash)) {
                   6037: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6038:     }
                   6039:     $items=~s/\&$//;
1.802     raeburn  6040:     if (defined($context)) {
                   6041:         $items .= ':'.&escape($context);
                   6042:     }
1.667     albertel 6043:     return &reply("tmpput:$items",$server);
                   6044: }
                   6045: 
                   6046: # ------------------------------------------------------------ tmpget interface
                   6047: sub tmpget {
1.688     albertel 6048:     my ($token,$server)=@_;
                   6049:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6050:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6051:     my %returnhash;
                   6052:     foreach my $item (split(/\&/,$rep)) {
                   6053: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6054:         next if ($key =~ /^error: 2 /);
1.667     albertel 6055: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6056:     }
                   6057:     return %returnhash;
                   6058: }
                   6059: 
1.1113    raeburn  6060: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6061: sub tmpdel {
                   6062:     my ($token,$server)=@_;
                   6063:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6064:     return &reply("tmpdel:$token",$server);
                   6065: }
                   6066: 
1.1198    raeburn  6067: # ------------------------------------------------------------ get_timebased_id 
                   6068: 
                   6069: sub get_timebased_id {
                   6070:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6071:         $maxtries) = @_;
                   6072:     my ($newid,$error,$dellock);
                   6073:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6074:         return ('','ok','invalid call to get suffix');
                   6075:     }
                   6076: 
                   6077: # set defaults for any optional args for which values were not supplied
                   6078:     if ($who eq '') {
                   6079:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6080:     }
                   6081:     if (!$locktries) {
                   6082:         $locktries = 3;
                   6083:     }
                   6084:     if (!$maxtries) {
                   6085:         $maxtries = 10;
                   6086:     }
                   6087:     
                   6088:     if (($cdom eq '') || ($cnum eq '')) {
                   6089:         if ($env{'request.course.id'}) {
                   6090:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6091:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6092:         }
                   6093:         if (($cdom eq '') || ($cnum eq '')) {
                   6094:             return ('','ok','call to get suffix not in course context');
                   6095:         }
                   6096:     }
                   6097: 
                   6098: # construct locking item
                   6099:     my $lockhash = {
                   6100:                       $prefix."\0".'locked_'.$keyid => $who,
                   6101:                    };
                   6102:     my $tries = 0;
                   6103: 
                   6104: # attempt to get lock on nohist_$namespace file
                   6105:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6106:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6107:         $tries ++;
                   6108:         sleep 1;
                   6109:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6110:     }
                   6111: 
                   6112: # attempt to get unique identifier, based on current timestamp
                   6113:     if ($gotlock eq 'ok') {
                   6114:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6115:         my $id = time;
                   6116:         $newid = $id;
1.1268    raeburn  6117:         if ($idtype eq 'addcode') {
                   6118:             $newid .= &sixnum_code();
                   6119:         }
1.1198    raeburn  6120:         my $idtries = 0;
                   6121:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6122:             if ($idtype eq 'concat') {
                   6123:                 $newid = $id.$idtries;
1.1268    raeburn  6124:             } elsif ($idtype eq 'addcode') {
                   6125:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6126:             } else {
                   6127:                 $newid ++;
                   6128:             }
                   6129:             $idtries ++;
                   6130:         }
                   6131:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6132:             my %new_item =  (
                   6133:                               $prefix."\0".$newid => $who,
                   6134:                             );
                   6135:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6136:                                                  $cdom,$cnum);
                   6137:             if ($putresult ne 'ok') {
                   6138:                 undef($newid);
                   6139:                 $error = 'error saving new item: '.$putresult;
                   6140:             }
                   6141:         } else {
1.1268    raeburn  6142:              undef($newid);
1.1198    raeburn  6143:              $error = ('error: no unique suffix available for the new item ');
                   6144:         }
                   6145: #  remove lock
                   6146:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6147:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6148:     } else {
                   6149:         $error = "error: could not obtain lockfile\n";
                   6150:         $dellock = 'ok';
1.1276    raeburn  6151:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6152:             $dellock = 'nolock';
                   6153:         }
1.1198    raeburn  6154:     }
                   6155:     return ($newid,$dellock,$error);
                   6156: }
                   6157: 
1.1268    raeburn  6158: sub sixnum_code {
                   6159:     my $code;
                   6160:     for (0..6) {
                   6161:         $code .= int( rand(9) );
                   6162:     }
                   6163:     return $code;
                   6164: }
                   6165: 
1.765     albertel 6166: # -------------------------------------------------- portfolio access checking
                   6167: 
                   6168: sub portfolio_access {
1.1270    raeburn  6169:     my ($requrl,$clientip) = @_;
1.765     albertel 6170:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6171:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6172:     if ($result) {
                   6173:         my %setters;
                   6174:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6175:             my ($startblock,$endblock) =
                   6176:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6177:             if ($startblock && $endblock) {
                   6178:                 return 'B';
                   6179:             }
                   6180:         } else {
                   6181:             my ($startblock,$endblock) =
                   6182:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6183:             if ($startblock && $endblock) {
                   6184:                 return 'B';
                   6185:             }
                   6186:         }
                   6187:     }
1.765     albertel 6188:     if ($result eq 'ok') {
1.766     albertel 6189:        return 'F';
1.765     albertel 6190:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6191:        return 'A';
1.765     albertel 6192:     }
1.766     albertel 6193:     return '';
1.765     albertel 6194: }
                   6195: 
                   6196: sub get_portfolio_access {
1.1270    raeburn  6197:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6198: 
                   6199:     if (!ref($access_hash)) {
                   6200: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6201: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6202: 						   $file_name);
                   6203: 	$access_hash = $access_controls{$file_name};
                   6204:     }
                   6205: 
1.1270    raeburn  6206:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6207:     my $now = time;
                   6208:     if (ref($access_hash) eq 'HASH') {
                   6209:         foreach my $key (keys(%{$access_hash})) {
                   6210:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6211:             if ($start > $now) {
                   6212:                 next;
                   6213:             }
                   6214:             if ($end && $end<$now) {
                   6215:                 next;
                   6216:             }
                   6217:             if ($scope eq 'public') {
                   6218:                 $public = $key;
                   6219:                 last;
                   6220:             } elsif ($scope eq 'guest') {
                   6221:                 $guest = $key;
                   6222:             } elsif ($scope eq 'domains') {
                   6223:                 push(@domains,$key);
                   6224:             } elsif ($scope eq 'users') {
                   6225:                 push(@users,$key);
                   6226:             } elsif ($scope eq 'course') {
                   6227:                 push(@courses,$key);
                   6228:             } elsif ($scope eq 'group') {
                   6229:                 push(@groups,$key);
1.1270    raeburn  6230:             } elsif ($scope eq 'ip') {
                   6231:                 push(@ips,$key);
1.765     albertel 6232:             }
                   6233:         }
                   6234:         if ($public) {
                   6235:             return 'ok';
1.1270    raeburn  6236:         } elsif (@ips > 0) {
                   6237:             my $allowed;
                   6238:             foreach my $ipkey (@ips) {
                   6239:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6240:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6241:                         $allowed = 1;
                   6242:                         last; 
                   6243:                     }
                   6244:                 }
                   6245:             }
                   6246:             if ($allowed) {
                   6247:                 return 'ok';
                   6248:             }
1.765     albertel 6249:         }
                   6250:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6251:             if ($guest) {
                   6252:                 return $guest;
                   6253:             }
                   6254:         } else {
                   6255:             if (@domains > 0) {
                   6256:                 foreach my $domkey (@domains) {
                   6257:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6258:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6259:                             return 'ok';
                   6260:                         }
                   6261:                     }
                   6262:                 }
                   6263:             }
                   6264:             if (@users > 0) {
                   6265:                 foreach my $userkey (@users) {
1.865     raeburn  6266:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6267:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6268:                             if (ref($item) eq 'HASH') {
                   6269:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6270:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6271:                                     return 'ok';
                   6272:                                 }
                   6273:                             }
                   6274:                         }
                   6275:                     } 
1.765     albertel 6276:                 }
                   6277:             }
                   6278:             my %roleshash;
                   6279:             my @courses_and_groups = @courses;
                   6280:             push(@courses_and_groups,@groups); 
                   6281:             if (@courses_and_groups > 0) {
                   6282:                 my (%allgroups,%allroles); 
                   6283:                 my ($start,$end,$role,$sec,$group);
                   6284:                 foreach my $envkey (%env) {
1.1060    raeburn  6285:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6286:                         my $cid = $2.'_'.$3; 
                   6287:                         if ($1 eq 'gr') {
                   6288:                             $group = $4;
                   6289:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6290:                         } else {
                   6291:                             if ($4 eq '') {
                   6292:                                 $sec = 'none';
                   6293:                             } else {
                   6294:                                 $sec = $4;
                   6295:                             }
                   6296:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6297:                         }
1.811     albertel 6298:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6299:                         my $cid = $2.'_'.$3;
                   6300:                         if ($4 eq '') {
                   6301:                             $sec = 'none';
                   6302:                         } else {
                   6303:                             $sec = $4;
                   6304:                         }
                   6305:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6306:                     }
                   6307:                 }
                   6308:                 if (keys(%allroles) == 0) {
                   6309:                     return;
                   6310:                 }
                   6311:                 foreach my $key (@courses_and_groups) {
                   6312:                     my %content = %{$$access_hash{$key}};
                   6313:                     my $cnum = $content{'number'};
                   6314:                     my $cdom = $content{'domain'};
                   6315:                     my $cid = $cdom.'_'.$cnum;
                   6316:                     if (!exists($allroles{$cid})) {
                   6317:                         next;
                   6318:                     }    
                   6319:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6320:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6321:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6322:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6323:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6324:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6325:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6326:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6327:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6328:                                         if (grep/^all$/,@sections) {
                   6329:                                             return 'ok';
                   6330:                                         } else {
                   6331:                                             if (grep/^$sec$/,@sections) {
                   6332:                                                 return 'ok';
                   6333:                                             }
                   6334:                                         }
                   6335:                                     }
                   6336:                                 }
                   6337:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6338:                                     if (grep/^none$/,@groups) {
                   6339:                                         return 'ok';
                   6340:                                     }
                   6341:                                 } else {
                   6342:                                     if (grep/^all$/,@groups) {
                   6343:                                         return 'ok';
                   6344:                                     } 
                   6345:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6346:                                         if (grep/^$group$/,@groups) {
                   6347:                                             return 'ok';
                   6348:                                         }
                   6349:                                     }
                   6350:                                 } 
                   6351:                             }
                   6352:                         }
                   6353:                     }
                   6354:                 }
                   6355:             }
                   6356:             if ($guest) {
                   6357:                 return $guest;
                   6358:             }
                   6359:         }
                   6360:     }
                   6361:     return;
                   6362: }
                   6363: 
                   6364: sub course_group_datechecker {
                   6365:     my ($dates,$now,$status) = @_;
                   6366:     my ($start,$end) = split(/\./,$dates);
                   6367:     if (!$start && !$end) {
                   6368:         return 'ok';
                   6369:     }
                   6370:     if (grep/^active$/,@{$status}) {
                   6371:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6372:             return 'ok';
                   6373:         }
                   6374:     }
                   6375:     if (grep/^previous$/,@{$status}) {
                   6376:         if ($end > $now ) {
                   6377:             return 'ok';
                   6378:         }
                   6379:     }
                   6380:     if (grep/^future$/,@{$status}) {
                   6381:         if ($start > $now) {
                   6382:             return 'ok';
                   6383:         }
                   6384:     }
                   6385:     return; 
                   6386: }
                   6387: 
                   6388: sub parse_portfolio_url {
                   6389:     my ($url) = @_;
                   6390: 
                   6391:     my ($type,$udom,$unum,$group,$file_name);
                   6392:     
1.823     albertel 6393:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6394: 	$type = 1;
                   6395:         $udom = $1;
                   6396:         $unum = $2;
                   6397:         $file_name = $3;
1.823     albertel 6398:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6399: 	$type = 2;
                   6400:         $udom = $1;
                   6401:         $unum = $2;
                   6402:         $group = $3;
                   6403:         $file_name = $3.'/'.$4;
                   6404:     }
                   6405:     if (wantarray) {
                   6406: 	return ($type,$udom,$unum,$file_name,$group);
                   6407:     }
                   6408:     return $type;
                   6409: }
                   6410: 
                   6411: sub is_portfolio_url {
                   6412:     my ($url) = @_;
                   6413:     return scalar(&parse_portfolio_url($url));
                   6414: }
                   6415: 
1.798     raeburn  6416: sub is_portfolio_file {
                   6417:     my ($file) = @_;
1.820     raeburn  6418:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6419:         return 1;
                   6420:     }
                   6421:     return;
                   6422: }
                   6423: 
1.976     raeburn  6424: sub usertools_access {
1.1084    raeburn  6425:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6426:     my ($access,%tools);
                   6427:     if ($context eq '') {
                   6428:         $context = 'tools';
                   6429:     }
                   6430:     if ($context eq 'requestcourses') {
                   6431:         %tools = (
                   6432:                       official   => 1,
                   6433:                       unofficial => 1,
1.1006    raeburn  6434:                       community  => 1,
1.1246    raeburn  6435:                       textbook   => 1,
1.985     raeburn  6436:                  );
1.1183    raeburn  6437:     } elsif ($context eq 'requestauthor') {
                   6438:         %tools = (
                   6439:                       requestauthor => 1,
                   6440:                  );
1.985     raeburn  6441:     } else {
                   6442:         %tools = (
                   6443:                       aboutme   => 1,
                   6444:                       blog      => 1,
1.1177    raeburn  6445:                       webdav    => 1,
1.985     raeburn  6446:                       portfolio => 1,
                   6447:                  );
                   6448:     }
1.976     raeburn  6449:     return if (!defined($tools{$tool}));
                   6450: 
1.1242    raeburn  6451:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6452:         $udom = $env{'user.domain'};
                   6453:         $uname = $env{'user.name'};
                   6454:     }
                   6455: 
1.978     raeburn  6456:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6457:         if ($action ne 'reload') {
1.985     raeburn  6458:             if ($context eq 'requestcourses') {
                   6459:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6460:             } elsif ($context eq 'requestauthor') {
                   6461:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6462:             } else {
                   6463:                 return $env{'environment.availabletools.'.$tool};
                   6464:             }
                   6465:         }
1.976     raeburn  6466:     }
                   6467: 
1.1183    raeburn  6468:     my ($toolstatus,$inststatus,$envkey);
                   6469:     if ($context eq 'requestauthor') {
                   6470:         $envkey = $context; 
                   6471:     } else {
                   6472:         $envkey = $context.'.'.$tool;
                   6473:     }
1.976     raeburn  6474: 
1.985     raeburn  6475:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6476:          ($action ne 'reload')) {
1.1183    raeburn  6477:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6478:         $inststatus = $env{'environment.inststatus'};
                   6479:     } else {
1.1084    raeburn  6480:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6481:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6482:             $inststatus = $userenvref->{'inststatus'};
                   6483:         } else {
1.1183    raeburn  6484:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6485:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6486:             $inststatus = $userenv{'inststatus'};
                   6487:         }
1.976     raeburn  6488:     }
                   6489: 
                   6490:     if ($toolstatus ne '') {
                   6491:         if ($toolstatus) {
                   6492:             $access = 1;
                   6493:         } else {
                   6494:             $access = 0;
                   6495:         }
                   6496:         return $access;
                   6497:     }
                   6498: 
1.1084    raeburn  6499:     my ($is_adv,%domdef);
                   6500:     if (ref($is_advref) eq 'HASH') {
                   6501:         $is_adv = $is_advref->{'is_adv'};
                   6502:     } else {
                   6503:         $is_adv = &is_advanced_user($udom,$uname);
                   6504:     }
                   6505:     if (ref($domdefref) eq 'HASH') {
                   6506:         %domdef = %{$domdefref};
                   6507:     } else {
                   6508:         %domdef = &get_domain_defaults($udom);
                   6509:     }
1.976     raeburn  6510:     if (ref($domdef{$tool}) eq 'HASH') {
                   6511:         if ($is_adv) {
                   6512:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6513:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6514:                     $access = 1;
                   6515:                 } else {
                   6516:                     $access = 0;
                   6517:                 }
                   6518:                 return $access;
                   6519:             }
                   6520:         }
                   6521:         if ($inststatus ne '') {
                   6522:             my ($hasaccess,$hasnoaccess);
                   6523:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6524:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6525:                     if ($domdef{$tool}{$affiliation}) {
                   6526:                         $hasaccess = 1;
                   6527:                     } else {
                   6528:                         $hasnoaccess = 1;
                   6529:                     }
                   6530:                 }
                   6531:             }
                   6532:             if ($hasaccess || $hasnoaccess) {
                   6533:                 if ($hasaccess) {
                   6534:                     $access = 1;
                   6535:                 } elsif ($hasnoaccess) {
                   6536:                     $access = 0; 
                   6537:                 }
                   6538:                 return $access;
                   6539:             }
                   6540:         } else {
                   6541:             if ($domdef{$tool}{'default'} ne '') {
                   6542:                 if ($domdef{$tool}{'default'}) {
                   6543:                     $access = 1;
                   6544:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6545:                     $access = 0;
                   6546:                 }
                   6547:                 return $access;
                   6548:             }
                   6549:         }
                   6550:     } else {
1.1177    raeburn  6551:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6552:             $access = 1;
                   6553:         } else {
                   6554:             $access = 0;
                   6555:         }
1.976     raeburn  6556:         return $access;
                   6557:     }
                   6558: }
                   6559: 
1.1050    raeburn  6560: sub is_course_owner {
                   6561:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6562:     if (($udom eq '') || ($uname eq '')) {
                   6563:         $udom = $env{'user.domain'};
                   6564:         $uname = $env{'user.name'};
                   6565:     }
                   6566:     unless (($udom eq '') || ($uname eq '')) {
                   6567:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6568:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6569:                 return 1;
                   6570:             } else {
                   6571:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6572:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6573:                     return 1;
                   6574:                 }
                   6575:             }
                   6576:         }
                   6577:     }
                   6578:     return;
                   6579: }
                   6580: 
1.976     raeburn  6581: sub is_advanced_user {
                   6582:     my ($udom,$uname) = @_;
1.1085    raeburn  6583:     if ($udom ne '' && $uname ne '') {
                   6584:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6585:             if (wantarray) {
                   6586:                 return ($env{'user.adv'},$env{'user.author'});
                   6587:             } else {
                   6588:                 return $env{'user.adv'};
                   6589:             }
1.1085    raeburn  6590:         }
                   6591:     }
1.976     raeburn  6592:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6593:     my %allroles;
1.1128    raeburn  6594:     my ($is_adv,$is_author);
1.976     raeburn  6595:     foreach my $role (keys(%roleshash)) {
                   6596:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6597:         my $area = '/'.$tdomain.'/'.$trest;
                   6598:         if ($sec ne '') {
                   6599:             $area .= '/'.$sec;
                   6600:         }
                   6601:         if (($area ne '') && ($trole ne '')) {
                   6602:             my $spec=$trole.'.'.$area;
                   6603:             if ($trole =~ /^cr\//) {
                   6604:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6605:             } elsif ($trole ne 'gr') {
                   6606:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6607:             }
1.1128    raeburn  6608:             if ($trole eq 'au') {
                   6609:                 $is_author = 1;
                   6610:             }
1.976     raeburn  6611:         }
                   6612:     }
                   6613:     foreach my $role (keys(%allroles)) {
                   6614:         last if ($is_adv);
                   6615:         foreach my $item (split(/:/,$allroles{$role})) {
                   6616:             if ($item ne '') {
                   6617:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6618:                 if ($privilege eq 'adv') {
                   6619:                     $is_adv = 1;
                   6620:                     last;
                   6621:                 }
                   6622:             }
                   6623:         }
                   6624:     }
1.1128    raeburn  6625:     if (wantarray) {
                   6626:         return ($is_adv,$is_author);
                   6627:     }
1.976     raeburn  6628:     return $is_adv;
                   6629: }
1.798     raeburn  6630: 
1.1035    raeburn  6631: sub check_can_request {
1.1036    raeburn  6632:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6633:     my $canreq = 0;
                   6634:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6635:     my @options = ('approval','validate','autolimit');
                   6636:     my $optregex = join('|',@options);
                   6637:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6638:         foreach my $type (@{$types}) {
                   6639:             if (&usertools_access($env{'user.name'},
                   6640:                                   $env{'user.domain'},
                   6641:                                   $type,undef,'requestcourses')) {
                   6642:                 $canreq ++;
1.1036    raeburn  6643:                 if (ref($request_domains) eq 'HASH') {
                   6644:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6645:                 }
1.1035    raeburn  6646:                 if ($dom eq $env{'user.domain'}) {
                   6647:                     $can_request->{$type} = 1;
                   6648:                 }
                   6649:             }
                   6650:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6651:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6652:                 if (@curr > 0) {
1.1036    raeburn  6653:                     foreach my $item (@curr) {
                   6654:                         if (ref($request_domains) eq 'HASH') {
                   6655:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6656:                             if ($otherdom ne '') {
                   6657:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6658:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6659:                                         push(@{$request_domains->{$type}},$otherdom);
                   6660:                                     }
                   6661:                                 } else {
                   6662:                                     push(@{$request_domains->{$type}},$otherdom);
                   6663:                                 }
                   6664:                             }
                   6665:                         }
                   6666:                     }
                   6667:                     unless($dom eq $env{'user.domain'}) {
                   6668:                         $canreq ++;
1.1035    raeburn  6669:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6670:                             $can_request->{$type} = 1;
                   6671:                         }
                   6672:                     }
                   6673:                 }
                   6674:             }
                   6675:         }
                   6676:     }
                   6677:     return $canreq;
                   6678: }
                   6679: 
1.341     www      6680: # ---------------------------------------------- Custom access rule evaluation
                   6681: 
                   6682: sub customaccess {
                   6683:     my ($priv,$uri)=@_;
1.807     albertel 6684:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6685:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6686:     $udom = &LONCAPA::clean_domain($udom);
                   6687:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6688:     my $access=0;
1.800     albertel 6689:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6690: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6691: 	if ($type eq 'user') {
                   6692: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6693: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6694: 		if ($tdom) {
                   6695: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6696: 		}
1.896     albertel 6697: 		if ($tuname) {
                   6698: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6699: 		}
                   6700: 		$access=($effect eq 'allow');
                   6701: 		last;
                   6702: 	    }
                   6703: 	} else {
                   6704: 	    if ($role) {
                   6705: 		if ($role ne $urole) { next; }
                   6706: 	    }
                   6707: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6708: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6709: 		if ($tdom) {
                   6710: 		    if ($tdom ne $udom) { next; }
                   6711: 		}
                   6712: 		if ($tcrs) {
                   6713: 		    if ($tcrs ne $ucrs) { next; }
                   6714: 		}
                   6715: 		if ($tsec) {
                   6716: 		    if ($tsec ne $usec) { next; }
                   6717: 		}
                   6718: 		$access=($effect eq 'allow');
                   6719: 		last;
                   6720: 	    }
                   6721: 	    if ($realm eq '' && $role eq '') {
                   6722: 		$access=($effect eq 'allow');
                   6723: 	    }
1.402     bowersj2 6724: 	}
1.341     www      6725:     }
                   6726:     return $access;
                   6727: }
                   6728: 
1.103     harris41 6729: # ------------------------------------------------- Check for a user privilege
1.12      www      6730: 
                   6731: sub allowed {
1.1281    raeburn  6732:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 6733:     my $ver_orguri=$uri;
1.439     www      6734:     $uri=&deversion($uri);
1.152     www      6735:     my $orguri=$uri;
1.52      www      6736:     $uri=&declutter($uri);
1.809     raeburn  6737: 
1.810     raeburn  6738:     if ($priv eq 'evb') {
                   6739: # Evade communication block restrictions for specified role in a course
                   6740:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6741:             return $1;
                   6742:         } else {
                   6743:             return;
                   6744:         }
                   6745:     }
                   6746: 
1.620     albertel 6747:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6748: # Free bre access to adm and meta resources
1.775     albertel 6749:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6750: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6751: 	&& ($priv eq 'bre')) {
1.14      www      6752: 	return 'F';
1.159     www      6753:     }
                   6754: 
1.545     banghart 6755: # Free bre access to user's own portfolio contents
1.714     raeburn  6756:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6757:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6758: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6759:         my %setters;
                   6760:         my ($startblock,$endblock) = 
                   6761:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6762:         if ($startblock && $endblock) {
                   6763:             return 'B';
                   6764:         } else {
                   6765:             return 'F';
                   6766:         }
1.545     banghart 6767:     }
                   6768: 
1.762     raeburn  6769: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6770:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6771:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6772:         if (exists($env{'request.course.id'})) {
                   6773:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6774:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6775:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6776:                 my $courseprivid=$env{'request.course.id'};
                   6777:                 $courseprivid=~s/\_/\//;
                   6778:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6779:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6780:                     return $1; 
1.762     raeburn  6781:                 } else {
                   6782:                     if ($env{'request.course.sec'}) {
                   6783:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6784:                     }
                   6785:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6786:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6787:                         return $2;
                   6788:                     }
1.714     raeburn  6789:                 }
                   6790:             }
                   6791:         }
                   6792:     }
                   6793: 
1.159     www      6794: # Free bre to public access
                   6795: 
                   6796:     if ($priv eq 'bre') {
1.238     www      6797:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6798: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6799:            return 'F'; 
                   6800:         }
1.238     www      6801:         if ($copyright eq 'priv') {
                   6802:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6803: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6804: 		return '';
                   6805:             }
                   6806:         }
                   6807:         if ($copyright eq 'domain') {
                   6808:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6809: 	    unless (($env{'user.domain'} eq $1) ||
                   6810:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6811: 		return '';
                   6812:             }
1.262     matthew  6813:         }
1.620     albertel 6814:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6815:             # Library role, so allow browsing of resources in this domain.
                   6816:             return 'F';
1.238     www      6817:         }
1.341     www      6818:         if ($copyright eq 'custom') {
                   6819: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6820:         }
1.14      www      6821:     }
1.264     matthew  6822:     # Domain coordinator is trying to create a course
1.620     albertel 6823:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6824:         # uri is the requested domain in this case.
                   6825:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6826:         # a role of dc for the domain in question.
1.620     albertel 6827:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6828:     }
1.29      www      6829: 
1.52      www      6830:     my $thisallowed='';
                   6831:     my $statecond=0;
                   6832:     my $courseprivid='';
                   6833: 
1.1039    raeburn  6834:     my $ownaccess;
1.1043    raeburn  6835:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6836:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6837:         if ($uri eq '') {
                   6838:             $ownaccess = 1;
                   6839:         } else {
                   6840:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6841:                 my $udom = $env{'user.domain'};
                   6842:                 my $uname = $env{'user.name'};
                   6843:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6844:                     $ownaccess = 1;
1.1040    raeburn  6845:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6846:                     unless ($uri =~ m{\.\./}) {
                   6847:                         $ownaccess = 1;
                   6848:                     }
                   6849:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6850:                     my $now = time;
                   6851:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6852:                         my $adom = $1;
                   6853:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6854:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6855:                                 my ($start,$end) = split('.',$env{$key});
                   6856:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6857:                                     $ownaccess = 1;
                   6858:                                     last;
                   6859:                                 }
                   6860:                             }
                   6861:                         }
                   6862:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6863:                         my $adom = $1;
                   6864:                         my $aname = $2;
1.1042    raeburn  6865:                         foreach my $role ('ca','aa') { 
                   6866:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6867:                                 my ($start,$end) =
                   6868:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6869:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6870:                                     $ownaccess = 1;
                   6871:                                     last;
                   6872:                                 }
1.1039    raeburn  6873:                             }
                   6874:                         }
                   6875:                     }
                   6876:                 }
                   6877:             }
                   6878:         }
                   6879:     }
                   6880: 
1.52      www      6881: # Course
                   6882: 
1.620     albertel 6883:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6884:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6885:             $thisallowed.=$1;
                   6886:         }
1.52      www      6887:     }
1.29      www      6888: 
1.52      www      6889: # Domain
                   6890: 
1.620     albertel 6891:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6892:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6893:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6894:             $thisallowed.=$1;
                   6895:         }
1.12      www      6896:     }
1.52      www      6897: 
1.1141    raeburn  6898: # User who is not author or co-author might still be able to edit
                   6899: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6900:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6901:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6902:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6903:             $thisallowed.=$1;
                   6904:         }
                   6905:     }
                   6906: 
1.52      www      6907: # Course: uri itself is a course
1.66      www      6908:     my $courseuri=$uri;
                   6909:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6910:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6911: 
1.620     albertel 6912:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6913:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6914:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6915:             $thisallowed.=$1;
                   6916:         }
1.12      www      6917:     }
1.29      www      6918: 
1.665     albertel 6919: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6920: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6921:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6922: 	$thisallowed='';
1.671     raeburn  6923:         my ($match)=&is_on_map($uri);
                   6924:         if ($match) {
                   6925:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6926:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  6927:                 my $value = $1;
                   6928:                 if ($noblockcheck) {
                   6929:                     $thisallowed.=$value;
1.1162    raeburn  6930:                 } else {
1.1281    raeburn  6931:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6932:                     if (@blockers > 0) {
                   6933:                         $thisallowed = 'B';
                   6934:                     } else {
                   6935:                         $thisallowed.=$value;
                   6936:                     }
1.1162    raeburn  6937:                 }
1.671     raeburn  6938:             }
                   6939:         } else {
1.705     albertel 6940:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6941:             if ($refuri) {
                   6942:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6943:                     $thisallowed='F';
1.671     raeburn  6944:                 } else {
                   6945:                     $refuri=&declutter($refuri);
                   6946:                     my ($match) = &is_on_map($refuri);
                   6947:                     if ($match) {
1.1281    raeburn  6948:                         if ($noblockcheck) {
                   6949:                             $thisallowed='F';
1.1162    raeburn  6950:                         } else {
1.1281    raeburn  6951:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6952:                             if (@blockers > 0) {
                   6953:                                 $thisallowed = 'B';
                   6954:                             } else {
                   6955:                                 $thisallowed='F';
                   6956:                             }
1.1162    raeburn  6957:                         }
1.671     raeburn  6958:                     }
1.669     raeburn  6959:                 }
1.671     raeburn  6960:             }
                   6961:         }
1.314     www      6962:     }
1.492     albertel 6963: 
1.766     albertel 6964:     if ($priv eq 'bre'
                   6965: 	&& $thisallowed ne 'F' 
                   6966: 	&& $thisallowed ne '2'
                   6967: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  6968: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 6969:     }
1.1250    raeburn  6970: 
1.52      www      6971: # Full access at system, domain or course-wide level? Exit.
1.29      www      6972:     if ($thisallowed=~/F/) {
                   6973: 	return 'F';
                   6974:     }
                   6975: 
1.52      www      6976: # If this is generating or modifying users, exit with special codes
1.29      www      6977: 
1.643     www      6978:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6979: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6980: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6981: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6982: 	    unless ($auname) { return $thisallowed; }
                   6983: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6984: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6985: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6986: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6987: 	}
1.52      www      6988: 	return $thisallowed;
                   6989:     }
                   6990: #
1.103     harris41 6991: # Gathered so far: system, domain and course wide privileges
1.52      www      6992: #
                   6993: # Course: See if uri or referer is an individual resource that is part of 
                   6994: # the course
                   6995: 
1.620     albertel 6996:     if ($env{'request.course.id'}) {
1.232     www      6997: 
1.620     albertel 6998:        $courseprivid=$env{'request.course.id'};
                   6999:        if ($env{'request.course.sec'}) {
                   7000:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7001:        }
                   7002:        $courseprivid=~s/\_/\//;
                   7003:        my $checkreferer=1;
1.232     www      7004:        my ($match,$cond)=&is_on_map($uri);
                   7005:        if ($match) {
                   7006:            $statecond=$cond;
1.620     albertel 7007:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7008:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7009:                my $value = $1;
                   7010:                if ($priv eq 'bre') {
1.1281    raeburn  7011:                    if ($noblockcheck) {
                   7012:                        $thisallowed.=$value;
1.1162    raeburn  7013:                    } else {
1.1281    raeburn  7014:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7015:                        if (@blockers > 0) {
                   7016:                            $thisallowed = 'B';
                   7017:                        } else {
                   7018:                            $thisallowed.=$value;
                   7019:                        }
1.1162    raeburn  7020:                    }
                   7021:                } else {
                   7022:                    $thisallowed.=$value;
                   7023:                }
1.52      www      7024:                $checkreferer=0;
                   7025:            }
1.29      www      7026:        }
1.83      www      7027:        
1.148     www      7028:        if ($checkreferer) {
1.620     albertel 7029: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7030:             unless ($refuri) {
1.800     albertel 7031:                 foreach my $key (keys(%env)) {
                   7032: 		    if ($key=~/^httpref\..*\*/) {
                   7033: 			my $pattern=$key;
1.156     www      7034:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7035:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7036:                         $pattern=~s/\//\\\//g;
1.152     www      7037:                         if ($orguri=~/$pattern/) {
1.800     albertel 7038: 			    $refuri=$env{$key};
1.148     www      7039:                         }
                   7040:                     }
1.191     harris41 7041:                 }
1.148     www      7042:             }
1.232     www      7043: 
1.148     www      7044:          if ($refuri) { 
1.152     www      7045: 	  $refuri=&declutter($refuri);
1.232     www      7046:           my ($match,$cond)=&is_on_map($refuri);
                   7047:             if ($match) {
                   7048:               my $refstatecond=$cond;
1.620     albertel 7049:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7050:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7051:                   my $value = $1;
                   7052:                   if ($priv eq 'bre') {
1.1281    raeburn  7053:                       if ($noblockcheck) {
                   7054:                           $thisallowed.=$value;
1.1162    raeburn  7055:                       } else {
1.1281    raeburn  7056:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7057:                           if (@blockers > 0) {
                   7058:                               $thisallowed = 'B';
                   7059:                           } else {
                   7060:                               $thisallowed.=$value;
                   7061:                           }
1.1162    raeburn  7062:                       }
                   7063:                   } else {
                   7064:                       $thisallowed.=$value;
                   7065:                   }
1.53      www      7066:                   $uri=$refuri;
                   7067:                   $statecond=$refstatecond;
1.52      www      7068:               }
                   7069:           }
1.148     www      7070:         }
1.29      www      7071:        }
1.52      www      7072:    }
1.29      www      7073: 
1.52      www      7074: #
1.103     harris41 7075: # Gathered now: all privileges that could apply, and condition number
1.52      www      7076: # 
                   7077: #
                   7078: # Full or no access?
                   7079: #
1.29      www      7080: 
1.52      www      7081:     if ($thisallowed=~/F/) {
                   7082: 	return 'F';
                   7083:     }
1.29      www      7084: 
1.52      www      7085:     unless ($thisallowed) {
                   7086:         return '';
                   7087:     }
1.29      www      7088: 
1.52      www      7089: # Restrictions exist, deal with them
                   7090: #
                   7091: #   C:according to course preferences
                   7092: #   R:according to resource settings
                   7093: #   L:unless locked
                   7094: #   X:according to user session state
                   7095: #
                   7096: 
                   7097: # Possibly locked functionality, check all courses
1.54      www      7098: # Locks might take effect only after 10 minutes cache expiration for other
                   7099: # courses, and 2 minutes for current course
1.52      www      7100: 
                   7101:     my $envkey;
                   7102:     if ($thisallowed=~/L/) {
1.1000    raeburn  7103:         foreach $envkey (keys(%env)) {
1.54      www      7104:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7105:                my $courseid=$2;
                   7106:                my $roleid=$1.'.'.$2;
1.92      www      7107:                $courseid=~s/^\///;
1.54      www      7108:                my $expiretime=600;
1.620     albertel 7109:                if ($env{'request.role'} eq $roleid) {
1.54      www      7110: 		  $expiretime=120;
                   7111:                }
                   7112: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7113:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7114:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7115: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7116:                }
1.620     albertel 7117:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7118:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7119: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7120:                        &log($env{'user.domain'},$env{'user.name'},
                   7121:                             $env{'user.home'},
1.57      www      7122:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7123:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7124:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7125: 		       return '';
                   7126:                    }
                   7127:                }
1.620     albertel 7128:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7129:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7130: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7131:                        &log($env{'user.domain'},$env{'user.name'},
                   7132:                             $env{'user.home'},
1.57      www      7133:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7134:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7135:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7136: 		       return '';
                   7137:                    }
                   7138:                }
                   7139: 	   }
1.29      www      7140:        }
1.52      www      7141:     }
                   7142:    
                   7143: #
                   7144: # Rest of the restrictions depend on selected course
                   7145: #
                   7146: 
1.620     albertel 7147:     unless ($env{'request.course.id'}) {
1.766     albertel 7148: 	if ($thisallowed eq 'A') {
                   7149: 	    return 'A';
1.814     raeburn  7150:         } elsif ($thisallowed eq 'B') {
                   7151:             return 'B';
1.766     albertel 7152: 	} else {
                   7153: 	    return '1';
                   7154: 	}
1.52      www      7155:     }
1.29      www      7156: 
1.52      www      7157: #
                   7158: # Now user is definitely in a course
                   7159: #
1.53      www      7160: 
                   7161: 
                   7162: # Course preferences
                   7163: 
                   7164:    if ($thisallowed=~/C/) {
1.620     albertel 7165:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7166:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7167:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7168: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7169: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7170: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7171: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7172: 			$env{'request.course.id'});
                   7173: 	   }
1.237     www      7174:            return '';
                   7175:        }
                   7176: 
1.620     albertel 7177:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7178: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7179: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7180: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7181: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7182: 			$env{'request.course.id'});
                   7183: 	   }
1.54      www      7184:            return '';
                   7185:        }
1.53      www      7186:    }
                   7187: 
                   7188: # Resource preferences
                   7189: 
                   7190:    if ($thisallowed=~/R/) {
1.620     albertel 7191:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7192:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7193: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7194: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7195: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7196: 	   }
                   7197: 	   return '';
1.54      www      7198:        }
1.53      www      7199:    }
1.30      www      7200: 
1.246     www      7201: # Restricted by state or randomout?
1.30      www      7202: 
1.52      www      7203:    if ($thisallowed=~/X/) {
1.620     albertel 7204:       if ($env{'acc.randomout'}) {
1.579     albertel 7205: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7206:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7207:             return ''; 
                   7208:          }
1.247     www      7209:       }
                   7210:       if (&condval($statecond)) {
1.52      www      7211: 	 return '2';
                   7212:       } else {
                   7213:          return '';
                   7214:       }
                   7215:    }
1.30      www      7216: 
1.766     albertel 7217:     if ($thisallowed eq 'A') {
                   7218: 	return 'A';
1.814     raeburn  7219:     } elsif ($thisallowed eq 'B') {
                   7220:         return 'B';
1.766     albertel 7221:     }
1.52      www      7222:    return 'F';
1.232     www      7223: }
1.1162    raeburn  7224: 
1.1192    raeburn  7225: # ------------------------------------------- Check construction space access
                   7226: 
                   7227: sub constructaccess {
                   7228:     my ($url,$setpriv)=@_;
                   7229: 
                   7230: # We do not allow editing of previous versions of files
                   7231:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7232: 
                   7233: # Get username and domain from URL
                   7234:     my ($ownername,$ownerdomain,$ownerhome);
                   7235: 
                   7236:     ($ownerdomain,$ownername) =
1.1297    damieng  7237:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)/});
1.1192    raeburn  7238: 
                   7239: # The URL does not really point to any authorspace, forget it
                   7240:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7241: 
                   7242: # Now we need to see if the user has access to the authorspace of
                   7243: # $ownername at $ownerdomain
                   7244: 
                   7245:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7246: # Real author for this?
                   7247:        $ownerhome = $env{'user.home'};
                   7248:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7249:           return ($ownername,$ownerdomain,$ownerhome);
                   7250:        }
                   7251:     } else {
                   7252: # Co-author for this?
                   7253:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7254:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7255:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7256:             return ($ownername,$ownerdomain,$ownerhome);
                   7257:         }
                   7258:     }
                   7259: 
                   7260: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7261: # we might as well leave
                   7262:    unless ($setpriv) { return ''; }
                   7263: 
                   7264: # Backdoor access?
                   7265:     my $allowed=&allowed('eco',$ownerdomain);
                   7266: # Nope
                   7267:     unless ($allowed) { return ''; }
                   7268: # Looks like we may have access, but could be locked by the owner of the construction space
                   7269:     if ($allowed eq 'U') {
                   7270:         my %blocked=&get('environment',['domcoord.author'],
                   7271:                          $ownerdomain,$ownername);
                   7272: # Is blocked by owner
                   7273:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7274:     }
                   7275:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7276: # Grant temporary access
                   7277:         my $then=$env{'user.login.time'};
1.1209    raeburn  7278:         my $update=$env{'user.update.time'};
1.1192    raeburn  7279:         if (!$update) { $update = $then; }
                   7280:         my $refresh=$env{'user.refresh.time'};
                   7281:         if (!$refresh) { $refresh = $update; }
                   7282:         my $now = time;
                   7283:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7284:                            $now,'ca','constructaccess');
                   7285:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7286:         return($ownername,$ownerdomain,$ownerhome);
                   7287:     }
                   7288: # No business here
                   7289:     return '';
                   7290: }
                   7291: 
1.1282    raeburn  7292: # ----------------------------------------------------------- Content Blocking
                   7293: 
                   7294: {
                   7295: # Caches for faster Course Contents display where content blocking
                   7296: # is in operation (i.e., interval param set) for timed quiz.
                   7297: #
                   7298: # User for whom data are being temporarily cached.
                   7299: my $cacheduser='';
                   7300: # Cached blockers for this user (a hash of blocking items). 
                   7301: my %cachedblockers=();
                   7302: # When the data were last cached.
                   7303: my $cachedlast='';
                   7304: 
                   7305: sub load_all_blockers {
                   7306:     my ($uname,$udom,$blocks)=@_;
                   7307:     if (($uname ne '') && ($udom ne '')) { 
                   7308:         if (($cacheduser eq $uname.':'.$udom) &&
                   7309:             (abs($cachedlast-time)<5)) {
                   7310:             return;
                   7311:         }
                   7312:     }
                   7313:     $cachedlast=time;
                   7314:     $cacheduser=$uname.':'.$udom;
                   7315:     %cachedblockers = &get_commblock_resources($blocks);
                   7316: }
                   7317: 
1.1162    raeburn  7318: sub get_comm_blocks {
                   7319:     my ($cdom,$cnum) = @_;
                   7320:     if ($cdom eq '' || $cnum eq '') {
                   7321:         return unless ($env{'request.course.id'});
                   7322:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7323:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7324:     }
                   7325:     my %commblocks;
                   7326:     my $hashid=$cdom.'_'.$cnum;
                   7327:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7328:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7329:         %commblocks = %{$blocksref};
                   7330:     } else {
                   7331:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7332:         my $cachetime = 600;
                   7333:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7334:     }
                   7335:     return %commblocks;
                   7336: }
                   7337: 
1.1282    raeburn  7338: sub get_commblock_resources {
                   7339:     my ($blocks) = @_;
                   7340:     my %blockers = ();
                   7341:     return %blockers unless ($env{'request.course.id'});
                   7342:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7343:     my %commblocks;
                   7344:     if (ref($blocks) eq 'HASH') {
                   7345:         %commblocks = %{$blocks};
                   7346:     } else {
                   7347:         %commblocks = &get_comm_blocks();
                   7348:     }
1.1282    raeburn  7349:     return %blockers unless (keys(%commblocks) > 0); 
                   7350:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7351:     return %blockers unless (ref($navmap));
1.1162    raeburn  7352:     my $now = time;
                   7353:     foreach my $block (keys(%commblocks)) {
                   7354:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7355:             my ($start,$end) = ($1,$2);
                   7356:             if ($start <= $now && $end >= $now) {
                   7357:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7358:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7359:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  7360:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7361:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  7362:                             }
                   7363:                         }
                   7364:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  7365:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7366:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7367:                             }
                   7368:                         }
                   7369:                     }
                   7370:                 }
                   7371:             }
                   7372:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7373:             my $item = $1;
1.1163    raeburn  7374:             my @to_test;
1.1162    raeburn  7375:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7376:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  7377:                     my @interval;
                   7378:                     my $type = 'map';
                   7379:                     if ($item eq 'course') {
                   7380:                         $type = 'course';
                   7381:                         @interval=&EXT("resource.0.interval");
                   7382:                     } else {
                   7383:                         if ($item =~ /___\d+___/) {
                   7384:                             $type = 'resource';
                   7385:                             @interval=&EXT("resource.0.interval",$item);
                   7386:                             if (ref($navmap)) {                        
                   7387:                                 my $res = $navmap->getBySymb($item); 
                   7388:                                 push(@to_test,$res);
                   7389:                             }
1.1162    raeburn  7390:                         } else {
1.1282    raeburn  7391:                             my $mapsymb = &symbread($item,1);
                   7392:                             if ($mapsymb) {
                   7393:                                 if (ref($navmap)) {
                   7394:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7395:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7396:                                     foreach my $res (@to_test) {
                   7397:                                         my $symb = $res->symb();
                   7398:                                         next if ($symb eq $mapsymb);
                   7399:                                         if ($symb ne '') {
                   7400:                                             @interval=&EXT("resource.0.interval",$symb);
                   7401:                                             if ($interval[1] eq 'map') {
                   7402:                                                 last;
1.1162    raeburn  7403:                                             }
                   7404:                                         }
                   7405:                                     }
                   7406:                                 }
                   7407:                             }
                   7408:                         }
1.1282    raeburn  7409:                     }
1.1292    raeburn  7410:                     if ($interval[0] =~ /^\d+/) {
                   7411:                         my ($timelimit) = split(/_/,$interval[0]);
1.1282    raeburn  7412:                         my $first_access;
                   7413:                         if ($type eq 'resource') {
                   7414:                             $first_access=&get_first_access($interval[1],$item);
                   7415:                         } elsif ($type eq 'map') {
                   7416:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7417:                         } else {
                   7418:                             $first_access=&get_first_access($interval[1]);
                   7419:                         }
                   7420:                         if ($first_access) {
1.1292    raeburn  7421:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  7422:                             if ($timesup > $now) {
                   7423:                                 my $activeblock;
                   7424:                                 foreach my $res (@to_test) {
1.1283    raeburn  7425:                                     if ($res->answerable()) {
1.1282    raeburn  7426:                                         $activeblock = 1;
                   7427:                                         last;
                   7428:                                     }
                   7429:                                 }
                   7430:                                 if ($activeblock) {
                   7431:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7432:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7433:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7434:                                          }
                   7435:                                     }
                   7436:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7437:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7438:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7439:                                         }
1.1162    raeburn  7440:                                     }
                   7441:                                 }
                   7442:                             }
                   7443:                         }
                   7444:                     }
                   7445:                 }
                   7446:             }
                   7447:         }
                   7448:     }
1.1282    raeburn  7449:     return %blockers;
1.1162    raeburn  7450: }
                   7451: 
1.1282    raeburn  7452: sub has_comm_blocking {
                   7453:     my ($priv,$symb,$uri,$blocks) = @_;
                   7454:     my @blockers;
                   7455:     return unless ($env{'request.course.id'});
                   7456:     return unless ($priv eq 'bre');
                   7457:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7458:     return if ($env{'request.state'} eq 'construct');
                   7459:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7460:     return unless (keys(%cachedblockers) > 0);
                   7461:     my (%possibles,@symbs);
                   7462:     if (!$symb) {
                   7463:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7464:     }
1.1282    raeburn  7465:     if ($symb) {
                   7466:         @symbs = ($symb);
                   7467:     } elsif (keys(%possibles)) { 
                   7468:         @symbs = keys(%possibles);
                   7469:     }
                   7470:     my $noblock;
                   7471:     foreach my $symb (@symbs) {
                   7472:         last if ($noblock);
                   7473:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7474:         foreach my $block (keys(%cachedblockers)) {
                   7475:             if ($block =~ /^firstaccess____(.+)$/) {
                   7476:                 my $item = $1;
                   7477:                 if (($item eq $map) || ($item eq $symb)) {
                   7478:                     $noblock = 1;
                   7479:                     last;
                   7480:                 }
                   7481:             }
                   7482:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7483:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7484:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7485:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7486:                             push(@blockers,$block);
                   7487:                         }
                   7488:                     }
                   7489:                 }
1.1162    raeburn  7490:             }
1.1282    raeburn  7491:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7492:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7493:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7494:                         push(@blockers,$block);
                   7495:                     }
                   7496:                 }
1.1162    raeburn  7497:             }
                   7498:         }
                   7499:     }
1.1282    raeburn  7500:     return if ($noblock);
                   7501:     return @blockers;
                   7502: }
1.1162    raeburn  7503: }
                   7504: 
1.1282    raeburn  7505: # -------------------------------- Deversion and split uri into path an filename   
                   7506: 
1.1133    foxr     7507: #
1.1282    raeburn  7508: #   Removes the version from a URI and
1.1133    foxr     7509: #   splits it in to its filename and path to the filename.
                   7510: #   Seems like File::Basename could have done this more clearly.
                   7511: #   Parameters:
                   7512: #      $uri   - input URI
                   7513: #   Returns:
                   7514: #     Two element list consisting of 
                   7515: #     $pathname  - the URI up to and excluding the trailing /
                   7516: #     $filename  - The part of the URI following the last /
                   7517: #  NOTE:
                   7518: #    Another realization of this is simply:
                   7519: #    use File::Basename;
                   7520: #    ...
                   7521: #    $uri = shift;
                   7522: #    $filename = basename($uri);
                   7523: #    $path     = dirname($uri);
                   7524: #    return ($filename, $path);
                   7525: #
                   7526: #     The implementation below is probably faster however.
                   7527: #
1.710     albertel 7528: sub split_uri_for_cond {
                   7529:     my $uri=&deversion(&declutter(shift));
                   7530:     my @uriparts=split(/\//,$uri);
                   7531:     my $filename=pop(@uriparts);
                   7532:     my $pathname=join('/',@uriparts);
                   7533:     return ($pathname,$filename);
                   7534: }
1.232     www      7535: # --------------------------------------------------- Is a resource on the map?
                   7536: 
                   7537: sub is_on_map {
1.710     albertel 7538:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7539:     #Trying to find the conditional for the file
1.620     albertel 7540:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7541: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7542:     if ($match) {
1.289     bowersj2 7543: 	return (1,$1);
                   7544:     } else {
1.434     www      7545: 	return (0,0);
1.289     bowersj2 7546:     }
1.12      www      7547: }
                   7548: 
1.427     www      7549: # --------------------------------------------------------- Get symb from alias
                   7550: 
                   7551: sub get_symb_from_alias {
                   7552:     my $symb=shift;
                   7553:     my ($map,$resid,$url)=&decode_symb($symb);
                   7554: # Already is a symb
                   7555:     if ($url) { return $symb; }
                   7556: # Must be an alias
                   7557:     my $aliassymb='';
                   7558:     my %bighash;
1.620     albertel 7559:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7560:                             &GDBM_READER(),0640)) {
                   7561:         my $rid=$bighash{'mapalias_'.$symb};
                   7562: 	if ($rid) {
                   7563: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7564: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7565: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7566: 	}
                   7567:         untie %bighash;
                   7568:     }
                   7569:     return $aliassymb;
                   7570: }
                   7571: 
1.12      www      7572: # ----------------------------------------------------------------- Define Role
                   7573: 
                   7574: sub definerole {
                   7575:   if (allowed('mcr','/')) {
                   7576:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7577:     foreach my $role (split(':',$sysrole)) {
                   7578: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7579:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7580:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7581: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7582:                return "refused:s:$crole&$cqual"; 
                   7583:             }
                   7584:         }
1.191     harris41 7585:     }
1.800     albertel 7586:     foreach my $role (split(':',$domrole)) {
                   7587: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7588:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7589:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7590: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7591:                return "refused:d:$crole&$cqual"; 
                   7592:             }
                   7593:         }
1.191     harris41 7594:     }
1.800     albertel 7595:     foreach my $role (split(':',$courole)) {
                   7596: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7597:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7598:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7599: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7600:                return "refused:c:$crole&$cqual"; 
                   7601:             }
                   7602:         }
1.191     harris41 7603:     }
1.620     albertel 7604:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7605:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7606: 	        "rolesdef_$rolename=".
                   7607:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7608:     return reply($command,$env{'user.home'});
1.12      www      7609:   } else {
                   7610:     return 'refused';
                   7611:   }
1.105     harris41 7612: }
                   7613: 
                   7614: # ---------------- Make a metadata query against the network of library servers
                   7615: 
                   7616: sub metadata_query {
1.1237    raeburn  7617:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7618:     my %rhash;
1.845     albertel 7619:     my %libserv = &all_library();
1.244     matthew  7620:     my @server_list = (defined($server_array) ? @$server_array
                   7621:                                               : keys(%libserv) );
                   7622:     for my $server (@server_list) {
1.1237    raeburn  7623:         my $domains = ''; 
                   7624:         if (ref($domains_hash) eq 'HASH') {
                   7625:             $domains = $domains_hash->{$server}; 
                   7626:         }
1.118     harris41 7627: 	unless ($custom or $customshow) {
1.1237    raeburn  7628: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7629: 	    $rhash{$server}=$reply;
                   7630: 	}
                   7631: 	else {
                   7632: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7633: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7634: 			     $server);
                   7635: 	    $rhash{$server}=$reply;
                   7636: 	}
1.112     harris41 7637:     }
1.118     harris41 7638:     return \%rhash;
1.240     www      7639: }
                   7640: 
                   7641: # ----------------------------------------- Send log queries and wait for reply
                   7642: 
                   7643: sub log_query {
                   7644:     my ($uname,$udom,$query,%filters)=@_;
                   7645:     my $uhome=&homeserver($uname,$udom);
                   7646:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7647:     my $uhost=&hostname($uhome);
1.800     albertel 7648:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7649:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7650:                        $uhome);
1.479     albertel 7651:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7652:     return get_query_reply($queryid);
                   7653: }
                   7654: 
1.818     raeburn  7655: # -------------------------- Update MySQL table for portfolio file
                   7656: 
                   7657: sub update_portfolio_table {
1.821     raeburn  7658:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7659:     if ($group ne '') {
                   7660:         $file_name =~s /^\Q$group\E//;
                   7661:     }
1.818     raeburn  7662:     my $homeserver = &homeserver($uname,$udom);
                   7663:     my $queryid=
1.821     raeburn  7664:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7665:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7666:     my $reply = &get_query_reply($queryid);
                   7667:     return $reply;
                   7668: }
                   7669: 
1.899     raeburn  7670: # -------------------------- Update MySQL allusers table
                   7671: 
                   7672: sub update_allusers_table {
                   7673:     my ($uname,$udom,$names) = @_;
                   7674:     my $homeserver = &homeserver($uname,$udom);
                   7675:     my $queryid=
                   7676:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7677:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7678:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7679:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7680:                'generation='.&escape($names->{'generation'}).'%%'.
                   7681:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7682:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7683:     return;
1.899     raeburn  7684: }
                   7685: 
1.508     raeburn  7686: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7687: 
                   7688: sub fetch_enrollment_query {
1.511     raeburn  7689:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7690:     my $homeserver;
1.547     raeburn  7691:     my $maxtries = 1;
1.508     raeburn  7692:     if ($context eq 'automated') {
                   7693:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7694:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7695:     } else {
                   7696:         $homeserver = &homeserver($cnum,$dom);
                   7697:     }
1.838     albertel 7698:     my $host=&hostname($homeserver);
1.506     raeburn  7699:     my $cmd = '';
1.1000    raeburn  7700:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7701:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7702:     }
                   7703:     $cmd =~ s/%%$//;
                   7704:     $cmd = &escape($cmd);
                   7705:     my $query = 'fetchenrollment';
1.620     albertel 7706:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7707:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7708:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7709:         return 'error: '.$queryid;
                   7710:     }
1.506     raeburn  7711:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7712:     my $tries = 1;
                   7713:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7714:         $reply = &get_query_reply($queryid);
                   7715:         $tries ++;
                   7716:     }
1.526     raeburn  7717:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7718:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7719:     } else {
1.901     albertel 7720:         my @responses = split(/:/,$reply);
1.515     raeburn  7721:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7722:             foreach my $line (@responses) {
                   7723:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7724:                 $$replyref{$key} = $value;
                   7725:             }
                   7726:         } else {
1.1117    foxr     7727:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7728:             foreach my $line (@responses) {
                   7729:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7730:                 $$replyref{$key} = $value;
                   7731:                 if ($value > 0) {
1.800     albertel 7732:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7733:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7734:                         my $destname = $pathname.'/'.$filename;
                   7735:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7736:                         if ($xml_classlist =~ /^error/) {
                   7737:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7738:                         } else {
1.506     raeburn  7739:                             if ( open(FILE,">$destname") ) {
                   7740:                                 print FILE &unescape($xml_classlist);
                   7741:                                 close(FILE);
1.526     raeburn  7742:                             } else {
                   7743:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7744:                             }
                   7745:                         }
                   7746:                     }
                   7747:                 }
                   7748:             }
                   7749:         }
                   7750:         return 'ok';
                   7751:     }
                   7752:     return 'error';
                   7753: }
                   7754: 
1.242     www      7755: sub get_query_reply {
                   7756:     my $queryid=shift;
1.1117    foxr     7757:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7758:     my $reply='';
                   7759:     for (1..100) {
1.1289    damieng  7760: 	sleep(0.2);
1.240     www      7761:         if (-e $replyfile.'.end') {
1.448     albertel 7762: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7763: 		$reply = join('',<$fh>);
                   7764: 		close($fh);
1.240     www      7765: 	   } else { return 'error: reply_file_error'; }
1.242     www      7766:            return &unescape($reply);
                   7767: 	}
1.240     www      7768:     }
1.242     www      7769:     return 'timeout:'.$queryid;
1.240     www      7770: }
                   7771: 
                   7772: sub courselog_query {
1.241     www      7773: #
                   7774: # possible filters:
                   7775: # url: url or symb
                   7776: # username
                   7777: # domain
                   7778: # action: view, submit, grade
                   7779: # start: timestamp
                   7780: # end: timestamp
                   7781: #
1.240     www      7782:     my (%filters)=@_;
1.620     albertel 7783:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7784:     if ($filters{'url'}) {
                   7785: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7786:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7787:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7788:     }
1.620     albertel 7789:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7790:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7791:     return &log_query($cname,$cdom,'courselog',%filters);
                   7792: }
                   7793: 
                   7794: sub userlog_query {
1.858     raeburn  7795: #
                   7796: # possible filters:
                   7797: # action: log check role
                   7798: # start: timestamp
                   7799: # end: timestamp
                   7800: #
1.240     www      7801:     my ($uname,$udom,%filters)=@_;
                   7802:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7803: }
                   7804: 
1.506     raeburn  7805: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7806: 
                   7807: sub auto_run {
1.508     raeburn  7808:     my ($cnum,$cdom) = @_;
1.876     raeburn  7809:     my $response = 0;
                   7810:     my $settings;
                   7811:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7812:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7813:         $settings = $domconfig{'autoenroll'};
                   7814:         if ($settings->{'run'} eq '1') {
                   7815:             $response = 1;
                   7816:         }
                   7817:     } else {
1.934     raeburn  7818:         my $homeserver;
                   7819:         if (&is_course($cdom,$cnum)) {
                   7820:             $homeserver = &homeserver($cnum,$cdom);
                   7821:         } else {
                   7822:             $homeserver = &domain($cdom,'primary');
                   7823:         }
                   7824:         if ($homeserver ne 'no_host') {
                   7825:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7826:         }
1.876     raeburn  7827:     }
1.506     raeburn  7828:     return $response;
                   7829: }
1.776     albertel 7830: 
1.506     raeburn  7831: sub auto_get_sections {
1.508     raeburn  7832:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7833:     my $homeserver;
                   7834:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7835:         $homeserver = &homeserver($cnum,$cdom);
                   7836:     }
                   7837:     if (!defined($homeserver)) { 
                   7838:         if ($cdom =~ /^$match_domain$/) {
                   7839:             $homeserver = &domain($cdom,'primary');
                   7840:         }
                   7841:     }
                   7842:     my @secs;
                   7843:     if (defined($homeserver)) {
                   7844:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7845:         unless ($response eq 'refused') {
                   7846:             @secs = split(/:/,$response);
                   7847:         }
1.506     raeburn  7848:     }
                   7849:     return @secs;
                   7850: }
1.776     albertel 7851: 
1.506     raeburn  7852: sub auto_new_course {
1.1099    raeburn  7853:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7854:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7855:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7856:     return $response;
                   7857: }
1.776     albertel 7858: 
1.506     raeburn  7859: sub auto_validate_courseID {
1.508     raeburn  7860:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7861:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7862:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7863:     return $response;
                   7864: }
1.776     albertel 7865: 
1.1007    raeburn  7866: sub auto_validate_instcode {
1.1020    raeburn  7867:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7868:     my ($homeserver,$response);
                   7869:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7870:         $homeserver = &homeserver($cnum,$cdom);
                   7871:     }
                   7872:     if (!defined($homeserver)) {
                   7873:         if ($cdom =~ /^$match_domain$/) {
                   7874:             $homeserver = &domain($cdom,'primary');
                   7875:         }
                   7876:     }
1.1065    raeburn  7877:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7878:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  7879:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7880:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7881: }
                   7882: 
1.506     raeburn  7883: sub auto_create_password {
1.873     raeburn  7884:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7885:     my ($homeserver,$response);
1.506     raeburn  7886:     my $create_passwd = 0;
                   7887:     my $authchk = '';
1.873     raeburn  7888:     if ($udom =~ /^$match_domain$/) {
                   7889:         $homeserver = &domain($udom,'primary');
                   7890:     }
                   7891:     if ($homeserver eq '') {
                   7892:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7893:             $homeserver = &homeserver($cnum,$cdom);
                   7894:         }
                   7895:     }
                   7896:     if ($homeserver eq '') {
                   7897:         $authchk = 'nodomain';
1.506     raeburn  7898:     } else {
1.873     raeburn  7899:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7900:         if ($response eq 'refused') {
                   7901:             $authchk = 'refused';
                   7902:         } else {
1.901     albertel 7903:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7904:         }
1.506     raeburn  7905:     }
                   7906:     return ($authparam,$create_passwd,$authchk);
                   7907: }
                   7908: 
1.706     raeburn  7909: sub auto_photo_permission {
                   7910:     my ($cnum,$cdom,$students) = @_;
                   7911:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7912:     my ($outcome,$perm_reqd,$conditions) = 
                   7913: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7914:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7915: 	return (undef,undef);
                   7916:     }
1.706     raeburn  7917:     return ($outcome,$perm_reqd,$conditions);
                   7918: }
                   7919: 
                   7920: sub auto_checkphotos {
                   7921:     my ($uname,$udom,$pid) = @_;
                   7922:     my $homeserver = &homeserver($uname,$udom);
                   7923:     my ($result,$resulttype);
                   7924:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7925: 				   &escape($uname).':'.&escape($pid),
                   7926: 				   $homeserver));
1.709     albertel 7927:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7928: 	return (undef,undef);
                   7929:     }
1.706     raeburn  7930:     if ($outcome) {
                   7931:         ($result,$resulttype) = split(/:/,$outcome);
                   7932:     } 
                   7933:     return ($result,$resulttype);
                   7934: }
                   7935: 
                   7936: sub auto_photochoice {
                   7937:     my ($cnum,$cdom) = @_;
                   7938:     my $homeserver = &homeserver($cnum,$cdom);
                   7939:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7940: 						       &escape($cdom),
                   7941: 						       $homeserver)));
1.709     albertel 7942:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7943: 	return (undef,undef);
                   7944:     }
1.706     raeburn  7945:     return ($update,$comment);
                   7946: }
                   7947: 
                   7948: sub auto_photoupdate {
                   7949:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7950:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7951:     my $host=&hostname($homeserver);
1.706     raeburn  7952:     my $cmd = '';
                   7953:     my $maxtries = 1;
1.800     albertel 7954:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7955:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7956:     }
                   7957:     $cmd =~ s/%%$//;
                   7958:     $cmd = &escape($cmd);
                   7959:     my $query = 'institutionalphotos';
                   7960:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7961:     unless ($queryid=~/^\Q$host\E\_/) {
                   7962:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7963:         return 'error: '.$queryid;
                   7964:     }
                   7965:     my $reply = &get_query_reply($queryid);
                   7966:     my $tries = 1;
                   7967:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7968:         $reply = &get_query_reply($queryid);
                   7969:         $tries ++;
                   7970:     }
                   7971:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7972:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7973:     } else {
                   7974:         my @responses = split(/:/,$reply);
                   7975:         my $outcome = shift(@responses); 
                   7976:         foreach my $item (@responses) {
                   7977:             my ($key,$value) = split(/=/,$item);
                   7978:             $$photo{$key} = $value;
                   7979:         }
                   7980:         return $outcome;
                   7981:     }
                   7982:     return 'error';
                   7983: }
                   7984: 
1.521     raeburn  7985: sub auto_instcode_format {
1.793     albertel 7986:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7987: 	$cat_order) = @_;
1.521     raeburn  7988:     my $courses = '';
1.772     raeburn  7989:     my @homeservers;
1.521     raeburn  7990:     if ($caller eq 'global') {
1.841     albertel 7991: 	my %servers = &get_servers($codedom,'library');
                   7992: 	foreach my $tryserver (keys(%servers)) {
                   7993: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7994: 		push(@homeservers,$tryserver);
                   7995: 	    }
1.584     raeburn  7996:         }
1.1022    raeburn  7997:     } elsif ($caller eq 'requests') {
                   7998:         if ($codedom =~ /^$match_domain$/) {
                   7999:             my $chome = &domain($codedom,'primary');
                   8000:             unless ($chome eq 'no_host') {
                   8001:                 push(@homeservers,$chome);
                   8002:             }
                   8003:         }
1.521     raeburn  8004:     } else {
1.772     raeburn  8005:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8006:     }
1.793     albertel 8007:     foreach my $code (keys(%{$instcodes})) {
                   8008:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8009:     }
                   8010:     chop($courses);
1.772     raeburn  8011:     my $ok_response = 0;
                   8012:     my $response;
                   8013:     while (@homeservers > 0 && $ok_response == 0) {
                   8014:         my $server = shift(@homeservers); 
                   8015:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8016:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8017:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8018: 		split(/:/,$response);
1.772     raeburn  8019:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8020:             push(@{$codetitles},&str2array($codetitles_str));
                   8021:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8022:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8023:             $ok_response = 1;
                   8024:         }
                   8025:     }
                   8026:     if ($ok_response) {
1.521     raeburn  8027:         return 'ok';
1.772     raeburn  8028:     } else {
                   8029:         return $response;
1.521     raeburn  8030:     }
                   8031: }
                   8032: 
1.792     raeburn  8033: sub auto_instcode_defaults {
                   8034:     my ($domain,$returnhash,$code_order) = @_;
                   8035:     my @homeservers;
1.841     albertel 8036: 
                   8037:     my %servers = &get_servers($domain,'library');
                   8038:     foreach my $tryserver (keys(%servers)) {
                   8039: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8040: 	    push(@homeservers,$tryserver);
                   8041: 	}
1.792     raeburn  8042:     }
1.841     albertel 8043: 
1.792     raeburn  8044:     my $response;
1.841     albertel 8045:     foreach my $server (@homeservers) {
1.792     raeburn  8046:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8047:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8048: 	
                   8049: 	foreach my $pair (split(/\&/,$response)) {
                   8050: 	    my ($name,$value)=split(/\=/,$pair);
                   8051: 	    if ($name eq 'code_order') {
                   8052: 		@{$code_order} = split(/\&/,&unescape($value));
                   8053: 	    } else {
                   8054: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8055: 	    }
                   8056: 	}
                   8057: 	return 'ok';
1.792     raeburn  8058:     }
1.841     albertel 8059: 
                   8060:     return $response;
1.1003    raeburn  8061: }
                   8062: 
                   8063: sub auto_possible_instcodes {
1.1007    raeburn  8064:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8065:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8066:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8067:         return;
                   8068:     }
1.1003    raeburn  8069:     my (@homeservers,$uhome);
                   8070:     if (defined(&domain($domain,'primary'))) {
                   8071:         $uhome=&domain($domain,'primary');
                   8072:         push(@homeservers,&domain($domain,'primary'));
                   8073:     } else {
                   8074:         my %servers = &get_servers($domain,'library');
                   8075:         foreach my $tryserver (keys(%servers)) {
                   8076:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8077:                 push(@homeservers,$tryserver);
                   8078:             }
                   8079:         }
                   8080:     }
                   8081:     my $response;
                   8082:     foreach my $server (@homeservers) {
                   8083:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8084:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8085:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8086:             split(':',$response);
                   8087:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8088:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8089:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8090:             my ($name,$value)=split('=',$item);
                   8091:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8092:         }
                   8093:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8094:             my ($name,$value)=split('=',$item);
                   8095:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8096:         }
                   8097:         return 'ok';
                   8098:     }
                   8099:     return $response;
                   8100: }
1.792     raeburn  8101: 
1.1010    raeburn  8102: sub auto_courserequest_checks {
                   8103:     my ($dom) = @_;
1.1020    raeburn  8104:     my ($homeserver,%validations);
                   8105:     if ($dom =~ /^$match_domain$/) {
                   8106:         $homeserver = &domain($dom,'primary');
                   8107:     }
                   8108:     unless ($homeserver eq 'no_host') {
                   8109:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8110:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8111:             my @items = split(/&/,$response);
                   8112:             foreach my $item (@items) {
                   8113:                 my ($key,$value) = split('=',$item);
                   8114:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8115:             }
                   8116:         }
                   8117:     }
1.1010    raeburn  8118:     return %validations; 
                   8119: }
                   8120: 
1.1020    raeburn  8121: sub auto_courserequest_validation {
1.1255    raeburn  8122:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8123:     my ($homeserver,$response);
                   8124:     if ($dom =~ /^$match_domain$/) {
                   8125:         $homeserver = &domain($dom,'primary');
                   8126:     }
1.1255    raeburn  8127:     unless ($homeserver eq 'no_host') {
                   8128:         my $customdata;
                   8129:         if (ref($custominfo) eq 'HASH') {
                   8130:             $customdata = &freeze_escape($custominfo);
                   8131:         }
1.1020    raeburn  8132:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8133:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8134:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8135:                                     $customdata,$homeserver));
1.1020    raeburn  8136:     }
                   8137:     return $response;
                   8138: }
                   8139: 
1.777     albertel 8140: sub auto_validate_class_sec {
1.918     raeburn  8141:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8142:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8143:     my $ownerlist;
                   8144:     if (ref($owners) eq 'ARRAY') {
                   8145:         $ownerlist = join(',',@{$owners});
                   8146:     } else {
                   8147:         $ownerlist = $owners;
                   8148:     }
1.773     raeburn  8149:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8150:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8151:     return $response;
                   8152: }
                   8153: 
1.1248    raeburn  8154: sub auto_crsreq_update {
                   8155:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8156:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8157:     my ($homeserver,%crsreqresponse);
                   8158:     if ($cdom =~ /^$match_domain$/) {
                   8159:         $homeserver = &domain($cdom,'primary');
                   8160:     }
                   8161:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8162:         my $info;
                   8163:         if (ref($inbound) eq 'HASH') {
                   8164:             $info = &freeze_escape($inbound);
                   8165:         }
                   8166:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8167:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8168:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8169:                             &escape($title).':'.&escape($code).':'.
                   8170:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8171:                             $homeserver);
1.1248    raeburn  8172:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8173:             my @items = split(/&/,$response);
                   8174:             foreach my $item (@items) {
                   8175:                 my ($key,$value) = split('=',$item);
                   8176:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8177:             }
                   8178:         }
                   8179:     }
                   8180:     return \%crsreqresponse;
                   8181: }
                   8182: 
1.1287    raeburn  8183: sub check_instcode_cloning {
                   8184:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8185:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8186:         return;
                   8187:     }
                   8188:     my $canclone;
                   8189:     if (@{$code_order} > 0) {
                   8190:         my $instcoderegexp ='^';
                   8191:         my @clonecodes = split(/\&/,$cloner);
                   8192:         foreach my $item (@{$code_order}) {
                   8193:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8194:                 foreach my $pair (@clonecodes) {
                   8195:                     my ($key,$val) = split(/\=/,$pair,2);
                   8196:                     $val = &unescape($val);
                   8197:                     if ($key eq $item) {
                   8198:                         $instcoderegexp .= '('.$val.')';
                   8199:                         last;
                   8200:                     }
                   8201:                 }
                   8202:             } else {
                   8203:                 $instcoderegexp .= $codedefaults->{$item};
                   8204:             }
                   8205:         }
                   8206:         $instcoderegexp .= '$';
                   8207:         my (@from,@to);
                   8208:         eval {
                   8209:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8210:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8211:         };
                   8212:         if ((@from > 0) && (@to > 0)) {
                   8213:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8214:             if (!@diffs) {
                   8215:                 $canclone = 1;
                   8216:             }
                   8217:         }
                   8218:     }
                   8219:     return $canclone;
                   8220: }
                   8221: 
                   8222: sub default_instcode_cloning {
                   8223:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8224:     my (%codedefaults,@code_order,$canclone);
                   8225:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8226:         %codedefaults = %{$codedefaultsref};
                   8227:         @code_order = @{$codeorderref};
                   8228:     } elsif ($clonedom) {
                   8229:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8230:     }
                   8231:     if (($domdefclone) && (@code_order)) {
                   8232:         my @clonecodes = split(/\+/,$domdefclone);
                   8233:         my $instcoderegexp ='^';
                   8234:         foreach my $item (@code_order) {
                   8235:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8236:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8237:             } else {
                   8238:                 $instcoderegexp .= $codedefaults{$item};
                   8239:             }
                   8240:         }
                   8241:         $instcoderegexp .= '$';
                   8242:         my (@from,@to);
                   8243:         eval {
                   8244:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8245:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8246:         };
                   8247:         if ((@from > 0) && (@to > 0)) {
                   8248:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8249:             if (!@diffs) {
                   8250:                 $canclone = 1;
                   8251:             }
                   8252:         }
                   8253:     }
                   8254:     return $canclone;
                   8255: }
                   8256: 
1.679     raeburn  8257: # ------------------------------------------------------- Course Group routines
                   8258: 
                   8259: sub get_coursegroups {
1.809     raeburn  8260:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8261:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8262: }
                   8263: 
1.679     raeburn  8264: sub modify_coursegroup {
                   8265:     my ($cdom,$cnum,$groupsettings) = @_;
                   8266:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8267: }
                   8268: 
1.809     raeburn  8269: sub toggle_coursegroup_status {
                   8270:     my ($cdom,$cnum,$group,$action) = @_;
                   8271:     my ($from_namespace,$to_namespace);
                   8272:     if ($action eq 'delete') {
                   8273:         $from_namespace = 'coursegroups';
                   8274:         $to_namespace = 'deleted_groups';
                   8275:     } else {
                   8276:         $from_namespace = 'deleted_groups';
                   8277:         $to_namespace = 'coursegroups';
                   8278:     }
                   8279:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8280:     if (my $tmp = &error(%curr_group)) {
                   8281:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8282:         return ('read error',$tmp);
                   8283:     } else {
                   8284:         my %savedsettings = %curr_group; 
1.809     raeburn  8285:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8286:         my $deloutcome;
                   8287:         if ($result eq 'ok') {
1.809     raeburn  8288:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8289:         } else {
                   8290:             return ('write error',$result);
                   8291:         }
                   8292:         if ($deloutcome eq 'ok') {
                   8293:             return 'ok';
                   8294:         } else {
                   8295:             return ('delete error',$deloutcome);
                   8296:         }
                   8297:     }
                   8298: }
                   8299: 
1.679     raeburn  8300: sub modify_group_roles {
1.957     raeburn  8301:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8302:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8303:     my $role = 'gr/'.&escape($userprivs);
                   8304:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8305:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8306:     if ($result eq 'ok') {
                   8307:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8308:     }
1.679     raeburn  8309:     return $result;
                   8310: }
                   8311: 
                   8312: sub modify_coursegroup_membership {
                   8313:     my ($cdom,$cnum,$membership) = @_;
                   8314:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8315:     return $result;
                   8316: }
                   8317: 
1.682     raeburn  8318: sub get_active_groups {
                   8319:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8320:     my $now = time;
                   8321:     my %groups = ();
                   8322:     foreach my $key (keys(%env)) {
1.811     albertel 8323:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8324:             my ($start,$end) = split(/\./,$env{$key});
                   8325:             if (($end!=0) && ($end<$now)) { next; }
                   8326:             if (($start!=0) && ($start>$now)) { next; }
                   8327:             if ($1 eq $cdom && $2 eq $cnum) {
                   8328:                 $groups{$3} = $env{$key} ;
                   8329:             }
                   8330:         }
                   8331:     }
                   8332:     return %groups;
                   8333: }
                   8334: 
1.683     raeburn  8335: sub get_group_membership {
                   8336:     my ($cdom,$cnum,$group) = @_;
                   8337:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8338: }
                   8339: 
                   8340: sub get_users_groups {
                   8341:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8342:     my @usersgroups;
1.683     raeburn  8343:     my $cachetime=1800;
                   8344: 
                   8345:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8346:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8347:     if (defined($cached)) {
1.734     albertel 8348:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8349:     } else {  
                   8350:         $grouplist = '';
1.816     raeburn  8351:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8352:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8353:         my $access_end = $env{'course.'.$courseid.
                   8354:                               '.default_enrollment_end_date'};
                   8355:         my $now = time;
                   8356:         foreach my $key (keys(%roleshash)) {
                   8357:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8358:                 my $group = $1;
                   8359:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8360:                     my $start = $2;
                   8361:                     my $end = $1;
                   8362:                     if ($start == -1) { next; } # deleted from group
                   8363:                     if (($start!=0) && ($start>$now)) { next; }
                   8364:                     if (($end!=0) && ($end<$now)) {
                   8365:                         if ($access_end && $access_end < $now) {
                   8366:                             if ($access_end - $end < 86400) {
                   8367:                                 push(@usersgroups,$group);
1.733     raeburn  8368:                             }
                   8369:                         }
1.817     raeburn  8370:                         next;
1.733     raeburn  8371:                     }
1.817     raeburn  8372:                     push(@usersgroups,$group);
1.683     raeburn  8373:                 }
                   8374:             }
                   8375:         }
1.817     raeburn  8376:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8377:         $grouplist = join(':',@usersgroups);
                   8378:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8379:     }
1.733     raeburn  8380:     return @usersgroups;
1.683     raeburn  8381: }
                   8382: 
                   8383: sub devalidate_getgroups_cache {
                   8384:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8385:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8386: 
1.683     raeburn  8387:     my $hashid="$udom:$uname:$courseid";
                   8388:     &devalidate_cache_new('getgroups',$hashid);
                   8389: }
                   8390: 
1.12      www      8391: # ------------------------------------------------------------------ Plain Text
                   8392: 
                   8393: sub plaintext {
1.988     raeburn  8394:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8395:     if ($short =~ m{^cr/}) {
1.758     albertel 8396: 	return (split('/',$short))[-1];
                   8397:     }
1.742     raeburn  8398:     if (!defined($cid)) {
                   8399:         $cid = $env{'request.course.id'};
                   8400:     }
                   8401:     my %rolenames = (
1.1008    raeburn  8402:                       Course    => 'std',
                   8403:                       Community => 'alt1',
1.742     raeburn  8404:                     );
1.1037    raeburn  8405:     if ($cid ne '') {
                   8406:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8407:             unless ($forcedefault) {
                   8408:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8409:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8410:                 return &Apache::lonlocal::mt($roletext);
                   8411:             }
                   8412:         }
                   8413:     }
                   8414:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8415:         (defined($rolenames{$type})) && 
                   8416:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8417:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8418:     } elsif ($cid ne '') {
                   8419:         my $crstype = $env{'course.'.$cid.'.type'};
                   8420:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8421:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8422:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8423:         }
1.742     raeburn  8424:     }
1.1037    raeburn  8425:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8426: }
                   8427: 
                   8428: # ----------------------------------------------------------------- Assign Role
                   8429: 
                   8430: sub assignrole {
1.957     raeburn  8431:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8432:         $context)=@_;
1.21      www      8433:     my $mrole;
                   8434:     if ($role =~ /^cr\//) {
1.393     www      8435:         my $cwosec=$url;
1.811     albertel 8436:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8437: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8438:            my $refused = 1;
                   8439:            if ($context eq 'requestcourses') {
                   8440:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8441:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8442:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8443:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8444:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8445:                            if ($crsenv{'internal.courseowner'} eq
                   8446:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8447:                                $refused = '';
                   8448:                            }
                   8449:                        }
                   8450:                    }
                   8451:                }
                   8452:            }
                   8453:            if ($refused) {
                   8454:                &logthis('Refused custom assignrole: '.
                   8455:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8456:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8457:                return 'refused';
                   8458:            }
1.104     www      8459:         }
1.21      www      8460:         $mrole='cr';
1.678     raeburn  8461:     } elsif ($role =~ /^gr\//) {
                   8462:         my $cwogrp=$url;
1.811     albertel 8463:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8464:         unless (&allowed('mdg',$cwogrp)) {
                   8465:             &logthis('Refused group assignrole: '.
                   8466:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8467:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8468:             return 'refused';
                   8469:         }
                   8470:         $mrole='gr';
1.21      www      8471:     } else {
1.82      www      8472:         my $cwosec=$url;
1.811     albertel 8473:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8474:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8475:             my $refused;
                   8476:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8477:                 if (!(&allowed('c'.$role,$url))) {
                   8478:                     $refused = 1;
                   8479:                 }
                   8480:             } else {
                   8481:                 $refused = 1;
                   8482:             }
1.947     raeburn  8483:             if ($refused) {
1.1045    raeburn  8484:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8485:                 if (!$selfenroll && $context eq 'course') {
                   8486:                     my %crsenv;
                   8487:                     if ($role eq 'cc' || $role eq 'co') {
                   8488:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8489:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8490:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8491:                                 if ($crsenv{'internal.courseowner'} eq 
                   8492:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8493:                                     $refused = '';
                   8494:                                 }
                   8495:                             }
                   8496:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8497:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8498:                                 if ($crsenv{'internal.courseowner'} eq 
                   8499:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8500:                                     $refused = '';
                   8501:                                 }
                   8502:                             }
                   8503:                         }
                   8504:                     }
                   8505:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8506:                     $refused = '';
1.1017    raeburn  8507:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8508:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8509:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8510:                         my $wrongcc;
                   8511:                         if ($cnum =~ /^$match_community$/) {
                   8512:                             $wrongcc = 1 if ($role eq 'cc');
                   8513:                         } else {
                   8514:                             $wrongcc = 1 if ($role eq 'co');
                   8515:                         }
                   8516:                         unless ($wrongcc) {
                   8517:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8518:                             if ($crsenv{'internal.courseowner'} eq 
                   8519:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8520:                                 $refused = '';
                   8521:                             }
1.1017    raeburn  8522:                         }
                   8523:                     }
1.1183    raeburn  8524:                 } elsif ($context eq 'requestauthor') {
                   8525:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8526:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8527:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8528:                             $refused = '';
                   8529:                         } else {
                   8530:                             my %domdefaults = &get_domain_defaults($udom);
                   8531:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8532:                                 my $checkbystatus;
                   8533:                                 if ($env{'user.adv'}) { 
                   8534:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8535:                                     if ($disposition eq 'automatic') {
                   8536:                                         $refused = '';
                   8537:                                     } elsif ($disposition eq '') {
                   8538:                                         $checkbystatus = 1;
                   8539:                                     } 
                   8540:                                 } else {
                   8541:                                     $checkbystatus = 1;
                   8542:                                 }
                   8543:                                 if ($checkbystatus) {
                   8544:                                     if ($env{'environment.inststatus'}) {
                   8545:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8546:                                         foreach my $type (@inststatuses) {
                   8547:                                             if (($type ne '') &&
                   8548:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8549:                                                 $refused = '';
                   8550:                                             }
                   8551:                                         }
                   8552:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8553:                                         $refused = '';
                   8554:                                     }
                   8555:                                 }
                   8556:                             }
                   8557:                         }
                   8558:                     }
1.1017    raeburn  8559:                 }
                   8560:                 if ($refused) {
1.947     raeburn  8561:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8562:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8563: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8564:                     return 'refused';
                   8565:                 }
1.932     raeburn  8566:             }
1.1131    raeburn  8567:         } elsif ($role eq 'au') {
                   8568:             if ($url ne '/'.$udom.'/') {
                   8569:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8570:                          ' to assign author role for '.$uname.':'.$udom.
                   8571:                          ' in domain: '.$url.' refused (wrong domain).');
                   8572:                 return 'refused';
                   8573:             }
1.104     www      8574:         }
1.21      www      8575:         $mrole=$role;
                   8576:     }
1.620     albertel 8577:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8578:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8579:     if ($end) { $command.='_'.$end; }
1.21      www      8580:     if ($start) {
                   8581: 	if ($end) { 
1.81      www      8582:            $command.='_'.$start; 
1.21      www      8583:         } else {
1.81      www      8584:            $command.='_0_'.$start;
1.21      www      8585:         }
                   8586:     }
1.739     raeburn  8587:     my $origstart = $start;
                   8588:     my $origend = $end;
1.957     raeburn  8589:     my $delflag;
1.357     www      8590: # actually delete
                   8591:     if ($deleteflag) {
1.373     www      8592: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8593: # modify command to delete the role
1.620     albertel 8594:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8595:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8596: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8597: # set start and finish to negative values for userrolelog
                   8598:            $start=-1;
                   8599:            $end=-1;
1.957     raeburn  8600:            $delflag = 1;
1.357     www      8601:         }
                   8602:     }
                   8603: # send command
1.349     www      8604:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8605: # log new user role if status is ok
1.349     www      8606:     if ($answer eq 'ok') {
1.663     raeburn  8607: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8608:         if (($role eq 'cc') || ($role eq 'in') ||
                   8609:             ($role eq 'ep') || ($role eq 'ad') ||
                   8610:             ($role eq 'ta') || ($role eq 'st') ||
                   8611:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8612:             ($role eq 'co')) {
1.1200    raeburn  8613: # for course roles, perform group memberships changes triggered by role change.
                   8614:             unless ($role =~ /^gr/) {
                   8615:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8616:                                                  $origstart,$selfenroll,$context);
                   8617:             }
1.1184    raeburn  8618:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8619:                            $selfenroll,$context);
                   8620:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8621:                  ($role eq 'au') || ($role eq 'dc')) {
                   8622:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8623:                            $context);
                   8624:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8625:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8626:                              $context); 
                   8627:         }
1.1053    raeburn  8628:         if ($role eq 'cc') {
                   8629:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8630:         }
1.349     www      8631:     }
                   8632:     return $answer;
1.169     harris41 8633: }
                   8634: 
1.1053    raeburn  8635: sub autoupdate_coowners {
                   8636:     my ($url,$end,$start,$uname,$udom) = @_;
                   8637:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8638:     if (($cdom ne '') && ($cnum ne '')) {
                   8639:         my $now = time;
                   8640:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8641:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8642:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8643:             my $instcode = $coursehash{'internal.coursecode'};
                   8644:             if ($instcode ne '') {
1.1056    raeburn  8645:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8646:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8647:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8648:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8649:                         if ($result eq 'valid') {
                   8650:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8651:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8652:                                     push(@newcoowners,$coowner);
                   8653:                                 }
                   8654:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8655:                                     push(@newcoowners,$uname.':'.$udom);
                   8656:                                 }
                   8657:                                 @newcoowners = sort(@newcoowners);
                   8658:                             } else {
                   8659:                                 push(@newcoowners,$uname.':'.$udom);
                   8660:                             }
                   8661:                         } else {
                   8662:                             if ($coursehash{'internal.co-owners'}) {
                   8663:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8664:                                     unless ($coowner eq $uname.':'.$udom) {
                   8665:                                         push(@newcoowners,$coowner);
                   8666:                                     }
                   8667:                                 }
                   8668:                                 unless (@newcoowners > 0) {
                   8669:                                     $delcoowners = 1;
                   8670:                                     $coowners = '';
                   8671:                                 }
                   8672:                             }
                   8673:                         }
                   8674:                         if (@newcoowners || $delcoowners) {
                   8675:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8676:                                             $delcoowners,@newcoowners);
                   8677:                         }
                   8678:                     }
                   8679:                 }
                   8680:             }
                   8681:         }
                   8682:     }
                   8683: }
                   8684: 
                   8685: sub store_coowners {
                   8686:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8687:     my $cid = $cdom.'_'.$cnum;
                   8688:     my ($coowners,$delresult,$putresult);
                   8689:     if (@newcoowners) {
                   8690:         $coowners = join(',',@newcoowners);
                   8691:         my %coownershash = (
                   8692:                             'internal.co-owners' => $coowners,
                   8693:                            );
                   8694:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8695:         if ($putresult eq 'ok') {
                   8696:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8697:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8698:             }
                   8699:         }
                   8700:     }
                   8701:     if ($delcoowners) {
                   8702:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8703:         if ($delresult eq 'ok') {
                   8704:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8705:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8706:             }
                   8707:         }
                   8708:     }
                   8709:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8710:         my %crsinfo =
                   8711:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8712:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8713:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8714:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8715:         }
                   8716:     }
                   8717: }
                   8718: 
1.169     harris41 8719: # -------------------------------------------------- Modify user authentication
1.197     www      8720: # Overrides without validation
                   8721: 
1.169     harris41 8722: sub modifyuserauth {
                   8723:     my ($udom,$uname,$umode,$upass)=@_;
                   8724:     my $uhome=&homeserver($uname,$udom);
1.197     www      8725:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8726:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8727:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8728:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8729:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8730: 		     &escape($upass),$uhome);
1.620     albertel 8731:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8732:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8733:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8734:     &log($udom,,$uname,$uhome,
1.620     albertel 8735:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8736:                                      $env{'user.name'}.', '.$umode.
1.197     www      8737:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8738:     unless ($reply eq 'ok') {
1.197     www      8739:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8740: 	return 'error: '.$reply;
                   8741:     }   
1.170     harris41 8742:     return 'ok';
1.80      www      8743: }
                   8744: 
1.81      www      8745: # --------------------------------------------------------------- Modify a user
1.80      www      8746: 
1.81      www      8747: sub modifyuser {
1.206     matthew  8748:     my ($udom,    $uname, $uid,
                   8749:         $umode,   $upass, $first,
                   8750:         $middle,  $last,  $gene,
1.1058    raeburn  8751:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8752:     $udom= &LONCAPA::clean_domain($udom);
                   8753:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8754:     my $showcandelete = 'none';
                   8755:     if (ref($candelete) eq 'ARRAY') {
                   8756:         if (@{$candelete} > 0) {
                   8757:             $showcandelete = join(', ',@{$candelete});
                   8758:         }
                   8759:     }
1.81      www      8760:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8761:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8762: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8763:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8764:                                      ' desiredhome not specified'). 
1.620     albertel 8765:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8766:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8767:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8768:     my $newuser;
                   8769:     if ($uhome eq 'no_host') {
                   8770:         $newuser = 1;
                   8771:     }
1.80      www      8772: # ----------------------------------------------------------------- Create User
1.406     albertel 8773:     if (($uhome eq 'no_host') && 
                   8774: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8775:         my $unhome='';
1.844     albertel 8776:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8777:             $unhome = $desiredhome;
1.620     albertel 8778: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8779: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8780:         } else { # load balancing routine for determining $unhome
1.81      www      8781:             my $loadm=10000000;
1.841     albertel 8782: 	    my %servers = &get_servers($udom,'library');
                   8783: 	    foreach my $tryserver (keys(%servers)) {
                   8784: 		my $answer=reply('load',$tryserver);
                   8785: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8786: 		    $loadm=$answer;
                   8787: 		    $unhome=$tryserver;
                   8788: 		}
1.80      www      8789: 	    }
                   8790:         }
                   8791:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8792: 	    return 'error: unable to find a home server for '.$uname.
                   8793:                    ' in domain '.$udom;
1.80      www      8794:         }
                   8795:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8796:                          &escape($upass),$unhome);
                   8797: 	unless ($reply eq 'ok') {
                   8798:             return 'error: '.$reply;
                   8799:         }   
1.230     stredwic 8800:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8801:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8802: 	    return 'error: unable verify users home machine.';
1.80      www      8803:         }
1.209     matthew  8804:     }   # End of creation of new user
1.80      www      8805: # ---------------------------------------------------------------------- Add ID
                   8806:     if ($uid) {
                   8807:        $uid=~tr/A-Z/a-z/;
                   8808:        my %uidhash=&idrget($udom,$uname);
1.196     www      8809:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8810:          && (!$forceid)) {
1.80      www      8811: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8812: 	      return 'error: user id "'.$uid.'" does not match '.
                   8813:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8814:           }
                   8815:        } else {
                   8816: 	  &idput($udom,($uname => $uid));
                   8817:        }
                   8818:     }
                   8819: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8820:     my @tmp=&get('environment',
1.899     raeburn  8821: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8822:                     'permanentemail','inststatus'],
1.134     albertel 8823: 		   $udom,$uname);
1.1075    raeburn  8824:     my (%names,%oldnames);
1.313     matthew  8825:     if ($tmp[0] =~ m/^error:.*/) { 
                   8826:         %names=(); 
                   8827:     } else {
                   8828:         %names = @tmp;
1.1075    raeburn  8829:         %oldnames = %names;
1.313     matthew  8830:     }
1.388     www      8831: #
1.1058    raeburn  8832: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8833: # of users did not contain them), do not overwrite existing values
                   8834: # unless field is in $candelete array ref.  
                   8835: #
                   8836: 
                   8837:     my @fields = ('firstname','middlename','lastname','generation',
                   8838:                   'permanentemail','id');
                   8839:     my %newvalues;
                   8840:     if (ref($candelete) eq 'ARRAY') {
                   8841:         foreach my $field (@fields) {
                   8842:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8843:                 if ($field eq 'firstname') {
                   8844:                     $names{$field} = $first;
                   8845:                 } elsif ($field eq 'middlename') {
                   8846:                     $names{$field} = $middle;
                   8847:                 } elsif ($field eq 'lastname') {
                   8848:                     $names{$field} = $last;
                   8849:                 } elsif ($field eq 'generation') { 
                   8850:                     $names{$field} = $gene;
                   8851:                 } elsif ($field eq 'permanentemail') {
                   8852:                     $names{$field} = $email;
                   8853:                 } elsif ($field eq 'id') {
                   8854:                     $names{$field}  = $uid;
                   8855:                 }
                   8856:             }
                   8857:         }
                   8858:     }
1.388     www      8859:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8860:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8861:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8862:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8863:     if ($email) {
                   8864:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8865:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8866:     }
1.899     raeburn  8867:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8868:     if (defined($inststatus)) {
                   8869:         $names{'inststatus'} = '';
                   8870:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8871:         if (ref($usertypes) eq 'HASH') {
                   8872:             my @okstatuses; 
                   8873:             foreach my $item (split(/:/,$inststatus)) {
                   8874:                 if (defined($usertypes->{$item})) {
                   8875:                     push(@okstatuses,$item);  
                   8876:                 }
                   8877:             }
                   8878:             if (@okstatuses) {
                   8879:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8880:             }
                   8881:         }
                   8882:     }
1.1075    raeburn  8883:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8884:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8885:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8886:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8887:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8888:     } else {
                   8889:         $logmsg .= ' during self creation';
                   8890:     }
1.1075    raeburn  8891:     my $changed;
                   8892:     if ($newuser) {
                   8893:         $changed = 1;
                   8894:     } else {
                   8895:         foreach my $field (@fields) {
                   8896:             if ($names{$field} ne $oldnames{$field}) {
                   8897:                 $changed = 1;
                   8898:                 last;
                   8899:             }
                   8900:         }
                   8901:     }
                   8902:     unless ($changed) {
                   8903:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8904:         &logthis($logmsg);
                   8905:         return 'ok';
                   8906:     }
                   8907:     my $reply = &put('environment', \%names, $udom,$uname);
                   8908:     if ($reply ne 'ok') { 
                   8909:         return 'error: '.$reply;
                   8910:     }
1.1087    raeburn  8911:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8912:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8913:     }
1.1075    raeburn  8914:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8915:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8916:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8917:     &logthis($logmsg);
1.134     albertel 8918:     return 'ok';
1.80      www      8919: }
                   8920: 
1.81      www      8921: # -------------------------------------------------------------- Modify student
1.80      www      8922: 
1.81      www      8923: sub modifystudent {
                   8924:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8925:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216    raeburn  8926:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8927:     if (!$cid) {
1.620     albertel 8928: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8929: 	    return 'not_in_class';
                   8930: 	}
1.80      www      8931:     }
                   8932: # --------------------------------------------------------------- Make the user
1.81      www      8933:     my $reply=&modifyuser
1.209     matthew  8934: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8935:          $desiredhome,$email,$inststatus);
1.80      www      8936:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8937:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  8938:     # student's environment
1.297     matthew  8939:     $uid = undef if (!$forceid);
1.455     albertel 8940:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  8941:                                         $gene,$usec,$end,$start,$type,$locktype,
                   8942:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8943:     return $reply;
                   8944: }
                   8945: 
                   8946: sub modify_student_enrollment {
1.1216    raeburn  8947:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8948:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8949:     my ($cdom,$cnum,$chome);
                   8950:     if (!$cid) {
1.620     albertel 8951: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8952: 	    return 'not_in_class';
                   8953: 	}
1.620     albertel 8954: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8955: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8956:     } else {
                   8957: 	($cdom,$cnum)=split(/_/,$cid);
                   8958:     }
1.620     albertel 8959:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8960:     if (!$chome) {
1.457     raeburn  8961: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8962:     }
1.455     albertel 8963:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8964:     # Make sure the user exists
1.81      www      8965:     my $uhome=&homeserver($uname,$udom);
                   8966:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8967: 	return 'error: no such user';
                   8968:     }
1.297     matthew  8969:     # Get student data if we were not given enough information
                   8970:     if (!defined($first)  || $first  eq '' || 
                   8971:         !defined($last)   || $last   eq '' || 
                   8972:         !defined($uid)    || $uid    eq '' || 
                   8973:         !defined($middle) || $middle eq '' || 
                   8974:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8975:         # They did not supply us with enough data to enroll the student, so
                   8976:         # we need to pick up more information.
1.297     matthew  8977:         my %tmp = &get('environment',
1.294     matthew  8978:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8979:                        ,$udom,$uname);
                   8980: 
1.800     albertel 8981:         #foreach my $key (keys(%tmp)) {
                   8982:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8983:         #}
1.294     matthew  8984:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8985:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8986:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8987:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8988:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8989:     }
1.556     albertel 8990:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8991:     my $user = "$uname:$udom";
                   8992:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8993:     my $reply=cput('classlist',
1.1148    raeburn  8994: 		   {$user => 
1.1216    raeburn  8995: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8996: 		   $cdom,$cnum);
1.1148    raeburn  8997:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8998:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8999:     } else { 
1.81      www      9000: 	return 'error: '.$reply;
                   9001:     }
1.297     matthew  9002:     # Add student role to user
1.83      www      9003:     my $uurl='/'.$cid;
1.81      www      9004:     $uurl=~s/\_/\//g;
                   9005:     if ($usec) {
                   9006: 	$uurl.='/'.$usec;
                   9007:     }
1.1148    raeburn  9008:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9009:                              $selfenroll,$context);
                   9010:     if ($result ne 'ok') {
                   9011:         if ($old_entry{$user} ne '') {
                   9012:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9013:         } else {
                   9014:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9015:         }
                   9016:     }
                   9017:     return $result; 
1.21      www      9018: }
                   9019: 
1.556     albertel 9020: sub format_name {
                   9021:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9022:     my $name;
                   9023:     if ($first ne 'lastname') {
                   9024: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9025:     } else {
                   9026: 	if ($lastname=~/\S/) {
                   9027: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9028: 	    $name=~s/\s+,/,/;
                   9029: 	} else {
                   9030: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9031: 	}
                   9032:     }
                   9033:     $name=~s/^\s+//;
                   9034:     $name=~s/\s+$//;
                   9035:     $name=~s/\s+/ /g;
                   9036:     return $name;
                   9037: }
                   9038: 
1.84      www      9039: # ------------------------------------------------- Write to course preferences
                   9040: 
                   9041: sub writecoursepref {
                   9042:     my ($courseid,%prefs)=@_;
                   9043:     $courseid=~s/^\///;
                   9044:     $courseid=~s/\_/\//g;
                   9045:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9046:     my $chome=homeserver($cnum,$cdomain);
                   9047:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9048: 	return 'error: no such course';
                   9049:     }
                   9050:     my $cstring='';
1.800     albertel 9051:     foreach my $pref (keys(%prefs)) {
                   9052: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9053:     }
1.84      www      9054:     $cstring=~s/\&$//;
                   9055:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9056: }
                   9057: 
                   9058: # ---------------------------------------------------------- Make/modify course
                   9059: 
                   9060: sub createcourse {
1.741     raeburn  9061:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9062:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9063:     $url=&declutter($url);
                   9064:     my $cid='';
1.1028    raeburn  9065:     if ($context eq 'requestcourses') {
                   9066:         my $can_create = 0;
                   9067:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9068:         if ($udom eq $ownerdom) {
                   9069:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9070:                                   $context)) {
                   9071:                 $can_create = 1;
                   9072:             }
                   9073:         } else {
                   9074:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9075:                                            $category);
                   9076:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9077:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9078:                 if (@curr > 0) {
                   9079:                     my @options = qw(approval validate autolimit);
                   9080:                     my $optregex = join('|',@options);
                   9081:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9082:                         $can_create = 1;
                   9083:                     }
                   9084:                 }
                   9085:             }
                   9086:         }
                   9087:         if ($can_create) {
                   9088:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9089:                 unless (&allowed('ccc',$udom)) {
                   9090:                     return 'refused'; 
                   9091:                 }
1.1017    raeburn  9092:             }
                   9093:         } else {
                   9094:             return 'refused';
                   9095:         }
1.1028    raeburn  9096:     } elsif (!&allowed('ccc',$udom)) {
                   9097:         return 'refused';
1.84      www      9098:     }
1.1011    raeburn  9099: # --------------------------------------------------------------- Get Unique ID
                   9100:     my $uname;
                   9101:     if ($cnum =~ /^$match_courseid$/) {
                   9102:         my $chome=&homeserver($cnum,$udom,'true');
                   9103:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9104:             $uname = $cnum;
                   9105:         } else {
1.1038    raeburn  9106:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9107:         }
                   9108:     } else {
1.1038    raeburn  9109:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9110:     }
                   9111:     return $uname if ($uname =~ /^error/);
                   9112: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9113:     if (!defined($course_server)) {
                   9114:         if (defined(&domain($udom,'primary'))) {
                   9115:             $course_server = &domain($udom,'primary');
                   9116:         } else {
                   9117:             $course_server = $env{'user.home'}; 
                   9118:         }
                   9119:     }
                   9120:     my %host_servers =
                   9121:         &Apache::lonnet::get_servers($udom,'library');
                   9122:     unless ($host_servers{$course_server}) {
                   9123:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9124:     }
1.84      www      9125: # ------------------------------------------------------------- Make the course
                   9126:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9127:                       $course_server);
1.84      www      9128:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9129:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9130:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9131: 	return 'error: no such course';
                   9132:     }
1.271     www      9133: # ----------------------------------------------------------------- Course made
1.516     raeburn  9134: # log existence
1.1029    raeburn  9135:     my $now = time;
1.918     raeburn  9136:     my $newcourse = {
                   9137:                     $udom.'_'.$uname => {
1.921     raeburn  9138:                                      description => $description,
                   9139:                                      inst_code   => $inst_code,
                   9140:                                      owner       => $course_owner,
                   9141:                                      type        => $crstype,
1.1029    raeburn  9142:                                      creator     => $env{'user.name'}.':'.
                   9143:                                                     $env{'user.domain'},
                   9144:                                      created     => $now,
                   9145:                                      context     => $context,
1.918     raeburn  9146:                                                 },
                   9147:                     };
1.921     raeburn  9148:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9149: # set toplevel url
1.271     www      9150:     my $topurl=$url;
                   9151:     unless ($nonstandard) {
                   9152: # ------------------------------------------ For standard courses, make top url
                   9153:         my $mapurl=&clutter($url);
1.278     www      9154:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9155:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9156: <map>
                   9157: <resource id="1" type="start"></resource>
                   9158: <resource id="2" src="$mapurl"></resource>
                   9159: <resource id="3" type="finish"></resource>
                   9160: <link index="1" from="1" to="2"></link>
                   9161: <link index="2" from="2" to="3"></link>
                   9162: </map>
                   9163: ENDINITMAP
                   9164:         $topurl=&declutter(
1.638     albertel 9165:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9166:                           );
                   9167:     }
                   9168: # ----------------------------------------------------------- Write preferences
1.84      www      9169:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9170:                      ('description'              => $description,
                   9171:                       'url'                      => $topurl,
                   9172:                       'internal.creator'         => $env{'user.name'}.':'.
                   9173:                                                     $env{'user.domain'},
                   9174:                       'internal.created'         => $now,
                   9175:                       'internal.creationcontext' => $context)
                   9176:                     );
1.84      www      9177:     return '/'.$udom.'/'.$uname;
                   9178: }
                   9179: 
1.1011    raeburn  9180: # ------------------------------------------------------------------- Create ID
                   9181: sub generate_coursenum {
1.1038    raeburn  9182:     my ($udom,$crstype) = @_;
1.1011    raeburn  9183:     my $domdesc = &domain($udom);
                   9184:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9185:     my $first;
                   9186:     if ($crstype eq 'Community') {
                   9187:         $first = '0';
                   9188:     } else {
                   9189:         $first = int(1+rand(9)); 
                   9190:     } 
                   9191:     my $uname=$first.
1.1011    raeburn  9192:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9193:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9194:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9195: # ----------------------------------------------- Make sure that does not exist
                   9196:     my $uhome=&homeserver($uname,$udom,'true');
                   9197:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9198:         if ($crstype eq 'Community') {
                   9199:             $first = '0';
                   9200:         } else {
                   9201:             $first = int(1+rand(9));
                   9202:         }
                   9203:         $uname=$first.
1.1011    raeburn  9204:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9205:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9206:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9207:         $uhome=&homeserver($uname,$udom,'true');
                   9208:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9209:             return 'error: unable to generate unique course-ID';
                   9210:         }
                   9211:     }
                   9212:     return $uname;
                   9213: }
                   9214: 
1.813     albertel 9215: sub is_course {
1.1167    droeschl 9216:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9217:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9218: 
                   9219:     return unless $cdom and $cnum;
                   9220: 
                   9221:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9222:         '.');
                   9223: 
1.1219    raeburn  9224:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9225:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9226: }
                   9227: 
1.1015    raeburn  9228: sub store_userdata {
                   9229:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9230:     my $result;
1.1016    raeburn  9231:     if ($datakey ne '') {
1.1013    raeburn  9232:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9233:             if ($udom eq '' || $uname eq '') {
                   9234:                 $udom = $env{'user.domain'};
                   9235:                 $uname = $env{'user.name'};
                   9236:             }
                   9237:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9238:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9239:                 $result = 'error: no_host';
                   9240:             } else {
                   9241:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9242:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9243: 
                   9244:                 my $namevalue='';
                   9245:                 foreach my $key (keys(%{$storehash})) {
                   9246:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9247:                 }
                   9248:                 $namevalue=~s/\&$//;
1.1224    raeburn  9249:                 unless ($namespace eq 'courserequests') {
                   9250:                     $datakey = &escape($datakey);
                   9251:                 }
1.1105    raeburn  9252:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9253:                                   $namevalue,$uhome);
1.1013    raeburn  9254:             }
                   9255:         } else {
                   9256:             $result = 'error: data to store was not a hash reference'; 
                   9257:         }
                   9258:     } else {
                   9259:         $result= 'error: invalid requestkey'; 
                   9260:     }
                   9261:     return $result;
                   9262: }
                   9263: 
1.21      www      9264: # ---------------------------------------------------------- Assign Custom Role
                   9265: 
                   9266: sub assigncustomrole {
1.957     raeburn  9267:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9268:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9269:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9270: }
                   9271: 
                   9272: # ----------------------------------------------------------------- Revoke Role
                   9273: 
                   9274: sub revokerole {
1.957     raeburn  9275:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9276:     my $now=time;
1.965     raeburn  9277:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9278: }
                   9279: 
                   9280: # ---------------------------------------------------------- Revoke Custom Role
                   9281: 
                   9282: sub revokecustomrole {
1.957     raeburn  9283:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9284:     my $now=time;
1.357     www      9285:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9286:            $deleteflag,$selfenroll,$context);
1.17      www      9287: }
                   9288: 
1.533     banghart 9289: # ------------------------------------------------------------ Disk usage
1.535     albertel 9290: sub diskusage {
1.955     raeburn  9291:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9292:     $directorypath =~ s/\/$//;
                   9293:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9294:                        .&escape($getpropath).':'.&escape($uname).':'
                   9295:                        .&escape($udom),homeserver($uname,$udom));
                   9296:     if ($listing eq 'unknown_cmd') {
                   9297:         if ($getpropath) {
                   9298:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9299:         }
                   9300:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9301:     }
1.514     albertel 9302:     return $listing;
1.512     banghart 9303: }
                   9304: 
1.566     banghart 9305: sub is_locked {
1.1096    raeburn  9306:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9307:     my @check;
                   9308:     my $is_locked;
1.1093    raeburn  9309:     push (@check,$file_name);
1.613     albertel 9310:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9311: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9312:     my ($tmp)=keys(%locked);
                   9313:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9314:     
1.566     banghart 9315:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9316:         $is_locked = 'false';
                   9317:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9318:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9319:                $is_locked = 'true';
1.1096    raeburn  9320:                if (ref($which) eq 'ARRAY') {
                   9321:                    push(@{$which},$entry);
                   9322:                } else {
                   9323:                    last;
                   9324:                }
1.745     raeburn  9325:            }
                   9326:        }
1.566     banghart 9327:     } else {
                   9328:         $is_locked = 'false';
                   9329:     }
1.1093    raeburn  9330:     return $is_locked;
1.566     banghart 9331: }
                   9332: 
1.759     albertel 9333: sub declutter_portfile {
                   9334:     my ($file) = @_;
1.833     albertel 9335:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9336:     return $file;
                   9337: }
                   9338: 
1.559     banghart 9339: # ------------------------------------------------------------- Mark as Read Only
                   9340: 
                   9341: sub mark_as_readonly {
                   9342:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9343:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9344:     my ($tmp)=keys(%current_permissions);
                   9345:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9346:     foreach my $file (@{$files}) {
1.759     albertel 9347: 	$file = &declutter_portfile($file);
1.561     banghart 9348:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9349:     }
1.613     albertel 9350:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9351:     return;
                   9352: }
                   9353: 
1.572     banghart 9354: # ------------------------------------------------------------Save Selected Files
                   9355: 
                   9356: sub save_selected_files {
                   9357:     my ($user, $path, @files) = @_;
                   9358:     my $filename = $user."savedfiles";
1.573     banghart 9359:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9360:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9361:     foreach my $file (@files) {
1.620     albertel 9362:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9363:     }
                   9364:     foreach my $file (@other_files) {
1.574     banghart 9365:         print (OUT $file."\n");
1.572     banghart 9366:     }
1.574     banghart 9367:     close (OUT);
1.572     banghart 9368:     return 'ok';
                   9369: }
                   9370: 
1.574     banghart 9371: sub clear_selected_files {
                   9372:     my ($user) = @_;
                   9373:     my $filename = $user."savedfiles";
1.1117    foxr     9374:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9375:     print (OUT undef);
                   9376:     close (OUT);
                   9377:     return ("ok");    
                   9378: }
                   9379: 
1.572     banghart 9380: sub files_in_path {
                   9381:     my ($user, $path) = @_;
                   9382:     my $filename = $user."savedfiles";
                   9383:     my %return_files;
1.1117    foxr     9384:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9385:     while (my $line_in = <IN>) {
1.574     banghart 9386:         chomp ($line_in);
                   9387:         my @paths_and_file = split (m!/!, $line_in);
                   9388:         my $file_part = pop (@paths_and_file);
                   9389:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9390:         $path_part.='/';
                   9391:         my $path_and_file = $path_part.$file_part;
                   9392:         if ($path_part eq $path) {
                   9393:             $return_files{$file_part}= 'selected';
                   9394:         }
                   9395:     }
1.574     banghart 9396:     close (IN);
                   9397:     return (\%return_files);
1.572     banghart 9398: }
                   9399: 
                   9400: # called in portfolio select mode, to show files selected NOT in current directory
                   9401: sub files_not_in_path {
                   9402:     my ($user, $path) = @_;
                   9403:     my $filename = $user."savedfiles";
                   9404:     my @return_files;
                   9405:     my $path_part;
1.1117    foxr     9406:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9407:     while (my $line = <IN>) {
1.572     banghart 9408:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9409:         my @paths_and_file = split(m|/|, $line);
                   9410:         my $file_part = pop(@paths_and_file);
                   9411:         chomp($file_part);
                   9412:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9413:         $path_part .= '/';
                   9414:         my $path_and_file = $path_part.$file_part;
                   9415:         if ($path_part ne $path) {
1.800     albertel 9416:             push(@return_files, ($path_and_file));
1.572     banghart 9417:         }
                   9418:     }
1.800     albertel 9419:     close(OUT);
1.574     banghart 9420:     return (@return_files);
1.572     banghart 9421: }
                   9422: 
1.1273    raeburn  9423: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9424:  
                   9425: sub portfiles_versioning {
                   9426:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   9427:     my $portfolio_root = '/userfiles/portfolio';
                   9428:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   9429:     foreach my $file (@{$portfiles}) {
                   9430:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   9431:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   9432:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   9433:         my $getpropath = 1;
                   9434:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   9435:                                              $stu_name,$getpropath);
                   9436:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   9437:         my $new_answer = 
                   9438:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   9439:         if ($new_answer ne 'problem getting file') {
                   9440:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   9441:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   9442:                               [$symb,$env{'request.course.id'},'graded']);
                   9443:         }
                   9444:     }
                   9445: }
                   9446: 
                   9447: sub get_next_version {
                   9448:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   9449:     my $version;
                   9450:     if (ref($dir_list) eq 'ARRAY') {
                   9451:         foreach my $row (@{$dir_list}) {
                   9452:             my ($file) = split(/\&/,$row,2);
                   9453:             my ($file_name,$file_version,$file_ext) =
                   9454:                 &file_name_version_ext($file);
                   9455:             if (($file_name eq $answer_name) &&
                   9456:                 ($file_ext eq $answer_ext)) {
                   9457:                      # gets here if filename and extension match,
                   9458:                      # regardless of version
                   9459:                 if ($file_version ne '') {
                   9460:                     # a versioned file is found  so save it for later
                   9461:                     if ($file_version > $version) {
                   9462:                         $version = $file_version;
                   9463:                     }
                   9464:                 }
                   9465:             }
                   9466:         }
                   9467:     }
                   9468:     $version ++;
                   9469:     return($version);
                   9470: }
                   9471: 
                   9472: sub version_selected_portfile {
                   9473:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   9474:     my ($answer_name,$answer_ver,$answer_ext) =
                   9475:         &file_name_version_ext($file_name);
                   9476:     my $new_answer;
                   9477:     $env{'form.copy'} =
                   9478:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   9479:     if($env{'form.copy'} eq '-1') {
                   9480:         $new_answer = 'problem getting file';
                   9481:     } else {
                   9482:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   9483:         my $copy_result = 
                   9484:             &finishuserfileupload($stu_name,$domain,'copy',
                   9485:                                   '/portfolio'.$directory.$new_answer);
                   9486:     }
                   9487:     undef($env{'form.copy'});
                   9488:     return ($new_answer);
                   9489: }
                   9490: 
                   9491: sub file_name_version_ext {
                   9492:     my ($file)=@_;
                   9493:     my @file_parts = split(/\./, $file);
                   9494:     my ($name,$version,$ext);
                   9495:     if (@file_parts > 1) {
                   9496:         $ext=pop(@file_parts);
                   9497:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   9498:             $version=pop(@file_parts);
                   9499:         }
                   9500:         $name=join('.',@file_parts);
                   9501:     } else {
                   9502:         $name=join('.',@file_parts);
                   9503:     }
                   9504:     return($name,$version,$ext);
                   9505: }
                   9506: 
1.745     raeburn  9507: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9508: 
1.745     raeburn  9509: sub get_portfile_permissions {
                   9510:     my ($domain,$user) = @_;
1.613     albertel 9511:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9512:     my ($tmp)=keys(%current_permissions);
                   9513:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9514:     return \%current_permissions;
                   9515: }
                   9516: 
                   9517: #---------------------------------------------Get portfolio file access controls
                   9518: 
1.749     raeburn  9519: sub get_access_controls {
1.745     raeburn  9520:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9521:     my %access;
                   9522:     my $real_file = $file;
                   9523:     $file =~ s/\.meta$//;
1.745     raeburn  9524:     if (defined($file)) {
1.749     raeburn  9525:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9526:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9527:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9528:             }
                   9529:         }
1.745     raeburn  9530:     } else {
1.749     raeburn  9531:         foreach my $key (keys(%{$current_permissions})) {
                   9532:             if ($key =~ /\0accesscontrol$/) {
                   9533:                 if (defined($group)) {
                   9534:                     if ($key !~ m-^\Q$group\E/-) {
                   9535:                         next;
                   9536:                     }
                   9537:                 }
                   9538:                 my ($fullpath) = split(/\0/,$key);
                   9539:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9540:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9541:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9542:                     }
                   9543:                 }
                   9544:             }
                   9545:         }
                   9546:     }
                   9547:     return %access;
                   9548: }
                   9549: 
                   9550: sub modify_access_controls {
                   9551:     my ($file_name,$changes,$domain,$user)=@_;
                   9552:     my ($outcome,$deloutcome);
                   9553:     my %store_permissions;
                   9554:     my %new_values;
                   9555:     my %new_control;
                   9556:     my %translation;
                   9557:     my @deletions = ();
                   9558:     my $now = time;
                   9559:     if (exists($$changes{'activate'})) {
                   9560:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9561:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9562:             my $numnew = scalar(@newitems);
                   9563:             for (my $i=0; $i<$numnew; $i++) {
                   9564:                 my $newkey = $newitems[$i];
                   9565:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9566:                 if ($newkey =~ /^\d+:/) { 
                   9567:                     $newkey =~ s/^(\d+)/$newid/;
                   9568:                     $translation{$1} = $newid;
                   9569:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9570:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9571:                     $translation{$1} = $newid;
                   9572:                 }
1.749     raeburn  9573:                 $new_values{$file_name."\0".$newkey} = 
                   9574:                                           $$changes{'activate'}{$newitems[$i]};
                   9575:                 $new_control{$newkey} = $now;
                   9576:             }
                   9577:         }
                   9578:     }
                   9579:     my %todelete;
                   9580:     my %changed_items;
                   9581:     foreach my $action ('delete','update') {
                   9582:         if (exists($$changes{$action})) {
                   9583:             if (ref($$changes{$action}) eq 'HASH') {
                   9584:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9585:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9586:                     if ($action eq 'delete') { 
                   9587:                         $todelete{$itemnum} = 1;
                   9588:                     } else {
                   9589:                         $changed_items{$itemnum} = $key;
                   9590:                     }
                   9591:                 }
1.745     raeburn  9592:             }
                   9593:         }
1.749     raeburn  9594:     }
                   9595:     # get lock on access controls for file.
                   9596:     my $lockhash = {
                   9597:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9598:                                                        ':'.$env{'user.domain'},
                   9599:                    }; 
                   9600:     my $tries = 0;
                   9601:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9602:    
1.1288    damieng  9603:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  9604:         $tries ++;
1.1289    damieng  9605:         sleep(0.1);
1.749     raeburn  9606:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9607:     }
                   9608:     if ($gotlock eq 'ok') {
                   9609:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9610:         my ($tmp)=keys(%curr_permissions);
                   9611:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9612:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9613:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9614:             if (ref($curr_controls) eq 'HASH') {
                   9615:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9616:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9617:                     if (defined($todelete{$itemnum})) {
                   9618:                         push(@deletions,$file_name."\0".$control_item);
                   9619:                     } else {
                   9620:                         if (defined($changed_items{$itemnum})) {
                   9621:                             $new_control{$changed_items{$itemnum}} = $now;
                   9622:                             push(@deletions,$file_name."\0".$control_item);
                   9623:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9624:                         } else {
                   9625:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9626:                         }
                   9627:                     }
1.745     raeburn  9628:                 }
                   9629:             }
                   9630:         }
1.970     raeburn  9631:         my ($group);
                   9632:         if (&is_course($domain,$user)) {
                   9633:             ($group,my $file) = split(/\//,$file_name,2);
                   9634:         }
1.749     raeburn  9635:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9636:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9637:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9638:         #  remove lock
                   9639:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9640:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9641:         my $sqlresult =
1.970     raeburn  9642:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9643:                                     $group);
1.749     raeburn  9644:     } else {
                   9645:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9646:     }
1.749     raeburn  9647:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9648: }
                   9649: 
1.827     raeburn  9650: sub make_public_indefinitely {
1.1271    raeburn  9651:     my (@requrl) = @_;
                   9652:     return &automated_portfile_access('public',\@requrl);
                   9653: }
                   9654: 
                   9655: sub automated_portfile_access {
                   9656:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  9657:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   9658:         return 'invalid';
                   9659:     }
1.1271    raeburn  9660:     my %urls;
                   9661:     if (ref($addsref) eq 'ARRAY') {
                   9662:         foreach my $requrl (@{$addsref}) {
                   9663:             if (&is_portfolio_url($requrl)) {
                   9664:                 unless (exists($urls{$requrl})) {
                   9665:                     $urls{$requrl} = 'add';
                   9666:                 }
                   9667:             }
                   9668:         }
                   9669:     }
                   9670:     if (ref($delsref) eq 'ARRAY') {
                   9671:         foreach my $requrl (@{$delsref}) { 
                   9672:             if (&is_portfolio_url($requrl)) {
                   9673:                 unless (exists($urls{$requrl})) {
                   9674:                     $urls{$requrl} = 'delete'; 
                   9675:                 }
                   9676:             }
                   9677:         }
                   9678:     }
                   9679:     unless (keys(%urls)) {
                   9680:         return 'invalid';
                   9681:     }
                   9682:     my $ip;
                   9683:     if ($accesstype eq 'ip') {
                   9684:         if (ref($info) eq 'HASH') {
                   9685:             if ($info->{'ip'} ne '') {
                   9686:                 $ip = $info->{'ip'};
                   9687:             }
                   9688:         }
                   9689:         if ($ip eq '') {
                   9690:             return 'invalid';
                   9691:         }
                   9692:     }
                   9693:     my $errors;
1.827     raeburn  9694:     my $now = time;
1.1271    raeburn  9695:     my %current_perms;
                   9696:     foreach my $requrl (sort(keys(%urls))) {
                   9697:         my $action;
                   9698:         if ($urls{$requrl} eq 'add') {
                   9699:             $action = 'activate';
                   9700:         } else {
                   9701:             $action = 'none';
                   9702:         }
                   9703:         my $aclnum = 0;
1.827     raeburn  9704:         my (undef,$udom,$unum,$file_name,$group) =
                   9705:             &parse_portfolio_url($requrl);
1.1271    raeburn  9706:         unless (exists($current_perms{$unum.':'.$udom})) {
                   9707:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   9708:         }
                   9709:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  9710:                                                    $group,$file_name);
                   9711:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9712:             my ($num,$scope,$end,$start) = 
                   9713:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  9714:             if ($scope eq $accesstype) {
                   9715:                 if (($start <= $now) && ($end == 0)) {
                   9716:                     if ($accesstype eq 'ip') {
                   9717:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   9718:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   9719:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   9720:                                     if ($urls{$requrl} eq 'add') {
                   9721:                                         $action = 'none';
                   9722:                                         last;
                   9723:                                     } else {
                   9724:                                         $action = 'delete';
                   9725:                                         $aclnum = $num;
                   9726:                                         last;
                   9727:                                     }
                   9728:                                 }
                   9729:                             }
                   9730:                         }
                   9731:                     } elsif ($accesstype eq 'public') {
                   9732:                         if ($urls{$requrl} eq 'add') {
                   9733:                             $action = 'none';
                   9734:                             last;
                   9735:                         } else {
                   9736:                             $action = 'delete';
                   9737:                             $aclnum = $num;
                   9738:                             last;
                   9739:                         }
                   9740:                     }
                   9741:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  9742:                     $action = 'update';
                   9743:                     $aclnum = $num;
1.1271    raeburn  9744:                     last;
1.827     raeburn  9745:                 }
                   9746:             }
                   9747:         }
                   9748:         if ($action eq 'none') {
1.1271    raeburn  9749:             next;
1.827     raeburn  9750:         } else {
                   9751:             my %changes;
                   9752:             my $newend = 0;
                   9753:             my $newstart = $now;
1.1271    raeburn  9754:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  9755:             $changes{$action}{$newkey} = {
1.1271    raeburn  9756:                 type => $accesstype,
1.827     raeburn  9757:                 time => {
                   9758:                     start => $newstart,
                   9759:                     end   => $newend,
                   9760:                 },
                   9761:             };
1.1271    raeburn  9762:             if ($accesstype eq 'ip') {
                   9763:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   9764:             }
1.827     raeburn  9765:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9766:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  9767:             unless ($outcome eq 'ok') {
                   9768:                 $errors .= $outcome.' ';
                   9769:             }
1.827     raeburn  9770:         }
1.1271    raeburn  9771:     }
                   9772:     if ($errors) {
                   9773:         $errors =~ s/\s$//;
                   9774:         return $errors;
1.827     raeburn  9775:     } else {
1.1271    raeburn  9776:         return 'ok';
1.827     raeburn  9777:     }
                   9778: }
                   9779: 
1.745     raeburn  9780: #------------------------------------------------------Get Marked as Read Only
                   9781: 
                   9782: sub get_marked_as_readonly {
                   9783:     my ($domain,$user,$what,$group) = @_;
                   9784:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9785:     my @readonly_files;
1.629     banghart 9786:     my $cmp1=$what;
                   9787:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9788:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9789:         if (defined($group)) {
                   9790:             if ($file_name !~ m-^\Q$group\E/-) {
                   9791:                 next;
                   9792:             }
                   9793:         }
1.561     banghart 9794:         if (ref($value) eq "ARRAY"){
                   9795:             foreach my $stored_what (@{$value}) {
1.629     banghart 9796:                 my $cmp2=$stored_what;
1.759     albertel 9797:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9798:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9799:                 }
1.629     banghart 9800:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9801:                     push(@readonly_files, $file_name);
1.745     raeburn  9802:                     last;
1.563     banghart 9803:                 } elsif (!defined($what)) {
                   9804:                     push(@readonly_files, $file_name);
1.745     raeburn  9805:                     last;
1.561     banghart 9806:                 }
                   9807:             }
1.745     raeburn  9808:         }
1.561     banghart 9809:     }
                   9810:     return @readonly_files;
                   9811: }
1.577     banghart 9812: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9813: 
1.577     banghart 9814: sub get_marked_as_readonly_hash {
1.745     raeburn  9815:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9816:     my %readonly_files;
1.745     raeburn  9817:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9818:         if (defined($group)) {
                   9819:             if ($file_name !~ m-^\Q$group\E/-) {
                   9820:                 next;
                   9821:             }
                   9822:         }
1.577     banghart 9823:         if (ref($value) eq "ARRAY"){
                   9824:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9825:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9826:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9827:                         if ($lock_descriptor eq 'graded') {
                   9828:                             $readonly_files{$file_name} = 'graded';
                   9829:                         } elsif ($lock_descriptor eq 'handback') {
                   9830:                             $readonly_files{$file_name} = 'handback';
                   9831:                         } else {
                   9832:                             if (!exists($readonly_files{$file_name})) {
                   9833:                                 $readonly_files{$file_name} = 'locked';
                   9834:                             }
                   9835:                         }
1.745     raeburn  9836:                     }
1.750     banghart 9837:                 } 
1.577     banghart 9838:             }
                   9839:         } 
                   9840:     }
                   9841:     return %readonly_files;
                   9842: }
1.559     banghart 9843: # ------------------------------------------------------------ Unmark as Read Only
                   9844: 
                   9845: sub unmark_as_readonly {
1.629     banghart 9846:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9847:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9848:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9849:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9850:     my $symb_crs = $what;
                   9851:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9852:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9853:     my ($tmp)=keys(%current_permissions);
                   9854:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9855:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9856:     foreach my $file (@readonly_files) {
1.759     albertel 9857: 	my $clean_file = &declutter_portfile($file);
                   9858: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9859: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9860:         my @new_locks;
                   9861:         my @del_keys;
                   9862:         if (ref($current_locks) eq "ARRAY"){
                   9863:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9864:                 my $compare=$locker;
1.749     raeburn  9865:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9866:                     $compare=join('',@{$locker});
1.746     raeburn  9867:                     if ($compare ne $symb_crs) {
                   9868:                         push(@new_locks, $locker);
                   9869:                     }
1.563     banghart 9870:                 }
                   9871:             }
1.650     albertel 9872:             if (scalar(@new_locks) > 0) {
1.563     banghart 9873:                 $current_permissions{$file} = \@new_locks;
                   9874:             } else {
                   9875:                 push(@del_keys, $file);
1.613     albertel 9876:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9877:                 delete($current_permissions{$file});
1.563     banghart 9878:             }
                   9879:         }
1.561     banghart 9880:     }
1.613     albertel 9881:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9882:     return;
                   9883: }
1.512     banghart 9884: 
1.17      www      9885: # ------------------------------------------------------------ Directory lister
                   9886: 
                   9887: sub dirlist {
1.955     raeburn  9888:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9889:     $uri=~s/^\///;
                   9890:     $uri=~s/\/$//;
1.253     stredwic 9891:     my ($udom, $uname);
1.955     raeburn  9892:     if ($getuserdir) {
1.253     stredwic 9893:         $udom = $userdomain;
                   9894:         $uname = $username;
1.955     raeburn  9895:     } else {
                   9896:         (undef,$udom,$uname)=split(/\//,$uri);
                   9897:         if(defined($userdomain)) {
                   9898:             $udom = $userdomain;
                   9899:         }
                   9900:         if(defined($username)) {
                   9901:             $uname = $username;
                   9902:         }
1.253     stredwic 9903:     }
1.955     raeburn  9904:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9905: 
1.955     raeburn  9906:     $dirRoot = $perlvar{'lonDocRoot'};
                   9907:     if (defined($getpropath)) {
                   9908:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9909:         $dirRoot =~ s/\/$//;
1.955     raeburn  9910:     } elsif (defined($getuserdir)) {
                   9911:         my $subdir=$uname.'__';
                   9912:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9913:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9914:                    ."/$udom/$subdir/$uname";
                   9915:     } elsif (defined($alternateRoot)) {
                   9916:         $dirRoot = $alternateRoot;
1.751     banghart 9917:     }
1.253     stredwic 9918: 
                   9919:     if($udom) {
                   9920:         if($uname) {
1.1135    raeburn  9921:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9922:             if ($uhome eq 'no_host') {
                   9923:                 return ([],'no_host');
                   9924:             }
1.955     raeburn  9925:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9926:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9927:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9928:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9929:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9930:             } else {
                   9931:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9932:             }
1.605     matthew  9933:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9934:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9935:                 @listing_results = split(/:/,$listing);
                   9936:             } else {
                   9937:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9938:             }
1.1135    raeburn  9939:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9940:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9941:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9942:                 return ([],$listing);
                   9943:             } else {
                   9944:                 return (\@listing_results);
1.1135    raeburn  9945:             }
1.955     raeburn  9946:         } elsif(!$alternateRoot) {
1.1136    raeburn  9947:             my (%allusers,%listerror);
1.841     albertel 9948: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9949:  	    foreach my $tryserver (keys(%servers)) {
                   9950:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9951:                                   &escape($udom),$tryserver);
                   9952:                 if ($listing eq 'unknown_cmd') {
                   9953: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9954: 				      $udom, $tryserver);
                   9955:                 } else {
                   9956:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9957:                 }
1.841     albertel 9958: 		if ($listing eq 'unknown_cmd') {
                   9959: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9960: 				      $udom, $tryserver);
                   9961: 		    @listing_results = split(/:/,$listing);
                   9962: 		} else {
                   9963: 		    @listing_results =
                   9964: 			map { &unescape($_); } split(/:/,$listing);
                   9965: 		}
1.1136    raeburn  9966:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9967:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9968:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9969:                     $listerror{$tryserver} = $listing;
                   9970:                 } else {
1.841     albertel 9971: 		    foreach my $line (@listing_results) {
                   9972: 			my ($entry) = split(/&/,$line,2);
                   9973: 			$allusers{$entry} = 1;
                   9974: 		    }
                   9975: 		}
1.253     stredwic 9976:             }
1.1136    raeburn  9977:             my @alluserslist=();
1.800     albertel 9978:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9979:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9980:             }
1.1136    raeburn  9981:             return (\@alluserslist);
1.253     stredwic 9982:         } else {
1.1136    raeburn  9983:             return ([],'missing username');
1.253     stredwic 9984:         }
1.955     raeburn  9985:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9986:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9987:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9988:         return (\@all_domains);
1.955     raeburn  9989:     } else {
1.1136    raeburn  9990:         return ([],'missing domain');
1.275     stredwic 9991:     }
                   9992: }
                   9993: 
                   9994: # --------------------------------------------- GetFileTimestamp
                   9995: # This function utilizes dirlist and returns the date stamp for
                   9996: # when it was last modified.  It will also return an error of -1
                   9997: # if an error occurs
                   9998: 
                   9999: sub GetFileTimestamp {
1.955     raeburn  10000:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10001:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10002:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10003:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10004:                                     undef,$getuserdir);
                   10005:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10006:         return -1;
                   10007:     }
                   10008:     if (ref($fileref) eq 'ARRAY') {
                   10009:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10010:         # @stats contains first the filename, then the stat output
                   10011:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10012:     } else {
                   10013:         return -1;
1.253     stredwic 10014:     }
1.26      www      10015: }
                   10016: 
1.712     albertel 10017: sub stat_file {
                   10018:     my ($uri) = @_;
1.787     albertel 10019:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10020: 
1.955     raeburn  10021:     my ($udom,$uname,$file);
1.712     albertel 10022:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10023: 	($udom,$uname,$file) =
1.811     albertel 10024: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10025: 	$file = 'userfiles/'.$file;
                   10026:     }
                   10027:     if ($uri =~ m-^/res/-) {
                   10028: 	($udom,$uname) = 
1.807     albertel 10029: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10030: 	$file = $uri;
                   10031:     }
                   10032: 
                   10033:     if (!$udom || !$uname || !$file) {
                   10034: 	# unable to handle the uri
                   10035: 	return ();
                   10036:     }
1.956     raeburn  10037:     my $getpropath;
                   10038:     if ($file =~ /^userfiles\//) {
                   10039:         $getpropath = 1;
                   10040:     }
1.1136    raeburn  10041:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10042:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10043:         return ();
                   10044:     } else {
                   10045:         if (ref($listref) eq 'ARRAY') {
                   10046:             my @stats = split('&',$listref->[0]);
                   10047: 	    shift(@stats); #filename is first
                   10048: 	    return @stats;
                   10049:         }
1.712     albertel 10050:     }
                   10051:     return ();
                   10052: }
                   10053: 
1.26      www      10054: # -------------------------------------------------------- Value of a Condition
                   10055: 
1.713     albertel 10056: # gets the value of a specific preevaluated condition
                   10057: #    stored in the string  $env{user.state.<cid>}
                   10058: # or looks up a condition reference in the bighash and if if hasn't
                   10059: # already been evaluated recurses into docondval to get the value of
                   10060: # the condition, then memoizing it to 
                   10061: #   $env{user.state.<cid>.<condition>}
1.40      www      10062: sub directcondval {
                   10063:     my $number=shift;
1.620     albertel 10064:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10065: 	&Apache::lonuserstate::evalstate();
                   10066:     }
1.713     albertel 10067:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10068: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10069:     } elsif ($number =~ /^_/) {
                   10070: 	my $sub_condition;
                   10071: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10072: 		&GDBM_READER(),0640)) {
                   10073: 	    $sub_condition=$bighash{'conditions'.$number};
                   10074: 	    untie(%bighash);
                   10075: 	}
                   10076: 	my $value = &docondval($sub_condition);
1.949     raeburn  10077: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10078: 	return $value;
                   10079:     }
1.620     albertel 10080:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10081:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10082:     } else {
                   10083:        return 2;
                   10084:     }
                   10085: }
                   10086: 
1.713     albertel 10087: # get the collection of conditions for this resource
1.26      www      10088: sub condval {
                   10089:     my $condidx=shift;
1.54      www      10090:     my $allpathcond='';
1.713     albertel 10091:     foreach my $cond (split(/\|/,$condidx)) {
                   10092: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10093: 	    $allpathcond.=
                   10094: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10095: 	}
1.191     harris41 10096:     }
1.54      www      10097:     $allpathcond=~s/\|$//;
1.713     albertel 10098:     return &docondval($allpathcond);
                   10099: }
                   10100: 
                   10101: #evaluates an expression of conditions
                   10102: sub docondval {
                   10103:     my ($allpathcond) = @_;
                   10104:     my $result=0;
                   10105:     if ($env{'request.course.id'}
                   10106: 	&& defined($allpathcond)) {
                   10107: 	my $operand='|';
                   10108: 	my @stack;
                   10109: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10110: 	    if ($chunk eq '(') {
                   10111: 		push @stack,($operand,$result);
                   10112: 	    } elsif ($chunk eq ')') {
                   10113: 		my $before=pop @stack;
                   10114: 		if (pop @stack eq '&') {
                   10115: 		    $result=$result>$before?$before:$result;
                   10116: 		} else {
                   10117: 		    $result=$result>$before?$result:$before;
                   10118: 		}
                   10119: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10120: 		$operand=$chunk;
                   10121: 	    } else {
                   10122: 		my $new=directcondval($chunk);
                   10123: 		if ($operand eq '&') {
                   10124: 		    $result=$result>$new?$new:$result;
                   10125: 		} else {
                   10126: 		    $result=$result>$new?$result:$new;
                   10127: 		}
                   10128: 	    }
                   10129: 	}
1.26      www      10130:     }
                   10131:     return $result;
1.421     albertel 10132: }
                   10133: 
                   10134: # ---------------------------------------------------- Devalidate courseresdata
                   10135: 
                   10136: sub devalidatecourseresdata {
                   10137:     my ($coursenum,$coursedomain)=@_;
                   10138:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10139:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10140: }
                   10141: 
1.763     www      10142: 
1.200     www      10143: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10144: #
                   10145: #  Parameters:
                   10146: #      $coursenum    - Number of the course.
                   10147: #      $coursedomain - Domain at which the course was created.
                   10148: #  Returns:
                   10149: #     A hash of the course parameters along (I think) with timestamps
                   10150: #     and version info.
1.877     foxr     10151: 
1.624     albertel 10152: sub get_courseresdata {
                   10153:     my ($coursenum,$coursedomain)=@_;
1.200     www      10154:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10155:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10156:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10157:     my %dumpreply;
1.417     albertel 10158:     unless (defined($cached)) {
1.624     albertel 10159: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10160: 	$result=\%dumpreply;
1.251     albertel 10161: 	my ($tmp) = keys(%dumpreply);
                   10162: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10163: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10164: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10165: 	    return $tmp;
1.416     albertel 10166: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10167: 	    $result=undef;
1.599     albertel 10168: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10169: 	}
                   10170:     }
1.624     albertel 10171:     return $result;
                   10172: }
                   10173: 
1.633     albertel 10174: sub devalidateuserresdata {
                   10175:     my ($uname,$udom)=@_;
                   10176:     my $hashid="$udom:$uname";
                   10177:     &devalidate_cache_new('userres',$hashid);
                   10178: }
                   10179: 
1.624     albertel 10180: sub get_userresdata {
                   10181:     my ($uname,$udom)=@_;
                   10182:     #most student don\'t have any data set, check if there is some data
                   10183:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10184: 
                   10185:     my $hashid="$udom:$uname";
                   10186:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10187:     if (!defined($cached)) {
                   10188: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10189: 	$result=\%resourcedata;
                   10190: 	&do_cache_new('userres',$hashid,$result,600);
                   10191:     }
                   10192:     my ($tmp)=keys(%$result);
                   10193:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10194: 	return $result;
                   10195:     }
                   10196:     #error 2 occurs when the .db doesn't exist
                   10197:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  10198:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10199: 	    &logthis("<font color=\"blue\">WARNING:".
                   10200: 		     " Trying to get resource data for ".
                   10201: 		     $uname." at ".$udom.": ".
                   10202: 		     $tmp."</font>");
                   10203:         }
1.624     albertel 10204:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10205: 	#&EXT_cache_set($udom,$uname);
                   10206: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10207: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10208:     }
                   10209:     return $tmp;
                   10210: }
1.879     foxr     10211: #----------------------------------------------- resdata - return resource data
                   10212: #  Purpose:
                   10213: #    Return resource data for either users or for a course.
                   10214: #  Parameters:
                   10215: #     $name      - Course/user name.
                   10216: #     $domain    - Name of the domain the user/course is registered on.
                   10217: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   10218: #     @which     - Array of names of resources desired.
                   10219: #  Returns:
                   10220: #     The value of the first reasource in @which that is found in the
                   10221: #     resource hash.
                   10222: #  Exceptional Conditions:
                   10223: #     If the $type passed in is not valid (not the string 'course' or 
                   10224: #     'user', an undefined  reference is returned.
                   10225: #     If none of the resources are found, an undef is returned
1.624     albertel 10226: sub resdata {
                   10227:     my ($name,$domain,$type,@which)=@_;
                   10228:     my $result;
                   10229:     if ($type eq 'course') {
                   10230: 	$result=&get_courseresdata($name,$domain);
                   10231:     } elsif ($type eq 'user') {
                   10232: 	$result=&get_userresdata($name,$domain);
                   10233:     }
                   10234:     if (!ref($result)) { return $result; }    
1.251     albertel 10235:     foreach my $item (@which) {
1.927     albertel 10236: 	if (defined($result->{$item->[0]})) {
                   10237: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10238: 	}
1.250     albertel 10239:     }
1.291     albertel 10240:     return undef;
1.200     www      10241: }
                   10242: 
1.1298    raeburn  10243: sub get_domain_ltitools {
                   10244:     my ($cdom) = @_;
                   10245:     my %ltitools;
                   10246:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   10247:     if (defined($cached)) {
                   10248:         if (ref($result) eq 'HASH') {
                   10249:             %ltitools = %{$result};
                   10250:         }
                   10251:     } else {
                   10252:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   10253:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   10254:             %ltitools = %{$domconfig{'ltitools'}};
                   10255:         }
                   10256:         my $cachetime = 24*60*60;
                   10257:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   10258:     }
                   10259:     return %ltitools;
                   10260: }
                   10261: 
1.1236    raeburn  10262: sub get_numsuppfiles {
                   10263:     my ($cnum,$cdom,$ignorecache)=@_;
                   10264:     my $hashid=$cnum.':'.$cdom;
                   10265:     my ($suppcount,$cached);
                   10266:     unless ($ignorecache) {
                   10267:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10268:     }
                   10269:     unless (defined($cached)) {
                   10270:         my $chome=&homeserver($cnum,$cdom);
                   10271:         unless ($chome eq 'no_host') {
                   10272:             ($suppcount,my $errors) = (0,0);
                   10273:             my $suppmap = 'supplemental.sequence';
                   10274:             ($suppcount,$errors) = 
                   10275:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10276:         }
                   10277:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10278:     }
                   10279:     return $suppcount;
                   10280: }
                   10281: 
1.379     matthew  10282: #
                   10283: # EXT resource caching routines
                   10284: #
                   10285: 
                   10286: sub clear_EXT_cache_status {
1.383     albertel 10287:     &delenv('cache.EXT.');
1.379     matthew  10288: }
                   10289: 
                   10290: sub EXT_cache_status {
                   10291:     my ($target_domain,$target_user) = @_;
1.383     albertel 10292:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10293:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10294:         # We know already the user has no data
                   10295:         return 1;
                   10296:     } else {
                   10297:         return 0;
                   10298:     }
                   10299: }
                   10300: 
                   10301: sub EXT_cache_set {
                   10302:     my ($target_domain,$target_user) = @_;
1.383     albertel 10303:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10304:     #&appenv({$cachename => time});
1.379     matthew  10305: }
                   10306: 
1.28      www      10307: # --------------------------------------------------------- Value of a Variable
1.58      www      10308: sub EXT {
1.715     albertel 10309: 
1.1228    raeburn  10310:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10311:     unless ($varname) { return ''; }
1.218     albertel 10312:     #get real user name/domain, courseid and symb
                   10313:     my $courseid;
1.359     albertel 10314:     my $publicuser;
1.427     www      10315:     if ($symbparm) {
                   10316: 	$symbparm=&get_symb_from_alias($symbparm);
                   10317:     }
1.218     albertel 10318:     if (!($uname && $udom)) {
1.790     albertel 10319:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10320:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10321:     } else {
1.620     albertel 10322: 	$courseid=$env{'request.course.id'};
1.218     albertel 10323:     }
1.48      www      10324:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10325:     my $rest;
1.320     albertel 10326:     if (defined($therest[0])) {
1.48      www      10327:        $rest=join('.',@therest);
                   10328:     } else {
                   10329:        $rest='';
                   10330:     }
1.320     albertel 10331: 
1.57      www      10332:     my $qualifierrest=$qualifier;
                   10333:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10334:     my $spacequalifierrest=$space;
                   10335:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10336:     if ($realm eq 'user') {
1.48      www      10337: # --------------------------------------------------------------- user.resource
                   10338: 	if ($space eq 'resource') {
1.651     albertel 10339: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10340: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10341: 		 &&
1.744     albertel 10342: 		 ($symbparm eq &symbread()) ) {	
                   10343: 		# if we are in the middle of processing the resource the
                   10344: 		# get the value we are planning on committing
                   10345:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10346:                     return $Apache::lonhomework::results{$qualifierrest};
                   10347:                 } else {
                   10348:                     return $Apache::lonhomework::history{$qualifierrest};
                   10349:                 }
1.335     albertel 10350: 	    } else {
1.359     albertel 10351: 		my %restored;
1.620     albertel 10352: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10353: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10354: 		} else {
                   10355: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10356: 		}
1.335     albertel 10357: 		return $restored{$qualifierrest};
                   10358: 	    }
1.48      www      10359: # ----------------------------------------------------------------- user.access
                   10360:         } elsif ($space eq 'access') {
1.218     albertel 10361: 	    # FIXME - not supporting calls for a specific user
1.48      www      10362:             return &allowed($qualifier,$rest);
                   10363: # ------------------------------------------ user.preferences, user.environment
                   10364:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10365: 	    if (($uname eq $env{'user.name'}) &&
                   10366: 		($udom eq $env{'user.domain'})) {
                   10367: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10368: 	    } else {
1.359     albertel 10369: 		my %returnhash;
                   10370: 		if (!$publicuser) {
                   10371: 		    %returnhash=&userenvironment($udom,$uname,
                   10372: 						 $qualifierrest);
                   10373: 		}
1.218     albertel 10374: 		return $returnhash{$qualifierrest};
                   10375: 	    }
1.48      www      10376: # ----------------------------------------------------------------- user.course
                   10377:         } elsif ($space eq 'course') {
1.218     albertel 10378: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10379:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10380: # ------------------------------------------------------------------- user.role
                   10381:         } elsif ($space eq 'role') {
1.218     albertel 10382: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10383:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10384:             if ($qualifier eq 'value') {
                   10385: 		return $role;
                   10386:             } elsif ($qualifier eq 'extent') {
                   10387:                 return $where;
                   10388:             }
                   10389: # ----------------------------------------------------------------- user.domain
                   10390:         } elsif ($space eq 'domain') {
1.218     albertel 10391:             return $udom;
1.48      www      10392: # ------------------------------------------------------------------- user.name
                   10393:         } elsif ($space eq 'name') {
1.218     albertel 10394:             return $uname;
1.48      www      10395: # ---------------------------------------------------- Any other user namespace
1.29      www      10396:         } else {
1.359     albertel 10397: 	    my %reply;
                   10398: 	    if (!$publicuser) {
                   10399: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10400: 	    }
                   10401: 	    return $reply{$qualifierrest};
1.48      www      10402:         }
1.236     www      10403:     } elsif ($realm eq 'query') {
                   10404: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10405:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10406: 						[$spacequalifierrest]);
1.620     albertel 10407: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10408:    } elsif ($realm eq 'request') {
1.48      www      10409: # ------------------------------------------------------------- request.browser
                   10410:         if ($space eq 'browser') {
1.1145    bisitz   10411:             return $env{'browser.'.$qualifier};
1.57      www      10412: # ------------------------------------------------------------ request.filename
                   10413:         } else {
1.620     albertel 10414:             return $env{'request.'.$spacequalifierrest};
1.29      www      10415:         }
1.28      www      10416:     } elsif ($realm eq 'course') {
1.48      www      10417: # ---------------------------------------------------------- course.description
1.620     albertel 10418:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10419:     } elsif ($realm eq 'resource') {
1.165     www      10420: 
1.620     albertel 10421: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10422: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10423: 	}
1.693     albertel 10424: 
1.1232    raeburn  10425:         if ($qualifier eq '') {
                   10426: 	    if ($space eq 'title') {
                   10427: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10428: 	        return &gettitle($symbparm);
                   10429: 	    }
1.693     albertel 10430: 	
1.1232    raeburn  10431: 	    if ($space eq 'map') {
                   10432: 	        my ($map) = &decode_symb($symbparm);
                   10433: 	        return &symbread($map);
                   10434: 	    }
                   10435:             if ($space eq 'maptitle') {
                   10436:                 my ($map) = &decode_symb($symbparm);
                   10437:                 return &gettitle($map);
                   10438:             }
                   10439: 	    if ($space eq 'filename') {
                   10440: 	        if ($symbparm) {
                   10441: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10442: 	        }
                   10443: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10444: 	    }
1.1232    raeburn  10445: 
1.1233    raeburn  10446:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10447:                 if ($space eq 'visibleparts') {
                   10448:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10449:                     my $item;
                   10450:                     if (ref($navmap)) {
                   10451:                         my $res = $navmap->getBySymb($symbparm);
                   10452:                         my $parts = $res->parts();
                   10453:                         if (ref($parts) eq 'ARRAY') {
                   10454:                             $item = join(',',@{$parts});
                   10455:                         }
                   10456:                         undef($navmap);
1.1232    raeburn  10457:                     }
1.1233    raeburn  10458:                     return $item;
1.1232    raeburn  10459:                 }
                   10460:             }
                   10461:         }
1.693     albertel 10462: 
                   10463: 	my ($section, $group, @groups);
1.593     albertel 10464: 	my ($courselevelm,$courselevel);
1.1228    raeburn  10465:         if (($courseid eq '') && ($cid)) {
                   10466:             $courseid = $cid;
                   10467:         }
                   10468: 	if (($symbparm && $courseid) && 
                   10469: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      10470: 
1.218     albertel 10471: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10472: 
1.60      www      10473: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10474: 	    my $symbp=$symbparm;
1.735     albertel 10475: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10476: 
                   10477: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10478: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10479: 
1.620     albertel 10480: 	    if (($env{'user.name'} eq $uname) &&
                   10481: 		($env{'user.domain'} eq $udom)) {
                   10482: 		$section=$env{'request.course.sec'};
1.733     raeburn  10483:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10484:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10485: 	    } else {
1.539     albertel 10486: 		if (! defined($usection)) {
1.551     albertel 10487: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10488: 		} else {
                   10489: 		    $section = $usection;
                   10490: 		}
1.733     raeburn  10491:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10492: 	    }
                   10493: 
                   10494: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10495: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10496: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10497: 
1.593     albertel 10498: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10499: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10500: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10501: 
1.60      www      10502: # ----------------------------------------------------------- first, check user
1.624     albertel 10503: 
                   10504: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10505: 				       ([$courselevelr,'resource'],
                   10506: 					[$courselevelm,'map'     ],
                   10507: 					[$courselevel, 'course'  ]));
1.931     albertel 10508: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10509: 
1.594     albertel 10510: # ------------------------------------------------ second, check some of course
1.684     raeburn  10511:             my $coursereply;
1.691     raeburn  10512:             if (@groups > 0) {
                   10513:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10514:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10515:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10516:             }
1.96      www      10517: 
1.684     raeburn  10518: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10519: 				  $env{'course.'.$courseid.'.domain'},
                   10520: 				  'course',
                   10521: 				  ([$seclevelr,   'resource'],
                   10522: 				   [$seclevelm,   'map'     ],
                   10523: 				   [$seclevel,    'course'  ],
                   10524: 				   [$courselevelr,'resource']));
                   10525: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10526: 
1.60      www      10527: # ------------------------------------------------------ third, check map parms
1.218     albertel 10528: 	    my %parmhash=();
                   10529: 	    my $thisparm='';
                   10530: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10531: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10532: 		    &GDBM_READER(),0640)) {
1.218     albertel 10533: 		$thisparm=$parmhash{$symbparm};
                   10534: 		untie(%parmhash);
                   10535: 	    }
1.927     albertel 10536: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10537: 	}
1.594     albertel 10538: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10539: 
1.218     albertel 10540: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10541: 	my $filename;
                   10542: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10543: 	if ($symbparm) {
1.409     www      10544: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10545: 	} else {
1.620     albertel 10546: 	    $filename=$env{'request.filename'};
1.282     albertel 10547: 	}
                   10548: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10549: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10550: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10551: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10552: 
1.927     albertel 10553: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10554: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10555: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10556: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10557: 				     $env{'course.'.$courseid.'.domain'},
                   10558: 				     'course',
1.927     albertel 10559: 				     ([$courselevelm,'map'   ],
                   10560: 				      [$courselevel, 'course']));
                   10561: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10562: 	}
1.145     www      10563: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10564: 	unless ($space eq '0') {
1.336     albertel 10565: 	    my @parts=split(/_/,$space);
                   10566: 	    my $id=pop(@parts);
                   10567: 	    my $part=join('_',@parts);
                   10568: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10569: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10570: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10571: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10572: 	}
1.395     albertel 10573: 	if ($recurse) { return undef; }
                   10574: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10575: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10576: # ---------------------------------------------------- Any other user namespace
                   10577:     } elsif ($realm eq 'environment') {
                   10578: # ----------------------------------------------------------------- environment
1.620     albertel 10579: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10580: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10581: 	} else {
1.770     albertel 10582: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10583: 		return '';
                   10584: 	    }
1.219     albertel 10585: 	    my %returnhash=&userenvironment($udom,$uname,
                   10586: 					    $spacequalifierrest);
                   10587: 	    return $returnhash{$spacequalifierrest};
                   10588: 	}
1.28      www      10589:     } elsif ($realm eq 'system') {
1.48      www      10590: # ----------------------------------------------------------------- system.time
                   10591: 	if ($space eq 'time') {
                   10592: 	    return time;
                   10593:         }
1.696     albertel 10594:     } elsif ($realm eq 'server') {
                   10595: # ----------------------------------------------------------------- system.time
                   10596: 	if ($space eq 'name') {
                   10597: 	    return $ENV{'SERVER_NAME'};
                   10598:         }
1.28      www      10599:     }
1.48      www      10600:     return '';
1.61      www      10601: }
                   10602: 
1.927     albertel 10603: sub get_reply {
                   10604:     my ($reply_value) = @_;
1.940     raeburn  10605:     if (ref($reply_value) eq 'ARRAY') {
                   10606:         if (wantarray) {
                   10607: 	    return @$reply_value;
                   10608:         }
                   10609:         return $reply_value->[0];
                   10610:     } else {
                   10611:         return $reply_value;
1.927     albertel 10612:     }
                   10613: }
                   10614: 
1.691     raeburn  10615: sub check_group_parms {
                   10616:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10617:     my @groupitems = ();
                   10618:     my $resultitem;
1.927     albertel 10619:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10620:     foreach my $group (@{$groups}) {
                   10621:         foreach my $level (@levels) {
1.927     albertel 10622:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10623:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10624:         }
                   10625:     }
                   10626:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10627:                             $env{'course.'.$courseid.'.domain'},
                   10628:                                      'course',@groupitems);
                   10629:     return $coursereply;
                   10630: }
                   10631: 
                   10632: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10633:     my ($courseid,@groups) = @_;
                   10634:     @groups = sort(@groups);
1.691     raeburn  10635:     return @groups;
                   10636: }
                   10637: 
1.395     albertel 10638: sub packages_tab_default {
                   10639:     my ($uri,$varname)=@_;
                   10640:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10641: 
                   10642:     my (@extension,@specifics,$do_default);
                   10643:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10644: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10645: 	if ($pack_type eq 'default') {
                   10646: 	    $do_default=1;
                   10647: 	} elsif ($pack_type eq 'extension') {
                   10648: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10649: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10650: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10651: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10652: 	}
                   10653:     }
                   10654:     # first look for a package that matches the requested part id
                   10655:     foreach my $package (@specifics) {
                   10656: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10657: 	next if ($pack_part ne $part);
                   10658: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10659: 	    return $packagetab{"$pack_type&$name&default"};
                   10660: 	}
                   10661:     }
                   10662:     # look for any possible matching non extension_ package
                   10663:     foreach my $package (@specifics) {
                   10664: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10665: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10666: 	    return $packagetab{"$pack_type&$name&default"};
                   10667: 	}
1.585     albertel 10668: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10669: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10670: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10671: 	}
                   10672:     }
1.738     albertel 10673:     # look for any posible extension_ match
                   10674:     foreach my $package (@extension) {
                   10675: 	my ($package,$pack_type)=@{$package};
                   10676: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10677: 	    return $packagetab{"$pack_type&$name&default"};
                   10678: 	}
                   10679: 	if (defined($packagetab{$package."&$name&default"})) {
                   10680: 	    return $packagetab{$package."&$name&default"};
                   10681: 	}
                   10682:     }
                   10683:     # look for a global default setting
                   10684:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10685: 	return $packagetab{"default&$name&default"};
                   10686:     }
1.395     albertel 10687:     return undef;
                   10688: }
                   10689: 
1.334     albertel 10690: sub add_prefix_and_part {
                   10691:     my ($prefix,$part)=@_;
                   10692:     my $keyroot;
                   10693:     if (defined($prefix) && $prefix !~ /^__/) {
                   10694: 	# prefix that has a part already
                   10695: 	$keyroot=$prefix;
                   10696:     } elsif (defined($prefix)) {
                   10697: 	# prefix that is missing a part
                   10698: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10699:     } else {
                   10700: 	# no prefix at all
                   10701: 	if (defined($part)) { $keyroot='_'.$part; }
                   10702:     }
                   10703:     return $keyroot;
                   10704: }
                   10705: 
1.71      www      10706: # ---------------------------------------------------------------- Get metadata
                   10707: 
1.599     albertel 10708: my %metaentry;
1.1070    www      10709: my %importedpartids;
1.71      www      10710: sub metadata {
1.176     www      10711:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10712:     $uri=&declutter($uri);
1.288     albertel 10713:     # if it is a non metadata possible uri return quickly
1.529     albertel 10714:     if (($uri eq '') || 
                   10715: 	(($uri =~ m|^/*adm/|) && 
1.1298    raeburn  10716: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108    raeburn  10717:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10718: 	return undef;
                   10719:     }
1.1261    raeburn  10720:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10721: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10722: 	return undef;
1.288     albertel 10723:     }
1.73      www      10724:     my $filename=$uri;
                   10725:     $uri=~s/\.meta$//;
1.172     www      10726: #
                   10727: # Is the metadata already cached?
1.177     www      10728: # Look at timestamp of caching
1.172     www      10729: # Everything is cached by the main uri, libraries are never directly cached
                   10730: #
1.428     albertel 10731:     if (!defined($liburi)) {
1.599     albertel 10732: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10733: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10734:     }
                   10735:     {
1.1069    www      10736: # Imported parts would go here
1.1070    www      10737:         my %importedids=();
                   10738:         my @origfileimportpartids=();
1.1069    www      10739:         my $importedparts=0;
1.172     www      10740: #
                   10741: # Is this a recursive call for a library?
                   10742: #
1.599     albertel 10743: #	if (! exists($metacache{$uri})) {
                   10744: #	    $metacache{$uri}={};
                   10745: #	}
1.924     albertel 10746: 	my $cachetime = 60*60;
1.171     www      10747:         if ($liburi) {
                   10748: 	    $liburi=&declutter($liburi);
                   10749:             $filename=$liburi;
1.401     bowersj2 10750:         } else {
1.599     albertel 10751: 	    &devalidate_cache_new('meta',$uri);
                   10752: 	    undef(%metaentry);
1.401     bowersj2 10753: 	}
1.140     www      10754:         my %metathesekeys=();
1.73      www      10755:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10756: 	my $metastring;
1.1140    www      10757: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10758: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10759: 	    $metastring = 
1.929     albertel 10760: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10761: 					  ('grade_target' => 'meta'));
                   10762: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10763: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10764:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10765: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10766: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10767: 	    $metastring=&getfile($file);
1.489     albertel 10768: 	}
1.208     albertel 10769:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10770:         my $token;
1.140     www      10771:         undef %metathesekeys;
1.71      www      10772:         while ($token=$parser->get_token) {
1.339     albertel 10773: 	    if ($token->[0] eq 'S') {
                   10774: 		if (defined($token->[2]->{'package'})) {
1.172     www      10775: #
                   10776: # This is a package - get package info
                   10777: #
1.339     albertel 10778: 		    my $package=$token->[2]->{'package'};
                   10779: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10780: 		    if (defined($token->[2]->{'id'})) { 
                   10781: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10782: 		    }
1.599     albertel 10783: 		    if ($metaentry{':packages'}) {
                   10784: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10785: 		    } else {
1.599     albertel 10786: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10787: 		    }
1.736     albertel 10788: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10789: 			my $part=$keyroot;
                   10790: 			$part=~s/^\_//;
1.736     albertel 10791: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10792: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10793: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10794: 			    # ignore package.tab specified default values
                   10795:                             # here &package_tab_default() will fetch those
                   10796: 			    if ($subp eq 'default') { next; }
1.736     albertel 10797: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10798: 			    my $unikey;
                   10799: 			    if ($pack =~ /_0$/) {
                   10800: 				$unikey='parameter_0_'.$name;
                   10801: 				$part=0;
                   10802: 			    } else {
                   10803: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10804: 			    }
1.339     albertel 10805: 			    if ($subp eq 'display') {
                   10806: 				$value.=' [Part: '.$part.']';
                   10807: 			    }
1.599     albertel 10808: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10809: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10810: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10811: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10812: 			    }
1.599     albertel 10813: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10814: 				$metaentry{':'.$unikey}=
                   10815: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10816: 			    }
1.339     albertel 10817: 			}
                   10818: 		    }
                   10819: 		} else {
1.172     www      10820: #
                   10821: # This is not a package - some other kind of start tag
1.339     albertel 10822: #
                   10823: 		    my $entry=$token->[1];
1.1068    www      10824: 		    my $unikey='';
1.175     www      10825: 
1.339     albertel 10826: 		    if ($entry eq 'import') {
1.175     www      10827: #
                   10828: # Importing a library here
1.339     albertel 10829: #
1.1067    www      10830:                         my $location=$parser->get_text('/import');
                   10831:                         my $dir=$filename;
                   10832:                         $dir=~s|[^/]*$||;
                   10833:                         $location=&filelocation($dir,$location);
1.1069    www      10834:                        
1.1068    www      10835:                         my $importmode=$token->[2]->{'importmode'};
                   10836:                         if ($importmode eq 'problem') {
1.1069    www      10837: # Import as problem/response
1.1068    www      10838:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10839:                         } elsif ($importmode eq 'part') {
                   10840: # Import as part(s)
1.1069    www      10841:                            $importedparts=1;
                   10842: # We need to get the original file and the imported file to get the part order correct
                   10843: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10844: # Load and inspect original file
1.1070    www      10845:                            if ($#origfileimportpartids<0) {
                   10846:                               undef(%importedpartids);
                   10847:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10848:                               my $origfile=&getfile($origfilelocation);
                   10849:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10850:                            }
                   10851: 
1.1069    www      10852: # Load and inspect imported file
                   10853:                            my $impfile=&getfile($location);
                   10854:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10855:                            if ($#impfilepartids>=0) {
                   10856: # This problem had parts
1.1070    www      10857:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10858:                            } else {
                   10859: # Importing by turning a single problem into a problem part
                   10860: # It gets the import-tags ID as part-ID
                   10861:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10862:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10863:                            }
1.1068    www      10864:                         } else {
                   10865: # Normal import
                   10866:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10867:                            if (defined($token->[2]->{'id'})) {
                   10868:                               $unikey.='_'.$token->[2]->{'id'};
                   10869:                            }
1.1067    www      10870:                         }
                   10871: 
1.339     albertel 10872: 			if ($depthcount<20) {
1.736     albertel 10873: 			    my $metadata = 
                   10874: 				&metadata($uri,'keys', $location,$unikey,
                   10875: 					  $depthcount+1);
                   10876: 			    foreach my $meta (split(',',$metadata)) {
                   10877: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10878: 				$metathesekeys{$meta}=1;
1.339     albertel 10879: 			    }
1.1068    www      10880: 			
                   10881:                         }
1.1067    www      10882: 		    } else {
                   10883: #
                   10884: # Not importing, some other kind of non-package, non-library start tag
                   10885: # 
                   10886:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10887:                         if (defined($token->[2]->{'id'})) {
                   10888:                             $unikey.='_'.$token->[2]->{'id'};
                   10889:                         }
1.339     albertel 10890: 			if (defined($token->[2]->{'name'})) { 
                   10891: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10892: 			}
                   10893: 			$metathesekeys{$unikey}=1;
1.736     albertel 10894: 			foreach my $param (@{$token->[3]}) {
                   10895: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10896: 				$token->[2]->{$param};
1.339     albertel 10897: 			}
                   10898: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10899: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10900: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10901: 		 # only ws inside the tag, and not in default, so use default
                   10902: 		 # as value
1.599     albertel 10903: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10904: 			} elsif ( $internaltext =~ /\S/ ) {
                   10905: 		  # something interesting inside the tag
                   10906: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10907: 			} else {
1.908     albertel 10908: 		  # no interesting values, don't set a default
1.339     albertel 10909: 			}
1.172     www      10910: # end of not-a-package not-a-library import
1.339     albertel 10911: 		    }
1.172     www      10912: # end of not-a-package start tag
1.339     albertel 10913: 		}
1.172     www      10914: # the next is the end of "start tag"
1.339     albertel 10915: 	    }
                   10916: 	}
1.483     albertel 10917: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10918: 	$extension = lc($extension);
                   10919: 	if ($extension eq 'htm') { $extension='html'; }
                   10920: 
1.737     albertel 10921: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10922: 	    #no specific packages #how's our extension
                   10923: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10924: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10925: 					 \%metathesekeys);
                   10926: 	}
1.883     albertel 10927: 
                   10928: 	if (!exists($metaentry{':packages'})
                   10929: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10930: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10931: 		#no specific packages well let's get default then
                   10932: 		if ($key!~/^default&/) { next; }
1.488     albertel 10933: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10934: 					     \%metathesekeys);
                   10935: 	    }
                   10936: 	}
1.338     www      10937: # are there custom rights to evaluate
1.599     albertel 10938: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10939: 
1.338     www      10940:     #
                   10941:     # Importing a rights file here
1.339     albertel 10942:     #
                   10943: 	    unless ($depthcount) {
1.599     albertel 10944: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10945: 		my $dir=$filename;
                   10946: 		$dir=~s|[^/]*$||;
                   10947: 		$location=&filelocation($dir,$location);
1.736     albertel 10948: 		my $rights_metadata =
                   10949: 		    &metadata($uri,'keys',$location,'_rights',
                   10950: 			      $depthcount+1);
                   10951: 		foreach my $rights (split(',',$rights_metadata)) {
                   10952: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10953: 		    $metathesekeys{$rights}=1;
1.339     albertel 10954: 		}
                   10955: 	    }
                   10956: 	}
1.737     albertel 10957: 	# uniqifiy package listing
                   10958: 	my %seen;
                   10959: 	my @uniq_packages =
                   10960: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10961: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10962: 
1.1070    www      10963:         if ($importedparts) {
                   10964: # We had imported parts and need to rebuild partorder
                   10965:            $metaentry{':partorder'}='';
                   10966:            $metathesekeys{'partorder'}=1;
                   10967:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10968:                if ($origfileimportpartids[$index] eq 'part') {
                   10969: # original part, part of the problem
                   10970:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10971:                } else {
                   10972: # we have imported parts at this position
                   10973:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10974:                }
                   10975:            }
                   10976:            $metaentry{':partorder'}=~s/^\,//;
                   10977:         }
                   10978: 
1.737     albertel 10979: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10980: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  10981: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 10982: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10983: # this is the end of "was not already recently cached
1.71      www      10984:     }
1.599     albertel 10985:     return $metaentry{':'.$what};
1.261     albertel 10986: }
                   10987: 
1.488     albertel 10988: sub metadata_create_package_def {
1.483     albertel 10989:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10990:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10991:     if ($subp eq 'default') { next; }
                   10992:     
1.599     albertel 10993:     if (defined($metaentry{':packages'})) {
                   10994: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10995:     } else {
1.599     albertel 10996: 	$metaentry{':packages'}=$package;
1.483     albertel 10997:     }
                   10998:     my $value=$packagetab{$key};
                   10999:     my $unikey;
                   11000:     $unikey='parameter_0_'.$name;
1.599     albertel 11001:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11002:     $$metathesekeys{$unikey}=1;
1.599     albertel 11003:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11004: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11005:     }
1.599     albertel 11006:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11007: 	$metaentry{':'.$unikey}=
                   11008: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11009:     }
                   11010: }
                   11011: 
1.261     albertel 11012: sub metadata_generate_part0 {
                   11013:     my ($metadata,$metacache,$uri) = @_;
                   11014:     my %allnames;
1.737     albertel 11015:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11016: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11017: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11018: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11019: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11020: 	    $allnames{$name}=$part;
                   11021: 	  }
                   11022: 	}
                   11023:     }
                   11024:     foreach my $name (keys(%allnames)) {
                   11025:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11026:       my $key=":parameter_0_$name";
1.261     albertel 11027:       $$metacache{"$key.part"}='0';
                   11028:       $$metacache{"$key.name"}=$name;
1.428     albertel 11029:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11030: 					   $allnames{$name}.'_'.$name.
                   11031: 					   '.type'};
1.428     albertel 11032:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11033: 			     '.display'};
1.644     www      11034:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11035:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11036:       $$metacache{"$key.display"}=$olddis;
                   11037:     }
1.71      www      11038: }
                   11039: 
1.764     albertel 11040: # ------------------------------------------------------ Devalidate title cache
                   11041: 
                   11042: sub devalidate_title_cache {
                   11043:     my ($url)=@_;
                   11044:     if (!$env{'request.course.id'}) { return; }
                   11045:     my $symb=&symbread($url);
                   11046:     if (!$symb) { return; }
                   11047:     my $key=$env{'request.course.id'}."\0".$symb;
                   11048:     &devalidate_cache_new('title',$key);
                   11049: }
                   11050: 
1.1014    droeschl 11051: # ------------------------------------------------- Get the title of a course
                   11052: 
                   11053: sub current_course_title {
                   11054:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11055: }
1.301     www      11056: # ------------------------------------------------- Get the title of a resource
                   11057: 
                   11058: sub gettitle {
                   11059:     my $urlsymb=shift;
                   11060:     my $symb=&symbread($urlsymb);
1.534     albertel 11061:     if ($symb) {
1.620     albertel 11062: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11063: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11064: 	if (defined($cached)) { 
                   11065: 	    return $result;
                   11066: 	}
1.534     albertel 11067: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11068: 	my $title='';
1.907     albertel 11069: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11070: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11071: 	} else {
                   11072: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11073: 		    &GDBM_READER(),0640)) {
                   11074: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11075: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11076: 		untie(%bighash);
                   11077: 	    }
1.534     albertel 11078: 	}
                   11079: 	$title=~s/\&colon\;/\:/gs;
                   11080: 	if ($title) {
1.1159    www      11081: # Remember both $symb and $title for dynamic metadata
                   11082:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11083:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11084: # Cache this title and then return it
1.599     albertel 11085: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11086: 	}
                   11087: 	$urlsymb=$url;
                   11088:     }
                   11089:     my $title=&metadata($urlsymb,'title');
                   11090:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11091:     return $title;
1.301     www      11092: }
1.613     albertel 11093: 
1.614     albertel 11094: sub get_slot {
                   11095:     my ($which,$cnum,$cdom)=@_;
                   11096:     if (!$cnum || !$cdom) {
1.790     albertel 11097: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11098: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11099: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11100:     }
1.703     albertel 11101:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11102:     my %slotinfo;
                   11103:     if (exists($remembered{$key})) {
                   11104: 	$slotinfo{$which} = $remembered{$key};
                   11105:     } else {
                   11106: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11107: 	&Apache::lonhomework::showhash(%slotinfo);
                   11108: 	my ($tmp)=keys(%slotinfo);
                   11109: 	if ($tmp=~/^error:/) { return (); }
                   11110: 	$remembered{$key} = $slotinfo{$which};
                   11111:     }
1.616     albertel 11112:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11113: 	return %{$slotinfo{$which}};
                   11114:     }
                   11115:     return $slotinfo{$which};
1.614     albertel 11116: }
1.1150    raeburn  11117: 
                   11118: sub get_reservable_slots {
                   11119:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11120:     my $now = time;
                   11121:     my $reservable_info;
                   11122:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11123:     if (exists($remembered{$key})) {
                   11124:         $reservable_info = $remembered{$key};
                   11125:     } else {
                   11126:         my %resv;
                   11127:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11128:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11129:         $reservable_info = \%resv;
                   11130:         $remembered{$key} = $reservable_info;
                   11131:     }
                   11132:     return $reservable_info;
                   11133: }
                   11134: 
                   11135: sub get_course_slots {
                   11136:     my ($cnum,$cdom) = @_;
                   11137:     my $hashid=$cnum.':'.$cdom;
                   11138:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11139:     if (defined($cached)) {
                   11140:         if (ref($result) eq 'HASH') {
                   11141:             return %{$result};
                   11142:         }
                   11143:     } else {
                   11144:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11145:         my ($tmp) = keys(%slots);
                   11146:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  11147:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11148:             return %slots;
                   11149:         }
                   11150:     }
                   11151:     return;
                   11152: }
                   11153: 
                   11154: sub devalidate_slots_cache {
                   11155:     my ($cnum,$cdom)=@_;
                   11156:     my $hashid=$cnum.':'.$cdom;
                   11157:     &devalidate_cache_new('allslots',$hashid);
                   11158: }
                   11159: 
1.1181    raeburn  11160: sub get_coursechange {
                   11161:     my ($cdom,$cnum) = @_;
                   11162:     if ($cdom eq '' || $cnum eq '') {
                   11163:         return unless ($env{'request.course.id'});
                   11164:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11165:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11166:     }
                   11167:     my $hashid=$cdom.'_'.$cnum;
                   11168:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11169:     if ((defined($cached)) && ($change ne '')) {
                   11170:         return $change;
                   11171:     } else {
                   11172:         my %crshash;
                   11173:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11174:         if ($crshash{'internal.contentchange'} eq '') {
                   11175:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11176:             if ($change eq '') {
                   11177:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11178:                 $change = $crshash{'internal.created'};
                   11179:             }
                   11180:         } else {
                   11181:             $change = $crshash{'internal.contentchange'};
                   11182:         }
                   11183:         my $cachetime = 600;
                   11184:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11185:     }
                   11186:     return $change;
                   11187: }
                   11188: 
                   11189: sub devalidate_coursechange_cache {
                   11190:     my ($cnum,$cdom)=@_;
                   11191:     my $hashid=$cnum.':'.$cdom;
                   11192:     &devalidate_cache_new('crschange',$hashid);
                   11193: }
                   11194: 
1.31      www      11195: # ------------------------------------------------- Update symbolic store links
                   11196: 
                   11197: sub symblist {
                   11198:     my ($mapname,%newhash)=@_;
1.438     www      11199:     $mapname=&deversion(&declutter($mapname));
1.31      www      11200:     my %hash;
1.620     albertel 11201:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11202:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11203:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11204: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11205: 		next if ($url eq 'last_known'
                   11206: 			 && $env{'form.no_update_last_known'});
                   11207: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11208: 						    $newhash{$url}->[1],
                   11209: 						    $newhash{$url}->[0]);
1.191     harris41 11210:             }
1.31      www      11211:             if (untie(%hash)) {
                   11212: 		return 'ok';
                   11213:             }
                   11214:         }
                   11215:     }
                   11216:     return 'error';
1.212     www      11217: }
                   11218: 
                   11219: # --------------------------------------------------------------- Verify a symb
                   11220: 
                   11221: sub symbverify {
1.1190    raeburn  11222:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11223:     my $thisfn=$thisurl;
1.439     www      11224:     $thisfn=&declutter($thisfn);
1.215     www      11225: # direct jump to resource in page or to a sequence - will construct own symbs
                   11226:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11227: # check URL part
1.409     www      11228:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11229: 
1.431     www      11230:     unless ($url eq $thisfn) { return 0; }
1.213     www      11231: 
1.216     www      11232:     $symb=&symbclean($symb);
1.510     www      11233:     $thisurl=&deversion($thisurl);
1.439     www      11234:     $thisfn=&deversion($thisfn);
1.213     www      11235: 
                   11236:     my %bighash;
                   11237:     my $okay=0;
1.431     www      11238: 
1.620     albertel 11239:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11240:                             &GDBM_READER(),0640)) {
1.1204    raeburn  11241:         my $noclutter;
1.1032    raeburn  11242:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11243:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  11244:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11245:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11246:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11247:                 $noclutter = 1;
                   11248:             }
                   11249:         }
                   11250:         my $ids;
                   11251:         if ($noclutter) {
                   11252:             $ids=$bighash{'ids_'.$thisurl};
                   11253:         } else {
                   11254:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11255:         }
1.1102    raeburn  11256:         unless ($ids) {
                   11257:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   11258:             $ids=$bighash{$idkey};
1.216     www      11259:         }
                   11260:         if ($ids) {
                   11261: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  11262:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  11263:                 $symb =~ s/\?.+$//;
1.1202    raeburn  11264:             }
1.800     albertel 11265: 	    foreach my $id (split(/\,/,$ids)) {
                   11266: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11267:                if (
                   11268:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  11269:    eq $symb) {
                   11270:                    if (ref($encstate)) {
                   11271:                        $$encstate = $bighash{'encrypted_'.$id};
                   11272:                    }
1.620     albertel 11273: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  11274: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   11275:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  11276: 		       $okay=1;
1.1202    raeburn  11277:                        last;
1.582     albertel 11278: 		   }
                   11279: 	       }
1.216     www      11280: 	   }
                   11281:         }
1.213     www      11282: 	untie(%bighash);
                   11283:     }
                   11284:     return $okay;
1.31      www      11285: }
                   11286: 
1.210     www      11287: # --------------------------------------------------------------- Clean-up symb
                   11288: 
                   11289: sub symbclean {
                   11290:     my $symb=shift;
1.568     albertel 11291:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11292: # remove version from map
                   11293:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11294: 
1.210     www      11295: # remove version from URL
                   11296:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11297: 
1.507     www      11298: # remove wrapper
                   11299: 
1.510     www      11300:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11301:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11302:     return $symb;
1.409     www      11303: }
                   11304: 
                   11305: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11306: 
                   11307: sub encode_symb {
                   11308:     my ($map,$resid,$url)=@_;
                   11309:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11310: }
1.409     www      11311: 
                   11312: sub decode_symb {
1.568     albertel 11313:     my $symb=shift;
                   11314:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11315:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11316:     return (&fixversion($map),$resid,&fixversion($url));
                   11317: }
                   11318: 
                   11319: sub fixversion {
                   11320:     my $fn=shift;
1.609     banghart 11321:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11322:     my %bighash;
                   11323:     my $uri=&clutter($fn);
1.620     albertel 11324:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11325: # is this cached?
1.599     albertel 11326:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11327:     if (defined($cached)) { return $result; }
                   11328: # unfortunately not cached, or expired
1.620     albertel 11329:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11330: 	    &GDBM_READER(),0640)) {
                   11331:  	if ($bighash{'version_'.$uri}) {
                   11332:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11333:  	    unless (($version eq 'mostrecent') || 
                   11334: 		    ($version==&getversion($uri))) {
1.440     www      11335:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11336:  	    }
                   11337:  	}
                   11338:  	untie %bighash;
1.413     www      11339:     }
1.599     albertel 11340:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11341: }
                   11342: 
                   11343: sub deversion {
                   11344:     my $url=shift;
                   11345:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11346:     return $url;
1.210     www      11347: }
                   11348: 
1.31      www      11349: # ------------------------------------------------------ Return symb list entry
                   11350: 
                   11351: sub symbread {
1.1282    raeburn  11352:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  11353:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  11354:     if (defined($env{$cache_str})) {
                   11355:         if ($ignorecachednull) {
                   11356:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11357:         } else {
                   11358:             return $env{$cache_str};
                   11359:         }
                   11360:     }
1.242     www      11361: # no filename provided? try from environment
1.1265    raeburn  11362:     unless ($thisfn) {
1.620     albertel 11363:         if ($env{'request.symb'}) {
                   11364: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 11365: 	}
1.620     albertel 11366: 	$thisfn=$env{'request.filename'};
1.44      www      11367:     }
1.569     albertel 11368:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11369: # is that filename actually a symb? Verify, clean, and return
                   11370:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11371: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11372: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11373: 	}
1.242     www      11374:     }
1.44      www      11375:     $thisfn=declutter($thisfn);
1.31      www      11376:     my %hash;
1.37      www      11377:     my %bighash;
                   11378:     my $syval='';
1.620     albertel 11379:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11380:         my $targetfn = $thisfn;
1.609     banghart 11381:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11382:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11383:         }
1.687     albertel 11384: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11385: 	    $targetfn=$1;
                   11386: 	}
1.620     albertel 11387:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11388:                       &GDBM_READER(),0640)) {
1.481     raeburn  11389: 	    $syval=$hash{$targetfn};
1.37      www      11390:             untie(%hash);
                   11391:         }
                   11392: # ---------------------------------------------------------- There was an entry
                   11393:         if ($syval) {
1.601     albertel 11394: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11395: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11396: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11397: 		    #return $env{$cache_str}='';
1.601     albertel 11398: 		#}    
                   11399: 		#$syval.=$1;
                   11400: 	    #}
1.37      www      11401:         } else {
                   11402: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11403:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11404:                             &GDBM_READER(),0640)) {
1.37      www      11405: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11406:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11407:               unless ($ids) { 
                   11408:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11409:               }
                   11410:               unless ($ids) {
                   11411: # alias?
                   11412: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11413:               }
1.37      www      11414:               if ($ids) {
                   11415: # ------------------------------------------------------------------- Has ID(s)
                   11416:                  my @possibilities=split(/\,/,$ids);
1.39      www      11417:                  if ($#possibilities==0) {
                   11418: # ----------------------------------------------- There is only one possibility
1.37      www      11419: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11420: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11421: 						    $resid,$thisfn);
1.1282    raeburn  11422:                      if (ref($possibles) eq 'HASH') {
                   11423:                          $possibles->{$syval} = 1;    
                   11424:                      }
                   11425:                      if ($checkforblock) {
                   11426:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11427:                          if (@blockers) {
                   11428:                              $syval = '';
                   11429:                              return;
                   11430:                          }
                   11431:                      }
                   11432:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      11433: # ------------------------------------------ There is more than one possibility
                   11434:                      my $realpossible=0;
1.800     albertel 11435:                      foreach my $id (@possibilities) {
                   11436: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  11437:                          my $canaccess;
                   11438:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11439:                              $canaccess = 1;
                   11440:                          } else { 
                   11441:                              $canaccess = &allowed('bre',$file);
                   11442:                          }
                   11443:                          if ($canaccess) {
                   11444:          		     my ($mapid,$resid)=split(/\./,$id);
                   11445:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11446:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11447: 						             $resid,$thisfn);
                   11448:                                  if (ref($possibles) eq 'HASH') {
                   11449:                                      $possibles->{$syval} = 1;
                   11450:                                  }
                   11451:                                  if ($checkforblock) {
                   11452:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11453:                                      unless (@blockers > 0) {
                   11454:                                          $syval = $poss_syval;
                   11455:                                          $realpossible++;
                   11456:                                      }
                   11457:                                  } else {
                   11458:                                      $syval = $poss_syval;
                   11459:                                      $realpossible++;
                   11460:                                  }
                   11461:                              }
1.39      www      11462: 			 }
1.191     harris41 11463:                      }
1.39      www      11464: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11465:                  } else {
                   11466:                      $syval='';
1.37      www      11467:                  }
                   11468: 	      }
1.1282    raeburn  11469:               untie(%bighash);
1.481     raeburn  11470:            }
1.31      www      11471:         }
1.62      www      11472:         if ($syval) {
1.620     albertel 11473: 	    return $env{$cache_str}=$syval;
1.62      www      11474:         }
1.31      www      11475:     }
1.949     raeburn  11476:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11477:     return $env{$cache_str}='';
1.31      www      11478: }
                   11479: 
                   11480: # ---------------------------------------------------------- Return random seed
                   11481: 
1.32      www      11482: sub numval {
                   11483:     my $txt=shift;
                   11484:     $txt=~tr/A-J/0-9/;
                   11485:     $txt=~tr/a-j/0-9/;
                   11486:     $txt=~tr/K-T/0-9/;
                   11487:     $txt=~tr/k-t/0-9/;
                   11488:     $txt=~tr/U-Z/0-5/;
                   11489:     $txt=~tr/u-z/0-5/;
                   11490:     $txt=~s/\D//g;
1.564     albertel 11491:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11492:     return int($txt);
1.368     albertel 11493: }
                   11494: 
1.484     albertel 11495: sub numval2 {
                   11496:     my $txt=shift;
                   11497:     $txt=~tr/A-J/0-9/;
                   11498:     $txt=~tr/a-j/0-9/;
                   11499:     $txt=~tr/K-T/0-9/;
                   11500:     $txt=~tr/k-t/0-9/;
                   11501:     $txt=~tr/U-Z/0-5/;
                   11502:     $txt=~tr/u-z/0-5/;
                   11503:     $txt=~s/\D//g;
                   11504:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11505:     my $total;
                   11506:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11507:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11508:     return int($total);
                   11509: }
                   11510: 
1.575     albertel 11511: sub numval3 {
                   11512:     use integer;
                   11513:     my $txt=shift;
                   11514:     $txt=~tr/A-J/0-9/;
                   11515:     $txt=~tr/a-j/0-9/;
                   11516:     $txt=~tr/K-T/0-9/;
                   11517:     $txt=~tr/k-t/0-9/;
                   11518:     $txt=~tr/U-Z/0-5/;
                   11519:     $txt=~tr/u-z/0-5/;
                   11520:     $txt=~s/\D//g;
                   11521:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11522:     my $total;
                   11523:     foreach my $val (@txts) { $total+=$val; }
                   11524:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11525:     return $total;
                   11526: }
                   11527: 
1.675     albertel 11528: sub digest {
                   11529:     my ($data)=@_;
                   11530:     my $digest=&Digest::MD5::md5($data);
                   11531:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11532:     my ($e,$f);
                   11533:     {
                   11534:         use integer;
                   11535:         $e=($a+$b);
                   11536:         $f=($c+$d);
                   11537:         if ($_64bit) {
                   11538:             $e=(($e<<32)>>32);
                   11539:             $f=(($f<<32)>>32);
                   11540:         }
                   11541:     }
                   11542:     if (wantarray) {
                   11543: 	return ($e,$f);
                   11544:     } else {
                   11545: 	my $g;
                   11546: 	{
                   11547: 	    use integer;
                   11548: 	    $g=($e+$f);
                   11549: 	    if ($_64bit) {
                   11550: 		$g=(($g<<32)>>32);
                   11551: 	    }
                   11552: 	}
                   11553: 	return $g;
                   11554:     }
                   11555: }
                   11556: 
1.368     albertel 11557: sub latest_rnd_algorithm_id {
1.675     albertel 11558:     return '64bit5';
1.366     albertel 11559: }
1.32      www      11560: 
1.503     albertel 11561: sub get_rand_alg {
                   11562:     my ($courseid)=@_;
1.790     albertel 11563:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11564:     if ($courseid) {
1.620     albertel 11565: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11566:     }
                   11567:     return &latest_rnd_algorithm_id();
                   11568: }
                   11569: 
1.562     albertel 11570: sub validCODE {
                   11571:     my ($CODE)=@_;
                   11572:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11573:     return 0;
                   11574: }
                   11575: 
1.491     albertel 11576: sub getCODE {
1.620     albertel 11577:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11578:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11579: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11580: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11581: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11582:     }
                   11583:     return undef;
                   11584: }
1.1133    foxr     11585: #
                   11586: #  Determines the random seed for a specific context:
                   11587: #
                   11588: # parameters:
                   11589: #   symb      - in course context the symb for the seed.
                   11590: #   course_id - The course id of the form domain_coursenum.
                   11591: #   domain    - Domain for the user.
                   11592: #   course    - Course for the user.
                   11593: #   cenv      - environment of the course.
                   11594: #
                   11595: # NOTE:
                   11596: #   All parameters are picked out of the environment if missing
                   11597: #   or not defined.
                   11598: #   If a symb cannot be determined the current time is used instead.
                   11599: #
                   11600: #  For a given well defined symb, courside, domain, username,
                   11601: #  and course environment, the seed is reproducible.
                   11602: #
1.31      www      11603: sub rndseed {
1.1133    foxr     11604:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11605:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11606:     if (!defined($symb)) {
1.366     albertel 11607: 	unless ($symb=$wsymb) { return time; }
                   11608:     }
1.1146    foxr     11609:     if (!defined $courseid) { 
                   11610: 	$courseid=$wcourseid; 
                   11611:     }
                   11612:     if (!defined $domain) { $domain=$wdomain; }
                   11613:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11614: 
                   11615:     my $which;
                   11616:     if (defined($cenv->{'rndseed'})) {
                   11617: 	$which = $cenv->{'rndseed'};
                   11618:     } else {
                   11619: 	$which =&get_rand_alg($courseid);
                   11620:     }
1.491     albertel 11621:     if (defined(&getCODE())) {
1.1133    foxr     11622: 
1.675     albertel 11623: 	if ($which eq '64bit5') {
                   11624: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11625: 	} elsif ($which eq '64bit4') {
1.575     albertel 11626: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11627: 	} else {
                   11628: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11629: 	}
1.675     albertel 11630:     } elsif ($which eq '64bit5') {
                   11631: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11632:     } elsif ($which eq '64bit4') {
                   11633: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11634:     } elsif ($which eq '64bit3') {
                   11635: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11636:     } elsif ($which eq '64bit2') {
                   11637: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11638:     } elsif ($which eq '64bit') {
                   11639: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11640:     }
                   11641:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11642: }
                   11643: 
                   11644: sub rndseed_32bit {
                   11645:     my ($symb,$courseid,$domain,$username)=@_;
                   11646:     {
                   11647: 	use integer;
                   11648: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11649: 	my $symbseed=numval($symb) << 22;
                   11650: 	my $namechck=unpack("%32C*",$username) << 17;
                   11651: 	my $nameseed=numval($username) << 12;
                   11652: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11653: 	my $courseseed=unpack("%32C*",$courseid);
                   11654: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11655: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11656: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11657: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11658: 	return $num;
                   11659:     }
                   11660: }
                   11661: 
                   11662: sub rndseed_64bit {
                   11663:     my ($symb,$courseid,$domain,$username)=@_;
                   11664:     {
                   11665: 	use integer;
                   11666: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11667: 	my $symbseed=numval($symb) << 10;
                   11668: 	my $namechck=unpack("%32S*",$username);
                   11669: 	
                   11670: 	my $nameseed=numval($username) << 21;
                   11671: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11672: 	my $courseseed=unpack("%32S*",$courseid);
                   11673: 	
                   11674: 	my $num1=$symbchck+$symbseed+$namechck;
                   11675: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11676: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11677: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11678: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11679: 	return "$num1,$num2";
1.155     albertel 11680:     }
1.366     albertel 11681: }
                   11682: 
1.443     albertel 11683: sub rndseed_64bit2 {
                   11684:     my ($symb,$courseid,$domain,$username)=@_;
                   11685:     {
                   11686: 	use integer;
                   11687: 	# strings need to be an even # of cahracters long, it it is odd the
                   11688:         # last characters gets thrown away
                   11689: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11690: 	my $symbseed=numval($symb) << 10;
                   11691: 	my $namechck=unpack("%32S*",$username.' ');
                   11692: 	
                   11693: 	my $nameseed=numval($username) << 21;
1.501     albertel 11694: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11695: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11696: 	
                   11697: 	my $num1=$symbchck+$symbseed+$namechck;
                   11698: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11699: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11700: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11701: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11702: 	return "$num1,$num2";
                   11703:     }
                   11704: }
                   11705: 
                   11706: sub rndseed_64bit3 {
                   11707:     my ($symb,$courseid,$domain,$username)=@_;
                   11708:     {
                   11709: 	use integer;
                   11710: 	# strings need to be an even # of cahracters long, it it is odd the
                   11711:         # last characters gets thrown away
                   11712: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11713: 	my $symbseed=numval2($symb) << 10;
                   11714: 	my $namechck=unpack("%32S*",$username.' ');
                   11715: 	
                   11716: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11717: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11718: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11719: 	
                   11720: 	my $num1=$symbchck+$symbseed+$namechck;
                   11721: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11722: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11723: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11724: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11725: 	
1.503     albertel 11726: 	return "$num1:$num2";
1.443     albertel 11727:     }
                   11728: }
                   11729: 
1.575     albertel 11730: sub rndseed_64bit4 {
                   11731:     my ($symb,$courseid,$domain,$username)=@_;
                   11732:     {
                   11733: 	use integer;
                   11734: 	# strings need to be an even # of cahracters long, it it is odd the
                   11735:         # last characters gets thrown away
                   11736: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11737: 	my $symbseed=numval3($symb) << 10;
                   11738: 	my $namechck=unpack("%32S*",$username.' ');
                   11739: 	
                   11740: 	my $nameseed=numval3($username) << 21;
                   11741: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11742: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11743: 	
                   11744: 	my $num1=$symbchck+$symbseed+$namechck;
                   11745: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11746: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11747: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11748: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11749: 	
1.575     albertel 11750: 	return "$num1:$num2";
                   11751:     }
                   11752: }
                   11753: 
1.675     albertel 11754: sub rndseed_64bit5 {
                   11755:     my ($symb,$courseid,$domain,$username)=@_;
                   11756:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11757:     return "$num1:$num2";
                   11758: }
                   11759: 
1.366     albertel 11760: sub rndseed_CODE_64bit {
                   11761:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11762:     {
1.366     albertel 11763: 	use integer;
1.443     albertel 11764: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11765: 	my $symbseed=numval2($symb);
1.491     albertel 11766: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11767: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11768: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11769: 	my $num1=$symbseed+$CODEchck;
                   11770: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11771: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11772: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11773: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11774: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11775: 	return "$num1:$num2";
1.366     albertel 11776:     }
                   11777: }
                   11778: 
1.575     albertel 11779: sub rndseed_CODE_64bit4 {
                   11780:     my ($symb,$courseid,$domain,$username)=@_;
                   11781:     {
                   11782: 	use integer;
                   11783: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11784: 	my $symbseed=numval3($symb);
                   11785: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11786: 	my $CODEseed=numval3(&getCODE());
                   11787: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11788: 	my $num1=$symbseed+$CODEchck;
                   11789: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11790: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11791: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11792: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11793: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11794: 	return "$num1:$num2";
                   11795:     }
                   11796: }
                   11797: 
1.675     albertel 11798: sub rndseed_CODE_64bit5 {
                   11799:     my ($symb,$courseid,$domain,$username)=@_;
                   11800:     my $code = &getCODE();
                   11801:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11802:     return "$num1:$num2";
                   11803: }
                   11804: 
1.366     albertel 11805: sub setup_random_from_rndseed {
                   11806:     my ($rndseed)=@_;
1.503     albertel 11807:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  11808:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   11809:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   11810:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   11811:         } else {
                   11812:             &Math::Random::random_set_seed($num1,$num2);
                   11813:         }
1.366     albertel 11814:     } else {
                   11815: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11816:     }
1.36      albertel 11817: }
                   11818: 
1.474     albertel 11819: sub latest_receipt_algorithm_id {
1.835     albertel 11820:     return 'receipt3';
1.474     albertel 11821: }
                   11822: 
1.480     www      11823: sub recunique {
                   11824:     my $fucourseid=shift;
                   11825:     my $unique;
1.835     albertel 11826:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11827: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11828: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11829:     } else {
                   11830: 	$unique=$perlvar{'lonReceipt'};
                   11831:     }
                   11832:     return unpack("%32C*",$unique);
                   11833: }
                   11834: 
                   11835: sub recprefix {
                   11836:     my $fucourseid=shift;
                   11837:     my $prefix;
1.835     albertel 11838:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11839: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11840: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11841:     } else {
                   11842: 	$prefix=$perlvar{'lonHostID'};
                   11843:     }
                   11844:     return unpack("%32C*",$prefix);
                   11845: }
                   11846: 
1.76      www      11847: sub ireceipt {
1.474     albertel 11848:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11849: 
                   11850:     my $return =&recprefix($fucourseid).'-';
                   11851: 
                   11852:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11853: 	$env{'request.state'} eq 'construct') {
                   11854: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11855: 	return $return;
                   11856:     }
                   11857: 
1.76      www      11858:     my $cuname=unpack("%32C*",$funame);
                   11859:     my $cudom=unpack("%32C*",$fudom);
                   11860:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11861:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11862:     my $cunique=&recunique($fucourseid);
1.474     albertel 11863:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11864:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11865: 
1.790     albertel 11866: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11867: 			       
                   11868: 	$return.= ($cunique%$cuname+
                   11869: 		   $cunique%$cudom+
                   11870: 		   $cusymb%$cuname+
                   11871: 		   $cusymb%$cudom+
                   11872: 		   $cucourseid%$cuname+
                   11873: 		   $cucourseid%$cudom+
                   11874: 		   $cpart%$cuname+
                   11875: 		   $cpart%$cudom);
                   11876:     } else {
                   11877: 	$return.= ($cunique%$cuname+
                   11878: 		   $cunique%$cudom+
                   11879: 		   $cusymb%$cuname+
                   11880: 		   $cusymb%$cudom+
                   11881: 		   $cucourseid%$cuname+
                   11882: 		   $cucourseid%$cudom);
                   11883:     }
                   11884:     return $return;
1.76      www      11885: }
                   11886: 
                   11887: sub receipt {
1.474     albertel 11888:     my ($part)=@_;
1.790     albertel 11889:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11890:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11891: }
1.260     ng       11892: 
1.790     albertel 11893: sub whichuser {
                   11894:     my ($passedsymb)=@_;
                   11895:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11896:     if (defined($env{'form.grade_symb'})) {
                   11897: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11898: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11899: 	if (!$allowed &&
                   11900: 	    exists($env{'request.course.sec'}) &&
                   11901: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11902: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11903: 			      '/'.$env{'request.course.sec'});
                   11904: 	}
                   11905: 	if ($allowed) {
                   11906: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11907: 	    $courseid=$tmp_courseid;
                   11908: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11909: 	    ($name)=&get_env_multiple('form.grade_username');
                   11910: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11911: 	}
                   11912:     }
                   11913:     if (!$passedsymb) {
                   11914: 	$symb=&symbread();
                   11915:     } else {
                   11916: 	$symb=$passedsymb;
                   11917:     }
                   11918:     $courseid=$env{'request.course.id'};
                   11919:     $domain=$env{'user.domain'};
                   11920:     $name=$env{'user.name'};
                   11921:     if ($name eq 'public' && $domain eq 'public') {
                   11922: 	if (!defined($env{'form.username'})) {
                   11923: 	    $env{'form.username'}.=time.rand(10000000);
                   11924: 	}
                   11925: 	$name.=$env{'form.username'};
                   11926:     }
                   11927:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11928: 
                   11929: }
                   11930: 
1.36      albertel 11931: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11932: # returns either the contents of the file or 
                   11933: # -1 if the file doesn't exist
1.481     raeburn  11934: #
                   11935: # if the target is a file that was uploaded via DOCS, 
                   11936: # a check will be made to see if a current copy exists on the local server,
                   11937: # if it does this will be served, otherwise a copy will be retrieved from
                   11938: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11939: # the local server.   
1.472     albertel 11940: 
1.36      albertel 11941: sub getfile {
1.538     albertel 11942:     my ($file) = @_;
1.609     banghart 11943:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11944:     &repcopy($file);
                   11945:     return &readfile($file);
                   11946: }
                   11947: 
                   11948: sub repcopy_userfile {
                   11949:     my ($file)=@_;
1.1142    raeburn  11950:     my $londocroot = $perlvar{'lonDocRoot'};
                   11951:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11952:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11953:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11954: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11955:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11956:     if (-e "$file") {
1.828     www      11957: # we already have a local copy, check it out
1.538     albertel 11958: 	my @fileinfo = stat($file);
1.828     www      11959: 	my $rtncode;
                   11960: 	my $info;
1.538     albertel 11961: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11962: 	if ($lwpresp ne 'ok') {
1.828     www      11963: # there is no such file anymore, even though we had a local copy
1.482     albertel 11964: 	    if ($rtncode eq '404') {
1.538     albertel 11965: 		unlink($file);
1.482     albertel 11966: 	    }
                   11967: 	    return -1;
                   11968: 	}
                   11969: 	if ($info < $fileinfo[9]) {
1.828     www      11970: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11971: 	    return 'ok';
1.828     www      11972: 	} else {
                   11973: # the file is outdated, get rid of it
                   11974: 	    unlink($file);
1.482     albertel 11975: 	}
1.828     www      11976:     }
                   11977: # one way or the other, at this point, we don't have the file
                   11978: # construct the correct path for the file
                   11979:     my @parts = ($cdom,$cnum); 
                   11980:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11981: 	push @parts, split(/\//,$1);
                   11982:     }
                   11983:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11984:     foreach my $part (@parts) {
                   11985: 	$path .= '/'.$part;
                   11986: 	if (!-e $path) {
                   11987: 	    mkdir($path,0770);
1.482     albertel 11988: 	}
                   11989:     }
1.828     www      11990: # now the path exists for sure
                   11991: # get a user agent
                   11992:     my $ua=new LWP::UserAgent;
                   11993:     my $transferfile=$file.'.in.transfer';
                   11994: # FIXME: this should flock
                   11995:     if (-e $transferfile) { return 'ok'; }
                   11996:     my $request;
                   11997:     $uri=~s/^\///;
1.980     raeburn  11998:     my $homeserver = &homeserver($cnum,$cdom);
                   11999:     my $protocol = $protocol{$homeserver};
                   12000:     $protocol = 'http' if ($protocol ne 'https');
                   12001:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12002:     my $response=$ua->request($request,$transferfile);
                   12003: # did it work?
                   12004:     if ($response->is_error()) {
                   12005: 	unlink($transferfile);
                   12006: 	&logthis("Userfile repcopy failed for $uri");
                   12007: 	return -1;
                   12008:     }
                   12009: # worked, rename the transfer file
                   12010:     rename($transferfile,$file);
1.607     raeburn  12011:     return 'ok';
1.481     raeburn  12012: }
                   12013: 
1.517     albertel 12014: sub tokenwrapper {
                   12015:     my $uri=shift;
1.980     raeburn  12016:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12017:     $uri=~s|^/||;
1.620     albertel 12018:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12019:     my $token=$1;
1.552     albertel 12020:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12021:     if ($udom && $uname && $file) {
                   12022: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12023:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12024:         my $homeserver = &homeserver($uname,$udom);
                   12025:         my $protocol = $protocol{$homeserver};
                   12026:         $protocol = 'http' if ($protocol ne 'https');
                   12027:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12028:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12029:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12030:     } else {
                   12031:         return '/adm/notfound.html';
                   12032:     }
                   12033: }
                   12034: 
1.828     www      12035: # call with reqtype HEAD: get last modification time
                   12036: # call with reqtype GET: get the file contents
                   12037: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12038: #
1.481     raeburn  12039: sub getuploaded {
                   12040:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12041:     $uri=~s/^\///;
1.980     raeburn  12042:     my $homeserver = &homeserver($cnum,$cdom);
                   12043:     my $protocol = $protocol{$homeserver};
                   12044:     $protocol = 'http' if ($protocol ne 'https');
                   12045:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12046:     my $ua=new LWP::UserAgent;
                   12047:     my $request=new HTTP::Request($reqtype,$uri);
                   12048:     my $response=$ua->request($request);
                   12049:     $$rtncode = $response->code;
1.482     albertel 12050:     if (! $response->is_success()) {
                   12051: 	return 'failed';
                   12052:     }      
                   12053:     if ($reqtype eq 'HEAD') {
1.486     www      12054: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12055:     } elsif ($reqtype eq 'GET') {
                   12056: 	$$info = $response->content;
1.472     albertel 12057:     }
1.482     albertel 12058:     return 'ok';
1.36      albertel 12059: }
                   12060: 
1.481     raeburn  12061: sub readfile {
                   12062:     my $file = shift;
                   12063:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12064:     my $fh;
                   12065:     open($fh,"<$file");
                   12066:     my $a='';
1.800     albertel 12067:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12068:     return $a;
                   12069: }
                   12070: 
1.36      albertel 12071: sub filelocation {
1.590     banghart 12072:     my ($dir,$file) = @_;
                   12073:     my $location;
                   12074:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12075: 
                   12076:     if ($file =~ m-^/adm/-) {
                   12077: 	$file=~s-^/adm/wrapper/-/-;
                   12078: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12079:     }
1.882     albertel 12080: 
1.1139    www      12081:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12082:         $location = $file;
1.609     banghart 12083:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12084:         my ($udom,$uname,$filename)=
1.811     albertel 12085:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12086:         my $home=&homeserver($uname,$udom);
                   12087:         my $is_me=0;
                   12088:         my @ids=&current_machine_ids();
                   12089:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12090:         if ($is_me) {
1.1117    foxr     12091:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12092:         } else {
                   12093:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12094:   	      $udom.'/'.$uname.'/'.$filename;
                   12095:         }
1.882     albertel 12096:     } elsif ($file =~ m-^/adm/-) {
                   12097: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12098:     } else {
                   12099:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12100:         $file=~s:^/(res|priv)/:/:;
                   12101:         my $space=$1;
1.590     banghart 12102:         if ( !( $file =~ m:^/:) ) {
                   12103:             $location = $dir. '/'.$file;
                   12104:         } else {
1.1142    raeburn  12105:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12106:         }
1.59      albertel 12107:     }
1.590     banghart 12108:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12109:     while ($location=~m{/\.\./}) {
                   12110: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12111: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12112: 	} else {
                   12113: 	    $location=~ s{/\.\./}{/}g;
                   12114: 	}
                   12115:     } #remove dir/..
1.590     banghart 12116:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12117:     return $location;
1.46      www      12118: }
1.36      albertel 12119: 
1.46      www      12120: sub hreflocation {
                   12121:     my ($dir,$file)=@_;
1.980     raeburn  12122:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12123: 	$file=filelocation($dir,$file);
1.700     albertel 12124:     } elsif ($file=~m-^/adm/-) {
                   12125: 	$file=~s-^/adm/wrapper/-/-;
                   12126: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12127:     }
                   12128:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12129: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12130:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12131: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12132: 	        {/uploaded/$1/$2/}x;
1.46      www      12133:     }
1.913     albertel 12134:     if ($file=~ m{^/userfiles/}) {
                   12135: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12136:     }
1.462     albertel 12137:     return $file;
1.465     albertel 12138: }
                   12139: 
1.1139    www      12140: 
                   12141: 
                   12142: 
                   12143: 
1.465     albertel 12144: sub current_machine_domains {
1.853     albertel 12145:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12146: }
                   12147: 
                   12148: sub machine_domains {
                   12149:     my ($hostname) = @_;
1.465     albertel 12150:     my @domains;
1.838     albertel 12151:     my %hostname = &all_hostnames();
1.465     albertel 12152:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12153: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12154: 	if ($hostname eq $name) {
1.844     albertel 12155: 	    push(@domains,&host_domain($id));
1.465     albertel 12156: 	}
                   12157:     }
                   12158:     return @domains;
                   12159: }
                   12160: 
                   12161: sub current_machine_ids {
1.853     albertel 12162:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12163: }
                   12164: 
                   12165: sub machine_ids {
                   12166:     my ($hostname) = @_;
                   12167:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12168:     my @ids;
1.888     albertel 12169:     my %name_to_host = &all_names();
1.889     albertel 12170:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12171: 	return @{ $name_to_host{$hostname} };
                   12172:     }
                   12173:     return;
1.31      www      12174: }
                   12175: 
1.824     raeburn  12176: sub additional_machine_domains {
                   12177:     my @domains;
                   12178:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12179:     while( my $line = <$fh>) {
                   12180:         $line =~ s/\s//g;
                   12181:         push(@domains,$line);
                   12182:     }
                   12183:     return @domains;
                   12184: }
                   12185: 
                   12186: sub default_login_domain {
                   12187:     my $domain = $perlvar{'lonDefDomain'};
                   12188:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12189:     foreach my $posdom (&current_machine_domains(),
                   12190:                         &additional_machine_domains()) {
                   12191:         if (lc($posdom) eq lc($testdomain)) {
                   12192:             $domain=$posdom;
                   12193:             last;
                   12194:         }
                   12195:     }
                   12196:     return $domain;
                   12197: }
                   12198: 
1.31      www      12199: # ------------------------------------------------------------- Declutters URLs
                   12200: 
                   12201: sub declutter {
                   12202:     my $thisfn=shift;
1.569     albertel 12203:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  12204:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12205:         $thisfn=~s{^/home/httpd/html}{};
                   12206:     }
1.31      www      12207:     $thisfn=~s/^\///;
1.697     albertel 12208:     $thisfn=~s|^adm/wrapper/||;
                   12209:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12210:     $thisfn=~s/^res\///;
1.1172    bisitz   12211:     $thisfn=~s/^priv\///;
1.1032    raeburn  12212:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12213:         $thisfn=~s/\?.+$//;
                   12214:     }
1.268     www      12215:     return $thisfn;
                   12216: }
                   12217: 
                   12218: # ------------------------------------------------------------- Clutter up URLs
                   12219: 
                   12220: sub clutter {
                   12221:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12222:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12223: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12224:        $thisfn='/res'.$thisfn; 
                   12225:     }
1.1031    raeburn  12226:     if ($thisfn !~m|^/adm|) {
                   12227: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12228: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12229: 	} else {
                   12230: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12231: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12232: 	    if ($embstyle eq 'ssi'
                   12233: 		|| ($embstyle eq 'hdn')
                   12234: 		|| ($embstyle eq 'rat')
                   12235: 		|| ($embstyle eq 'prv')
                   12236: 		|| ($embstyle eq 'ign')) {
                   12237: 		#do nothing with these
                   12238: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12239: 		|| ($embstyle eq 'emb')
                   12240: 		|| ($embstyle eq 'wrp')) {
                   12241: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12242: 	    } elsif ($embstyle eq 'unk'
                   12243: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12244: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12245: 	    } else {
1.718     www      12246: #		&logthis("Got a blank emb style");
1.695     albertel 12247: 	    }
1.694     albertel 12248: 	}
1.1298    raeburn  12249:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
                   12250:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 12251:     }
1.31      www      12252:     return $thisfn;
1.12      www      12253: }
                   12254: 
1.787     albertel 12255: sub clutter_with_no_wrapper {
                   12256:     my $uri = &clutter(shift);
                   12257:     if ($uri =~ m-^/adm/-) {
                   12258: 	$uri =~ s-^/adm/wrapper/-/-;
                   12259: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12260:     }
                   12261:     return $uri;
                   12262: }
                   12263: 
1.557     albertel 12264: sub freeze_escape {
                   12265:     my ($value)=@_;
                   12266:     if (ref($value)) {
                   12267: 	$value=&nfreeze($value);
                   12268: 	return '__FROZEN__'.&escape($value);
                   12269:     }
                   12270:     return &escape($value);
                   12271: }
                   12272: 
1.11      www      12273: 
1.557     albertel 12274: sub thaw_unescape {
                   12275:     my ($value)=@_;
                   12276:     if ($value =~ /^__FROZEN__/) {
                   12277: 	substr($value,0,10,undef);
                   12278: 	$value=&unescape($value);
                   12279: 	return &thaw($value);
                   12280:     }
                   12281:     return &unescape($value);
                   12282: }
                   12283: 
1.436     albertel 12284: sub correct_line_ends {
                   12285:     my ($result)=@_;
                   12286:     $$result =~s/\r\n/\n/mg;
                   12287:     $$result =~s/\r/\n/mg;
1.415     albertel 12288: }
1.1       albertel 12289: # ================================================================ Main Program
                   12290: 
1.184     www      12291: sub goodbye {
1.204     albertel 12292:    &logthis("Starting Shut down");
1.443     albertel 12293: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12294:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12295: #converted
1.599     albertel 12296: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12297:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12298: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12299: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12300: #1.1 only
1.870     albertel 12301: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12302: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12303: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12304: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12305:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12306:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12307:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12308:    &flushcourselogs();
                   12309:    &logthis("Shutting down");
                   12310: }
                   12311: 
1.852     albertel 12312: sub get_dns {
1.1210    raeburn  12313:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12314:     if (!$ignore_cache) {
                   12315: 	my ($content,$cached)=
                   12316: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12317: 	if ($cached) {
1.1210    raeburn  12318: 	    &$func($content,$hashref);
1.869     albertel 12319: 	    return;
                   12320: 	}
                   12321:     }
                   12322: 
                   12323:     my %alldns;
1.852     albertel 12324:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12325:     foreach my $dns (<$config>) {
                   12326: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12327:         my $line = $1;
                   12328:         my ($host,$protocol) = split(/:/,$line);
                   12329:         if ($protocol ne 'https') {
                   12330:             $protocol = 'http';
                   12331:         }
                   12332: 	$alldns{$host} = $protocol;
1.869     albertel 12333:     }
                   12334:     while (%alldns) {
1.1263    raeburn  12335: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12336: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12337:         $ua->timeout(30);
1.979     raeburn  12338: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12339: 	my $response=$ua->request($request);
1.979     raeburn  12340:         delete($alldns{$dns});
1.852     albertel 12341: 	next if ($response->is_error());
                   12342: 	my @content = split("\n",$response->content);
1.1210    raeburn  12343: 	unless ($nocache) {
1.1219    raeburn  12344: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  12345: 	}
                   12346: 	&$func(\@content,$hashref);
1.869     albertel 12347: 	return;
1.852     albertel 12348:     }
                   12349:     close($config);
1.871     albertel 12350:     my $which = (split('/',$url))[3];
                   12351:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12352:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12353:     my @content = <$config>;
1.1210    raeburn  12354:     &$func(\@content,$hashref);
                   12355:     return;
                   12356: }
                   12357: 
                   12358: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  12359: sub parse_dns_checksums_tab {
1.1210    raeburn  12360:     my ($lines,$hashref) = @_;
1.1264    raeburn  12361:     my $lonhost = $perlvar{'lonHostID'};
                   12362:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  12363:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  12364:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12365:     my $webconfdir = '/etc/httpd/conf';
                   12366:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12367:         $webconfdir = '/etc/apache2';
                   12368:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12369:         if ($1 >= 10) {
                   12370:             $webconfdir = '/etc/apache2';
                   12371:         }
                   12372:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12373:         if ($1 >= 10.0) {
                   12374:             $webconfdir = '/etc/apache2';
                   12375:         }
                   12376:     }
1.1210    raeburn  12377:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12378:     my (%chksum,%revnum);
                   12379:     if (ref($lines) eq 'ARRAY') {
                   12380:         chomp(@{$lines});
1.1238    raeburn  12381:         my $version = shift(@{$lines});
                   12382:         if ($version eq $release) {  
1.1210    raeburn  12383:             foreach my $line (@{$lines}) {
1.1238    raeburn  12384:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  12385:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12386:                     if ($webconfdir eq '/etc/apache2') {
                   12387:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12388:                     }
                   12389:                 }
1.1238    raeburn  12390:                 $chksum{$file} = $shasum;
                   12391:                 $revnum{$file} = $version;
1.1210    raeburn  12392:             }
                   12393:             if (ref($hashref) eq 'HASH') {
                   12394:                 %{$hashref} = (
                   12395:                                 sums     => \%chksum,
                   12396:                                 versions => \%revnum,
                   12397:                               );
                   12398:             }
                   12399:         }
                   12400:     }
1.869     albertel 12401:     return;
1.852     albertel 12402: }
1.1210    raeburn  12403: 
                   12404: sub fetch_dns_checksums {
1.1238    raeburn  12405:     my %checksums;
                   12406:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  12407:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  12408:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12409:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  12410:              \%checksums);
1.1210    raeburn  12411:     return \%checksums;
                   12412: }
                   12413: 
1.327     albertel 12414: # ------------------------------------------------------------ Read domain file
                   12415: {
1.852     albertel 12416:     my $loaded;
1.846     albertel 12417:     my %domain;
                   12418: 
1.852     albertel 12419:     sub parse_domain_tab {
                   12420: 	my ($lines) = @_;
                   12421: 	foreach my $line (@$lines) {
                   12422: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12423: 
1.846     albertel 12424: 	    chomp($line);
1.852     albertel 12425: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12426: 	    my %this_domain;
                   12427: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12428: 			       'lang_def', 'city', 'longi', 'lati',
                   12429: 			       'primary') {
                   12430: 		$this_domain{$field} = shift(@elements);
                   12431: 	    }
                   12432: 	    $domain{$name} = \%this_domain;
1.852     albertel 12433: 	}
                   12434:     }
1.864     albertel 12435: 
                   12436:     sub reset_domain_info {
                   12437: 	undef($loaded);
                   12438: 	undef(%domain);
                   12439:     }
                   12440: 
1.852     albertel 12441:     sub load_domain_tab {
1.1293    raeburn  12442: 	my ($ignore_cache,$nocache) = @_;
                   12443: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12444: 	my $fh;
                   12445: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12446: 	    my @lines = <$fh>;
                   12447: 	    &parse_domain_tab(\@lines);
1.448     albertel 12448: 	}
1.852     albertel 12449: 	close($fh);
                   12450: 	$loaded = 1;
1.327     albertel 12451:     }
1.846     albertel 12452: 
                   12453:     sub domain {
1.852     albertel 12454: 	&load_domain_tab() if (!$loaded);
                   12455: 
1.846     albertel 12456: 	my ($name,$what) = @_;
                   12457: 	return if ( !exists($domain{$name}) );
                   12458: 
                   12459: 	if (!$what) {
                   12460: 	    return $domain{$name}{'description'};
                   12461: 	}
                   12462: 	return $domain{$name}{$what};
                   12463:     }
1.974     raeburn  12464: 
                   12465:     sub domain_info {
                   12466:         &load_domain_tab() if (!$loaded);
                   12467:         return %domain;
                   12468:     }
                   12469: 
1.327     albertel 12470: }
                   12471: 
                   12472: 
1.1       albertel 12473: # ------------------------------------------------------------- Read hosts file
                   12474: {
1.838     albertel 12475:     my %hostname;
1.844     albertel 12476:     my %hostdom;
1.845     albertel 12477:     my %libserv;
1.852     albertel 12478:     my $loaded;
1.888     albertel 12479:     my %name_to_host;
1.1074    raeburn  12480:     my %internetdom;
1.1107    raeburn  12481:     my %LC_dns_serv;
1.852     albertel 12482: 
                   12483:     sub parse_hosts_tab {
                   12484: 	my ($file) = @_;
                   12485: 	foreach my $configline (@$file) {
                   12486: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12487:             chomp($configline);
                   12488: 	    if ($configline =~ /^\^/) {
                   12489:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12490:                     $LC_dns_serv{$1} = 1;
                   12491:                 }
                   12492:                 next;
                   12493:             }
1.1074    raeburn  12494: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12495: 	    $name=~s/\s//g;
                   12496: 	    if ($id && $domain && $role && $name) {
                   12497: 		$hostname{$id}=$name;
1.888     albertel 12498: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12499: 		$hostdom{$id}=$domain;
                   12500: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12501:                 if (defined($protocol)) {
                   12502:                     if ($protocol eq 'https') {
                   12503:                         $protocol{$id} = $protocol;
                   12504:                     } else {
                   12505:                         $protocol{$id} = 'http'; 
                   12506:                     }
1.968     raeburn  12507:                 } else {
1.969     raeburn  12508:                     $protocol{$id} = 'http';
1.968     raeburn  12509:                 }
1.1074    raeburn  12510:                 if (defined($intdom)) {
                   12511:                     $internetdom{$id} = $intdom;
                   12512:                 }
1.852     albertel 12513: 	    }
                   12514: 	}
                   12515:     }
1.864     albertel 12516:     
                   12517:     sub reset_hosts_info {
1.897     albertel 12518: 	&purge_remembered();
1.864     albertel 12519: 	&reset_domain_info();
                   12520: 	&reset_hosts_ip_info();
1.892     albertel 12521: 	undef(%name_to_host);
1.864     albertel 12522: 	undef(%hostname);
                   12523: 	undef(%hostdom);
                   12524: 	undef(%libserv);
                   12525: 	undef($loaded);
                   12526:     }
1.1       albertel 12527: 
1.852     albertel 12528:     sub load_hosts_tab {
1.1293    raeburn  12529: 	my ($ignore_cache,$nocache) = @_;
                   12530: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 12531: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12532: 	my @config = <$config>;
                   12533: 	&parse_hosts_tab(\@config);
                   12534: 	close($config);
                   12535: 	$loaded=1;
1.1       albertel 12536:     }
1.852     albertel 12537: 
1.838     albertel 12538:     sub hostname {
1.852     albertel 12539: 	&load_hosts_tab() if (!$loaded);
                   12540: 
1.838     albertel 12541: 	my ($lonid) = @_;
                   12542: 	return $hostname{$lonid};
                   12543:     }
1.845     albertel 12544: 
1.838     albertel 12545:     sub all_hostnames {
1.852     albertel 12546: 	&load_hosts_tab() if (!$loaded);
                   12547: 
1.838     albertel 12548: 	return %hostname;
                   12549:     }
1.845     albertel 12550: 
1.888     albertel 12551:     sub all_names {
1.1293    raeburn  12552:         my ($ignore_cache,$nocache) = @_;
                   12553: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 12554: 
                   12555: 	return %name_to_host;
                   12556:     }
                   12557: 
1.974     raeburn  12558:     sub all_host_domain {
                   12559:         &load_hosts_tab() if (!$loaded);
                   12560:         return %hostdom;
                   12561:     }
                   12562: 
1.845     albertel 12563:     sub is_library {
1.852     albertel 12564: 	&load_hosts_tab() if (!$loaded);
                   12565: 
1.845     albertel 12566: 	return exists($libserv{$_[0]});
                   12567:     }
                   12568: 
                   12569:     sub all_library {
1.852     albertel 12570: 	&load_hosts_tab() if (!$loaded);
                   12571: 
1.845     albertel 12572: 	return %libserv;
                   12573:     }
                   12574: 
1.1062    droeschl 12575:     sub unique_library {
                   12576: 	#2x reverse removes all hostnames that appear more than once
                   12577:         my %unique = reverse &all_library();
                   12578:         return reverse %unique;
                   12579:     }
                   12580: 
1.841     albertel 12581:     sub get_servers {
1.852     albertel 12582: 	&load_hosts_tab() if (!$loaded);
                   12583: 
1.841     albertel 12584: 	my ($domain,$type) = @_;
                   12585: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12586: 	                                          : %hostname;
                   12587: 	my %result;
1.842     albertel 12588: 	if (ref($domain) eq 'ARRAY') {
                   12589: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12590: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12591: 		    $result{$host} = $hostname;
                   12592: 		}
                   12593: 	    }
                   12594: 	} else {
                   12595: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12596: 		if ($hostdom{$host} eq $domain) {
                   12597: 		    $result{$host} = $hostname;
                   12598: 		}
1.841     albertel 12599: 	    }
                   12600: 	}
                   12601: 	return %result;
                   12602:     }
1.845     albertel 12603: 
1.1062    droeschl 12604:     sub get_unique_servers {
                   12605:         my %unique = reverse &get_servers(@_);
                   12606: 	return reverse %unique;
                   12607:     }
                   12608: 
1.844     albertel 12609:     sub host_domain {
1.852     albertel 12610: 	&load_hosts_tab() if (!$loaded);
                   12611: 
1.844     albertel 12612: 	my ($lonid) = @_;
                   12613: 	return $hostdom{$lonid};
                   12614:     }
                   12615: 
1.841     albertel 12616:     sub all_domains {
1.852     albertel 12617: 	&load_hosts_tab() if (!$loaded);
                   12618: 
1.841     albertel 12619: 	my %seen;
                   12620: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12621: 	return @uniq;
                   12622:     }
1.1074    raeburn  12623: 
                   12624:     sub internet_dom {
                   12625:         &load_hosts_tab() if (!$loaded);
                   12626: 
                   12627:         my ($lonid) = @_;
                   12628:         return $internetdom{$lonid};
                   12629:     }
1.1107    raeburn  12630: 
                   12631:     sub is_LC_dns {
                   12632:         &load_hosts_tab() if (!$loaded);
                   12633: 
                   12634:         my ($hostname) = @_;
                   12635:         return exists($LC_dns_serv{$hostname});
                   12636:     }
                   12637: 
1.1       albertel 12638: }
                   12639: 
1.847     albertel 12640: { 
                   12641:     my %iphost;
1.856     albertel 12642:     my %name_to_ip;
                   12643:     my %lonid_to_ip;
1.869     albertel 12644: 
1.847     albertel 12645:     sub get_hosts_from_ip {
                   12646: 	my ($ip) = @_;
                   12647: 	my %iphosts = &get_iphost();
                   12648: 	if (ref($iphosts{$ip})) {
                   12649: 	    return @{$iphosts{$ip}};
                   12650: 	}
                   12651: 	return;
1.839     albertel 12652:     }
1.864     albertel 12653:     
                   12654:     sub reset_hosts_ip_info {
                   12655: 	undef(%iphost);
                   12656: 	undef(%name_to_ip);
                   12657: 	undef(%lonid_to_ip);
                   12658:     }
1.856     albertel 12659: 
                   12660:     sub get_host_ip {
                   12661: 	my ($lonid) = @_;
                   12662: 	if (exists($lonid_to_ip{$lonid})) {
                   12663: 	    return $lonid_to_ip{$lonid};
                   12664: 	}
                   12665: 	my $name=&hostname($lonid);
                   12666:    	my $ip = gethostbyname($name);
                   12667: 	return if (!$ip || length($ip) ne 4);
                   12668: 	$ip=inet_ntoa($ip);
                   12669: 	$name_to_ip{$name}   = $ip;
                   12670: 	$lonid_to_ip{$lonid} = $ip;
                   12671: 	return $ip;
                   12672:     }
1.847     albertel 12673:     
                   12674:     sub get_iphost {
1.1293    raeburn  12675: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 12676: 
1.869     albertel 12677: 	if (!$ignore_cache) {
                   12678: 	    if (%iphost) {
                   12679: 		return %iphost;
                   12680: 	    }
                   12681: 	    my ($ip_info,$cached)=
                   12682: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12683: 	    if ($cached) {
                   12684: 		%iphost      = %{$ip_info->[0]};
                   12685: 		%name_to_ip  = %{$ip_info->[1]};
                   12686: 		%lonid_to_ip = %{$ip_info->[2]};
                   12687: 		return %iphost;
                   12688: 	    }
                   12689: 	}
1.894     albertel 12690: 
                   12691: 	# get yesterday's info for fallback
                   12692: 	my %old_name_to_ip;
                   12693: 	my ($ip_info,$cached)=
                   12694: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12695: 	if ($cached) {
                   12696: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12697: 	}
                   12698: 
1.1293    raeburn  12699: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 12700: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12701: 	    my $ip;
                   12702: 	    if (!exists($name_to_ip{$name})) {
                   12703: 		$ip = gethostbyname($name);
                   12704: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12705: 		    if (defined($old_name_to_ip{$name})) {
                   12706: 			$ip = $old_name_to_ip{$name};
                   12707: 			&logthis("Can't find $name defaulting to old $ip");
                   12708: 		    } else {
                   12709: 			&logthis("Name $name no IP found");
                   12710: 			next;
                   12711: 		    }
                   12712: 		} else {
                   12713: 		    $ip=inet_ntoa($ip);
1.847     albertel 12714: 		}
                   12715: 		$name_to_ip{$name} = $ip;
                   12716: 	    } else {
                   12717: 		$ip = $name_to_ip{$name};
1.653     albertel 12718: 	    }
1.888     albertel 12719: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12720: 		$lonid_to_ip{$id} = $ip;
                   12721: 	    }
                   12722: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12723: 	}
1.1293    raeburn  12724:         unless ($nocache) {
                   12725: 	    &do_cache_new('iphost','iphost',
                   12726: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12727: 		          48*60*60);
                   12728:         }
1.869     albertel 12729: 
1.847     albertel 12730: 	return %iphost;
1.598     albertel 12731:     }
                   12732: 
1.992     raeburn  12733:     #
                   12734:     #  Given a DNS returns the loncapa host name for that DNS 
                   12735:     # 
                   12736:     sub host_from_dns {
                   12737:         my ($dns) = @_;
                   12738:         my @hosts;
                   12739:         my $ip;
                   12740: 
1.993     raeburn  12741:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12742:             $ip = $name_to_ip{$dns};
                   12743:         }
                   12744:         if (!$ip) {
                   12745:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12746:             if (length($ip) == 4) { 
                   12747: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12748:             }
                   12749:         }
                   12750:         if ($ip) {
                   12751: 	    @hosts = get_hosts_from_ip($ip);
                   12752: 	    return $hosts[0];
                   12753:         }
                   12754:         return undef;
1.986     foxr     12755:     }
1.992     raeburn  12756: 
1.1074    raeburn  12757:     sub get_internet_names {
                   12758:         my ($lonid) = @_;
                   12759:         return if ($lonid eq '');
                   12760:         my ($idnref,$cached)=
                   12761:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12762:         if ($cached) {
                   12763:             return $idnref;
                   12764:         }
                   12765:         my $ip = &get_host_ip($lonid);
                   12766:         my @hosts = &get_hosts_from_ip($ip);
                   12767:         my %iphost = &get_iphost();
                   12768:         my (@idns,%seen);
                   12769:         foreach my $id (@hosts) {
                   12770:             my $dom = &host_domain($id);
                   12771:             my $prim_id = &domain($dom,'primary');
                   12772:             my $prim_ip = &get_host_ip($prim_id);
                   12773:             next if ($seen{$prim_ip});
                   12774:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12775:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12776:                     my $intdom = &internet_dom($id);
                   12777:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12778:                         push(@idns,$intdom);
                   12779:                     }
                   12780:                 }
                   12781:             }
                   12782:             $seen{$prim_ip} = 1;
                   12783:         }
1.1219    raeburn  12784:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12785:     }
                   12786: 
1.986     foxr     12787: }
                   12788: 
1.1079    raeburn  12789: sub all_loncaparevs {
1.1249    raeburn  12790:     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  12791: }
                   12792: 
1.1227    raeburn  12793: # ---------------------------------------------------------- Read loncaparev table
                   12794: {
                   12795:     sub load_loncaparevs { 
                   12796:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12797:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12798:                 while (my $configline=<$config>) {
                   12799:                     chomp($configline);
                   12800:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12801:                     $loncaparevs{$hostid}=$loncaparev;
                   12802:                 }
                   12803:                 close($config);
                   12804:             }
                   12805:         }
                   12806:     }
                   12807: }
                   12808: 
                   12809: # ---------------------------------------------------------- Read serverhostID table
                   12810: {
                   12811:     sub load_serverhomeIDs {
                   12812:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12813:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12814:                 while (my $configline=<$config>) {
                   12815:                     chomp($configline);
                   12816:                     my ($name,$id)=split(/:/,$configline);
                   12817:                     $serverhomeIDs{$name}=$id;
                   12818:                 }
                   12819:                 close($config);
                   12820:             }
                   12821:         }
                   12822:     }
                   12823: }
                   12824: 
                   12825: 
1.862     albertel 12826: BEGIN {
                   12827: 
                   12828: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12829:     unless ($readit) {
                   12830: {
                   12831:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12832:     %perlvar = (%perlvar,%{$configvars});
                   12833: }
                   12834: 
                   12835: 
1.1       albertel 12836: # ------------------------------------------------------ Read spare server file
                   12837: {
1.448     albertel 12838:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12839: 
                   12840:     while (my $configline=<$config>) {
                   12841:        chomp($configline);
1.284     matthew  12842:        if ($configline) {
1.784     albertel 12843: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12844: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12845: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12846:        }
                   12847:     }
1.448     albertel 12848:     close($config);
1.1       albertel 12849: }
1.11      www      12850: # ------------------------------------------------------------ Read permissions
                   12851: {
1.448     albertel 12852:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12853: 
                   12854:     while (my $configline=<$config>) {
1.448     albertel 12855: 	chomp($configline);
                   12856: 	if ($configline) {
                   12857: 	    my ($role,$perm)=split(/ /,$configline);
                   12858: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12859: 	}
1.11      www      12860:     }
1.448     albertel 12861:     close($config);
1.11      www      12862: }
                   12863: 
                   12864: # -------------------------------------------- Read plain texts for permissions
                   12865: {
1.448     albertel 12866:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12867: 
                   12868:     while (my $configline=<$config>) {
1.448     albertel 12869: 	chomp($configline);
                   12870: 	if ($configline) {
1.742     raeburn  12871: 	    my ($short,@plain)=split(/:/,$configline);
                   12872:             %{$prp{$short}} = ();
                   12873: 	    if (@plain > 0) {
                   12874:                 $prp{$short}{'std'} = $plain[0];
                   12875:                 for (my $i=1; $i<@plain; $i++) {
                   12876:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12877:                 }
                   12878:             }
1.448     albertel 12879: 	}
1.135     www      12880:     }
1.448     albertel 12881:     close($config);
1.135     www      12882: }
                   12883: 
                   12884: # ---------------------------------------------------------- Read package table
                   12885: {
1.448     albertel 12886:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12887: 
                   12888:     while (my $configline=<$config>) {
1.483     albertel 12889: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12890: 	chomp($configline);
                   12891: 	my ($short,$plain)=split(/:/,$configline);
                   12892: 	my ($pack,$name)=split(/\&/,$short);
                   12893: 	if ($plain ne '') {
                   12894: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12895: 	    $packagetab{$short}=$plain; 
                   12896: 	}
1.11      www      12897:     }
1.448     albertel 12898:     close($config);
1.329     matthew  12899: }
                   12900: 
1.1073    raeburn  12901: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  12902: 
                   12903: &load_loncaparevs();
1.1073    raeburn  12904: 
1.1074    raeburn  12905: # ---------------------------------------------------------- Read serverhostID table
                   12906: 
1.1227    raeburn  12907: &load_serverhomeIDs();
                   12908: 
                   12909: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12910: {
                   12911:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12912:     if (-e $file) {
                   12913:         my $parser = HTML::LCParser->new($file);
                   12914:         while (my $token = $parser->get_token()) {
                   12915:             if ($token->[0] eq 'S') {
                   12916:                 my $item = $token->[1];
                   12917:                 my $name = $token->[2]{'name'};
                   12918:                 my $value = $token->[2]{'value'};
1.1285    raeburn  12919:                 my $valuematch = $token->[2]{'valuematch'};
                   12920:                 if ($item ne '' && $name ne '' && ($value ne '' || $valuematch ne '')) {
1.1079    raeburn  12921:                     my $release = $parser->get_text();
                   12922:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1285    raeburn  12923:                     $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch} = $release;
1.1079    raeburn  12924:                 }
                   12925:             }
                   12926:         }
                   12927:     }
1.1073    raeburn  12928: }
                   12929: 
1.1138    raeburn  12930: # ---------------------------------------------------------- Read managers table
                   12931: {
                   12932:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12933:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12934:             while (my $configline=<$config>) {
                   12935:                 chomp($configline);
                   12936:                 next if ($configline =~ /^\#/);
                   12937:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12938:                     $managerstab{$configline} = 1;
                   12939:                 }
                   12940:             }
                   12941:             close($config);
                   12942:         }
                   12943:     }
                   12944: }
                   12945: 
1.329     matthew  12946: # ------------- set up temporary directory
                   12947: {
1.1117    foxr     12948:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12949: 
1.11      www      12950: }
                   12951: 
1.794     albertel 12952: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12953: 				'compress_threshold'=> 20_000,
                   12954:  			        });
1.185     www      12955: 
1.281     www      12956: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12957: $dumpcount=0;
1.958     www      12958: $locknum=0;
1.22      www      12959: 
1.163     harris41 12960: &logtouch();
1.672     albertel 12961: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12962: $readit=1;
1.564     albertel 12963:     {
                   12964: 	use integer;
                   12965: 	my $test=(2**32)+1;
1.568     albertel 12966: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12967: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12968:     }
1.195     www      12969: }
1.1       albertel 12970: }
1.179     www      12971: 
1.1       albertel 12972: 1;
1.191     harris41 12973: __END__
                   12974: 
1.243     albertel 12975: =pod
                   12976: 
1.191     harris41 12977: =head1 NAME
                   12978: 
1.243     albertel 12979: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12980: 
                   12981: =head1 SYNOPSIS
                   12982: 
1.243     albertel 12983: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12984: 
                   12985:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12986: 
1.243     albertel 12987: Common parameters:
                   12988: 
                   12989: =over 4
                   12990: 
                   12991: =item *
                   12992: 
                   12993: $uname : an internal username (if $cname expecting a course Id specifically)
                   12994: 
                   12995: =item *
                   12996: 
                   12997: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12998: 
                   12999: =item *
                   13000: 
                   13001: $symb : a resource instance identifier
                   13002: 
                   13003: =item *
                   13004: 
                   13005: $namespace : the name of a .db file that contains the data needed or
                   13006: being set.
                   13007: 
                   13008: =back
                   13009: 
1.394     bowersj2 13010: =head1 OVERVIEW
1.191     harris41 13011: 
1.394     bowersj2 13012: lonnet provides subroutines which interact with the
                   13013: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13014: about classes, users, and resources.
1.243     albertel 13015: 
                   13016: For many of these objects you can also use this to store data about
                   13017: them or modify them in various ways.
1.191     harris41 13018: 
1.394     bowersj2 13019: =head2 Symbs
1.191     harris41 13020: 
1.394     bowersj2 13021: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13022: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13023: map, the resource number of the resource in the map, and the URL of
                   13024: the resource itself. The latter is somewhat redundant, but might help
                   13025: if maps change.
                   13026: 
                   13027: An example is
                   13028: 
                   13029:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13030: 
                   13031: The respective map entry is
                   13032: 
                   13033:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13034:   title="Problem 2">
                   13035:  </resource>
                   13036: 
                   13037: Symbs are used by the random number generator, as well as to store and
                   13038: restore data specific to a certain instance of for example a problem.
                   13039: 
                   13040: =head2 Storing And Retrieving Data
                   13041: 
                   13042: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13043: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13044: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13045: is is the non-critical message twin of cstore. These functions are for
                   13046: handlers to store a perl hash to a user's permanent data space in an
                   13047: easy manner, and to retrieve it again on another call. It is expected
                   13048: that a handler would use this once at the beginning to retrieve data,
                   13049: and then again once at the end to send only the new data back.
                   13050: 
                   13051: The data is stored in the user's data directory on the user's
                   13052: homeserver under the ID of the course.
                   13053: 
                   13054: The hash that is returned by restore will have all of the previous
                   13055: value for all of the elements of the hash.
                   13056: 
                   13057: Example:
                   13058: 
                   13059:  #creating a hash
                   13060:  my %hash;
                   13061:  $hash{'foo'}='bar';
                   13062: 
                   13063:  #storing it
                   13064:  &Apache::lonnet::cstore(\%hash);
                   13065: 
                   13066:  #changing a value
                   13067:  $hash{'foo'}='notbar';
                   13068: 
                   13069:  #adding a new value
                   13070:  $hash{'bar'}='foo';
                   13071:  &Apache::lonnet::cstore(\%hash);
                   13072: 
                   13073:  #retrieving the hash
                   13074:  my %history=&Apache::lonnet::restore();
                   13075: 
                   13076:  #print the hash
                   13077:  foreach my $key (sort(keys(%history))) {
                   13078:    print("\%history{$key} = $history{$key}");
                   13079:  }
                   13080: 
                   13081: Will print out:
1.191     harris41 13082: 
1.394     bowersj2 13083:  %history{1:foo} = bar
                   13084:  %history{1:keys} = foo:timestamp
                   13085:  %history{1:timestamp} = 990455579
                   13086:  %history{2:bar} = foo
                   13087:  %history{2:foo} = notbar
                   13088:  %history{2:keys} = foo:bar:timestamp
                   13089:  %history{2:timestamp} = 990455580
                   13090:  %history{bar} = foo
                   13091:  %history{foo} = notbar
                   13092:  %history{timestamp} = 990455580
                   13093:  %history{version} = 2
                   13094: 
                   13095: Note that the special hash entries C<keys>, C<version> and
                   13096: C<timestamp> were added to the hash. C<version> will be equal to the
                   13097: total number of versions of the data that have been stored. The
                   13098: C<timestamp> attribute will be the UNIX time the hash was
                   13099: stored. C<keys> is available in every historical section to list which
                   13100: keys were added or changed at a specific historical revision of a
                   13101: hash.
                   13102: 
                   13103: B<Warning>: do not store the hash that restore returns directly. This
                   13104: will cause a mess since it will restore the historical keys as if the
                   13105: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13106: 
1.394     bowersj2 13107: Calling convention:
1.191     harris41 13108: 
1.1225    raeburn  13109:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  13110:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13111: 
1.394     bowersj2 13112: For more detailed information, see lonnet specific documentation.
1.191     harris41 13113: 
1.394     bowersj2 13114: =head1 RETURN MESSAGES
1.191     harris41 13115: 
1.394     bowersj2 13116: =over 4
1.191     harris41 13117: 
1.394     bowersj2 13118: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13119: 
1.394     bowersj2 13120: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13121: when the connection is brought back up
1.191     harris41 13122: 
1.394     bowersj2 13123: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13124: for later delivery
1.191     harris41 13125: 
1.967     bisitz   13126: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13127: 
1.394     bowersj2 13128: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13129: that was requested
1.191     harris41 13130: 
1.243     albertel 13131: =back
1.191     harris41 13132: 
1.243     albertel 13133: =head1 PUBLIC SUBROUTINES
1.191     harris41 13134: 
1.243     albertel 13135: =head2 Session Environment Functions
1.191     harris41 13136: 
1.243     albertel 13137: =over 4
1.191     harris41 13138: 
1.394     bowersj2 13139: =item * 
                   13140: X<appenv()>
1.949     raeburn  13141: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13142: the user envirnoment file, and will be restored for each access this
1.620     albertel 13143: user makes during this session, also modifies the %env for the current
1.949     raeburn  13144: process. Optional rolesarrayref - if defined contains a reference to an array
                   13145: of roles which are exempt from the restriction on modifying user.role entries 
                   13146: in the user's environment.db and in %env.    
1.191     harris41 13147: 
                   13148: =item *
1.394     bowersj2 13149: X<delenv()>
1.987     raeburn  13150: B<delenv($delthis,$regexp)>: removes all items from the session
                   13151: environment file that begin with $delthis. If the 
                   13152: optional second arg - $regexp - is true, $delthis is treated as a 
                   13153: regular expression, otherwise \Q$delthis\E is used. 
                   13154: The values are also deleted from the current processes %env.
1.191     harris41 13155: 
1.795     albertel 13156: =item * get_env_multiple($name) 
                   13157: 
                   13158: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13159: values may be defined and end up as an array ref.
                   13160: 
                   13161: returns an array of values
                   13162: 
1.243     albertel 13163: =back
                   13164: 
                   13165: =head2 User Information
1.191     harris41 13166: 
1.243     albertel 13167: =over 4
1.191     harris41 13168: 
                   13169: =item *
1.394     bowersj2 13170: X<queryauthenticate()>
                   13171: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13172: authentication scheme
                   13173: 
                   13174: =item *
1.394     bowersj2 13175: X<authenticate()>
1.1073    raeburn  13176: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13177: authenticate user from domain's lib servers (first use the current
                   13178: one). C<$upass> should be the users password.
1.1073    raeburn  13179: $checkdefauth is optional (value is 1 if a check should be made to
                   13180:    authenticate user using default authentication method, and allow
                   13181:    account creation if username does not have account in the domain).
                   13182: $clientcancheckhost is optional (value is 1 if checking whether the
                   13183:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13184: 
                   13185: =item *
1.394     bowersj2 13186: X<homeserver()>
                   13187: B<homeserver($uname,$udom)>: find the server which has
                   13188: the user's directory and files (there must be only one), this caches
                   13189: the answer, and also caches if there is a borken connection.
1.191     harris41 13190: 
                   13191: =item *
1.394     bowersj2 13192: X<idget()>
                   13193: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   13194: (IDs are a unique resource in a domain, there must be only 1 ID per
                   13195: username, and only 1 username per ID in a specific domain) (returns
                   13196: hash: id=>name,id=>name)
1.191     harris41 13197: 
                   13198: =item *
1.394     bowersj2 13199: X<idrget()>
                   13200: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13201: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13202: 
                   13203: =item *
1.394     bowersj2 13204: X<idput()>
                   13205: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 13206: 
                   13207: =item *
1.394     bowersj2 13208: X<rolesinit()>
1.1169    droeschl 13209: B<rolesinit($udom,$username)>: get user privileges.
                   13210: returns user role, first access and timer interval hashes
1.243     albertel 13211: 
                   13212: =item *
1.1171    droeschl 13213: X<privileged()>
                   13214: B<privileged($username,$domain)>: returns a true if user has a
                   13215: privileged and active role (i.e. su or dc), false otherwise.
                   13216: 
                   13217: =item *
1.551     albertel 13218: X<getsection()>
                   13219: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13220: course $cname, return section name/number or '' for "not in course"
                   13221: and '-1' for "no section"
                   13222: 
                   13223: =item *
1.394     bowersj2 13224: X<userenvironment()>
                   13225: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13226: passed in @what from the requested user's environment, returns a hash
                   13227: 
1.858     raeburn  13228: =item * 
                   13229: X<userlog_query()>
1.859     albertel 13230: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13231: activity.log file. %filters defines filters applied when parsing the
                   13232: log file. These can be start or end timestamps, or the type of action
                   13233: - log to look for Login or Logout events, check for Checkin or
                   13234: Checkout, role for role selection. The response is in the form
                   13235: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13236: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13237: 
1.243     albertel 13238: =back
                   13239: 
                   13240: =head2 User Roles
                   13241: 
                   13242: =over 4
                   13243: 
                   13244: =item *
                   13245: 
1.1284    raeburn  13246: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13247: returns codes for allowed actions.
                   13248: 
                   13249: The first argument is required, all others are optional.
                   13250: 
                   13251: $priv is the privilege being checked.
                   13252: $uri contains additional information about what is being checked for access (e.g.,
                   13253: URL, course ID etc.). 
                   13254: $symb is the unique resource instance identifier in a course; if needed,
                   13255: but not provided, it will be retrieved via a call to &symbread(). 
                   13256: $role is the role for which a priv is being checked (only used if priv is evb). 
                   13257: $clientip is the user's IP address (only used when checking for access to portfolio 
                   13258: files).
                   13259: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   13260: prevents recursive calls to &allowed.
                   13261: 
1.243     albertel 13262:  F: full access
                   13263:  U,I,K: authentication modes (cxx only)
                   13264:  '': forbidden
                   13265:  1: user needs to choose course
                   13266:  2: browse allowed
1.766     albertel 13267:  A: passphrase authentication needed
1.1284    raeburn  13268:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13269: 
                   13270: =item *
                   13271: 
1.1192    raeburn  13272: constructaccess($url,$setpriv) : check for access to construction space URL
                   13273: 
                   13274: See if the owner domain and name in the URL match those in the
                   13275: expected environment.  If so, return three element list
                   13276: ($ownername,$ownerdomain,$ownerhome).
                   13277: 
                   13278: Otherwise return the null string.
                   13279: 
                   13280: If second argument 'setpriv' is true, it assigns the privileges,
                   13281: and returns the same three element list, unless the owner has
                   13282: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13283: in which case the null string is returned.
                   13284: 
                   13285: =item *
                   13286: 
1.243     albertel 13287: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   13288: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   13289: and course level
                   13290: 
                   13291: =item *
                   13292: 
1.988     raeburn  13293: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13294: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13295: $type is Course (default) or Community.
1.988     raeburn  13296: If $forcedefault evaluates to true, text returned will be default 
                   13297: text for $type. Otherwise, if this is a course, the text returned 
                   13298: will be a custom name for the role (if defined in the course's 
                   13299: environment).  If no custom name is defined the default is returned.
                   13300:    
1.832     raeburn  13301: =item *
                   13302: 
1.1219    raeburn  13303: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13304: All arguments are optional. Returns a hash of a roles, either for
                   13305: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13306: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13307: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13308: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13309: For each key, value is set to colon-separated start and end times for
                   13310: the role.  If no username and domain are specified, will default to
1.934     raeburn  13311: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13312: of role statuses (active, future or previous), roles 
                   13313: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13314: to restrict the list of roles reported. If no array ref is 
                   13315: provided for types, will default to return only active roles.
1.834     albertel 13316: 
1.1195    raeburn  13317: =item *
                   13318: 
                   13319: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  13320: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   13321: 
                   13322: Additional optional arguments are: $type (if role checking is to be restricted 
                   13323: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  13324: available roles) or future (roles available in the future), and
                   13325: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  13326: have active Domain Coordinator role in course's domain or in additional
                   13327: domains (specified in 'Domains to check for privileged users' in course
                   13328: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13329: 
                   13330: =item *
                   13331: 
                   13332: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13333: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13334: $possdomains and $possroles are optional array refs -- to domains to check and
                   13335: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13336: users' roles.db to check for a dc or su role in any domain. This can be
                   13337: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13338: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13339: this then allows &privileged_by_domain() to be used, which caches the identity
                   13340: of privileged users, eliminating the need for repeated calls to &dump().
                   13341: 
                   13342: =item *
                   13343: 
                   13344: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13345: where the outer hash keys are domains specified in the $possdomains array ref,
                   13346: next inner hash keys are privileged roles specified in the $roles array ref,
                   13347: and the innermost hash contains key = value pairs for username:domain = end:start
                   13348: for active or future "privileged" users with that role in that domain. To avoid
                   13349: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13350: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  13351: 
1.243     albertel 13352: =back
                   13353: 
                   13354: =head2 User Modification
                   13355: 
                   13356: =over 4
                   13357: 
                   13358: =item *
                   13359: 
1.957     raeburn  13360: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13361: user for the level given by URL.  Optional start and end dates (leave empty
                   13362: string or zero for "no date")
1.191     harris41 13363: 
                   13364: =item *
                   13365: 
1.243     albertel 13366: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13367: change a users, password, possible return values are: ok,
                   13368: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13369: refused
1.191     harris41 13370: 
                   13371: =item *
                   13372: 
1.243     albertel 13373: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13374: 
                   13375: =item *
                   13376: 
1.1058    raeburn  13377: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13378:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13379: 
                   13380: will update user information (firstname,middlename,lastname,generation,
                   13381: permanentemail), and if forceid is true, student/employee ID also.
                   13382: A user's institutional affiliation(s) can also be updated.
                   13383: User information fields will not be overwritten with empty entries 
                   13384: unless the field is included in the $candelete array reference.
                   13385: This array is included when a single user is modified via "Manage Users",
                   13386: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13387: 
                   13388: =item *
                   13389: 
1.286     matthew  13390: modifystudent
                   13391: 
1.957     raeburn  13392: modify a student's enrollment and identification information.
1.1235    raeburn  13393: The course id is resolved based on the current user's environment.  
                   13394: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13395: associated with a course.
                   13396: 
1.297     matthew  13397: This call is essentially a wrapper for lonnet::modifyuser and
                   13398: lonnet::modify_student_enrollment
1.286     matthew  13399: 
                   13400: Inputs: 
                   13401: 
                   13402: =over 4
                   13403: 
1.957     raeburn  13404: =item B<$udom> Student's loncapa domain
1.286     matthew  13405: 
1.957     raeburn  13406: =item B<$uname> Student's loncapa login name
1.286     matthew  13407: 
1.964     bisitz   13408: =item B<$uid> Student/Employee ID
1.286     matthew  13409: 
1.957     raeburn  13410: =item B<$umode> Student's authentication mode
1.286     matthew  13411: 
1.957     raeburn  13412: =item B<$upass> Student's password
1.286     matthew  13413: 
1.957     raeburn  13414: =item B<$first> Student's first name
1.286     matthew  13415: 
1.957     raeburn  13416: =item B<$middle> Student's middle name
1.286     matthew  13417: 
1.957     raeburn  13418: =item B<$last> Student's last name
1.286     matthew  13419: 
1.957     raeburn  13420: =item B<$gene> Student's generation
1.286     matthew  13421: 
1.957     raeburn  13422: =item B<$usec> Student's section in course
1.286     matthew  13423: 
                   13424: =item B<$end> Unix time of the roles expiration
                   13425: 
                   13426: =item B<$start> Unix time of the roles start date
                   13427: 
                   13428: =item B<$forceid> If defined, allow $uid to be changed
                   13429: 
                   13430: =item B<$desiredhome> server to use as home server for student
                   13431: 
1.957     raeburn  13432: =item B<$email> Student's permanent e-mail address
                   13433: 
                   13434: =item B<$type> Type of enrollment (auto or manual)
                   13435: 
1.963     raeburn  13436: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13437: 
                   13438: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13439: 
1.963     raeburn  13440: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13441: 
1.963     raeburn  13442: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13443: 
1.1216    raeburn  13444: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13445: 
                   13446: =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  13447: 
1.286     matthew  13448: =back
1.297     matthew  13449: 
                   13450: =item *
                   13451: 
                   13452: modify_student_enrollment
                   13453: 
1.1235    raeburn  13454: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13455: 'role.request.course' must be defined for this function to proceed.
                   13456: 
                   13457: Inputs:
                   13458: 
                   13459: =over 4
                   13460: 
1.1235    raeburn  13461: =item $udom, student's domain
1.297     matthew  13462: 
1.1235    raeburn  13463: =item $uname, student's name
1.297     matthew  13464: 
1.1235    raeburn  13465: =item $uid, student's user id
1.297     matthew  13466: 
1.1235    raeburn  13467: =item $first, student's first name
1.297     matthew  13468: 
                   13469: =item $middle
                   13470: 
                   13471: =item $last
                   13472: 
                   13473: =item $gene
                   13474: 
                   13475: =item $usec
                   13476: 
                   13477: =item $end
                   13478: 
                   13479: =item $start
                   13480: 
1.957     raeburn  13481: =item $type
                   13482: 
                   13483: =item $locktype
                   13484: 
                   13485: =item $cid
                   13486: 
                   13487: =item $selfenroll
                   13488: 
                   13489: =item $context
                   13490: 
1.1216    raeburn  13491: =item $credits, number of credits student will earn from this class
                   13492: 
1.297     matthew  13493: =back
                   13494: 
1.191     harris41 13495: 
                   13496: =item *
                   13497: 
1.243     albertel 13498: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13499: custom role; give a custom role to a user for the level given by URL.  Specify
                   13500: name and domain of role author, and role name
1.191     harris41 13501: 
                   13502: =item *
                   13503: 
1.243     albertel 13504: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13505: 
                   13506: =item *
                   13507: 
1.243     albertel 13508: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13509: 
                   13510: =back
                   13511: 
                   13512: =head2 Course Infomation
                   13513: 
                   13514: =over 4
1.191     harris41 13515: 
                   13516: =item *
                   13517: 
1.1118    foxr     13518: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13519: specified course id, including all environment settings for the
                   13520: course, the description of the course will be in the hash under the
                   13521: key 'description'
1.191     harris41 13522: 
1.1118    foxr     13523: $options is an optional parameter that if supplied is a hash reference that controls
                   13524: what how this function works.  It has the following key/values:
                   13525: 
                   13526: =over 4
                   13527: 
                   13528: =item freshen_cache
                   13529: 
                   13530: If defined, and the environment cache for the course is valid, it is 
                   13531: returned in the returned hash.
                   13532: 
                   13533: =item one_time
                   13534: 
                   13535: If defined, the last cache time is set to _now_
                   13536: 
                   13537: =item user
                   13538: 
                   13539: If defined, the supplied username is used instead of the current user.
                   13540: 
                   13541: 
                   13542: =back
                   13543: 
1.191     harris41 13544: =item *
                   13545: 
1.624     albertel 13546: resdata($name,$domain,$type,@which) : request for current parameter
                   13547: setting for a specific $type, where $type is either 'course' or 'user',
                   13548: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  13549: answers for 10 minutes.
1.243     albertel 13550: 
1.877     foxr     13551: =item *
                   13552: 
                   13553: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13554: data base, returning a hash that is keyed by the resource name and has
                   13555: values that are the resource value.  I believe that the timestamps and
                   13556: versions are also returned.
                   13557: 
1.1236    raeburn  13558: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13559: supplemental content area. This routine caches the number of files for 
                   13560: 10 minutes.
                   13561: 
1.243     albertel 13562: =back
                   13563: 
                   13564: =head2 Course Modification
                   13565: 
                   13566: =over 4
1.191     harris41 13567: 
                   13568: =item *
                   13569: 
1.243     albertel 13570: writecoursepref($courseid,%prefs) : write preferences (environment
                   13571: database) for a course
1.191     harris41 13572: 
                   13573: =item *
                   13574: 
1.1011    raeburn  13575: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13576: 
                   13577: =item *
                   13578: 
1.1038    raeburn  13579: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13580: 
1.1167    droeschl 13581: =item *
                   13582: 
                   13583: is_course($courseid), is_course($cdom, $cnum)
                   13584: 
                   13585: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13586: two component version $cdom, $cnum. It checks if the specified course exists.
                   13587: 
                   13588: Returns:
                   13589:     undef if the course doesn't exist, otherwise
                   13590:     in scalar context the combined courseid.
                   13591:     in list context the two components of the course identifier, domain and 
                   13592:     courseid.    
                   13593: 
1.243     albertel 13594: =back
                   13595: 
                   13596: =head2 Resource Subroutines
                   13597: 
                   13598: =over 4
1.191     harris41 13599: 
                   13600: =item *
                   13601: 
1.243     albertel 13602: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13603: 
                   13604: =item *
                   13605: 
1.243     albertel 13606: repcopy($filename) : subscribes to the requested file, and attempts to
                   13607: replicate from the owning library server, Might return
1.607     raeburn  13608: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13609: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13610: resource. Expects the local filesystem pathname
                   13611: (/home/httpd/html/res/....)
                   13612: 
                   13613: =back
                   13614: 
                   13615: =head2 Resource Information
                   13616: 
                   13617: =over 4
1.191     harris41 13618: 
                   13619: =item *
                   13620: 
1.1228    raeburn  13621: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13622: and returns the value of a variety of different possible values,
                   13623: $varname should be a request string, and the other parameters can be
                   13624: used to specify who and what one is asking about. Ordinarily, $cid 
                   13625: does not need to be specified, as it is retrived from 
                   13626: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13627: within lonuserstate::loadmap() when initializing a course, before
                   13628: $env{'request.course.id'} has been set, so it needs to be provided
                   13629: in that one case.
1.243     albertel 13630: 
                   13631: Possible values for $varname are environment.lastname (or other item
                   13632: from the envirnment hash), user.name (or someother aspect about the
                   13633: user), resource.0.maxtries (or some other part and parameter of a
                   13634: resource)
1.204     albertel 13635: 
                   13636: =item *
                   13637: 
1.243     albertel 13638: directcondval($number) : get current value of a condition; reads from a state
                   13639: string
1.204     albertel 13640: 
                   13641: =item *
                   13642: 
1.243     albertel 13643: condval($condidx) : value of condition index based on state
1.204     albertel 13644: 
                   13645: =item *
                   13646: 
1.243     albertel 13647: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13648: resource's metadata, $what should be either a specific key, or either
                   13649: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13650: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13651: 
                   13652: this function automatically caches all requests
1.191     harris41 13653: 
                   13654: =item *
                   13655: 
1.243     albertel 13656: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13657: network of library servers; returns file handle of where SQL and regex results
                   13658: will be stored for query
1.191     harris41 13659: 
                   13660: =item *
                   13661: 
1.1282    raeburn  13662: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   13663: return symbolic list entry (all arguments optional). 
                   13664: 
                   13665: Args: filename is the filename (including path) for the file for which a symb 
                   13666: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   13667: to check access status if more than one resource was found in the bighash 
                   13668: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   13669: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   13670: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   13671: cause possible symbs to be checked to determine if they are subject to content
                   13672: blocking, if so they will not be included as possible symbs; possibles is a
                   13673: ref to a hash, which, as a side effect, will be populated with all possible 
                   13674: symbs (content blocking not tested).
                   13675:  
1.243     albertel 13676: returns the data handle
1.191     harris41 13677: 
                   13678: =item *
                   13679: 
1.1190    raeburn  13680: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   13681: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13682: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  13683: on failure, user must be in a course, as it assumes the existence of
                   13684: the course initial hash, and uses $env('request.course.id'}.  The third
                   13685: arg is an optional reference to a scalar.  If this arg is passed in the 
                   13686: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13687: encrypted; otherwise it will be null.  
1.191     harris41 13688: 
                   13689: =item *
                   13690: 
1.243     albertel 13691: symbclean($symb) : removes versions numbers from a symb, returns the
                   13692: cleaned symb
1.191     harris41 13693: 
                   13694: =item *
                   13695: 
1.243     albertel 13696: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13697: course map, user must be in a course for it to work.
1.191     harris41 13698: 
                   13699: =item *
                   13700: 
1.243     albertel 13701: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13702: 
                   13703: =item *
                   13704: 
1.243     albertel 13705: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13706: a random seed, all arguments are optional, if they aren't sent it uses the
                   13707: environment to derive them. Note: if symb isn't sent and it can't get one
                   13708: from &symbread it will use the current time as its return value
1.191     harris41 13709: 
                   13710: =item *
                   13711: 
1.243     albertel 13712: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13713: unfakeable, receipt
1.191     harris41 13714: 
                   13715: =item *
                   13716: 
1.620     albertel 13717: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13718: 
                   13719: =item *
                   13720: 
1.243     albertel 13721: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13722: 
                   13723: =item *
                   13724: 
1.243     albertel 13725: 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 13726: 
                   13727: =item *
                   13728: 
1.243     albertel 13729: 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 13730: 
                   13731: =item *
                   13732: 
1.243     albertel 13733: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13734: 
                   13735: =item *
                   13736: 
1.243     albertel 13737: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13738: forcing spreadsheet to reevaluate the resource scores next time.
                   13739: 
1.1195    raeburn  13740: =item * 
                   13741: 
1.1196    raeburn  13742: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13743: when viewing in course context.
1.1195    raeburn  13744: 
1.1196    raeburn  13745:  input: six args -- filename (decluttered), course number, course domain,
                   13746:                     url, symb (if registered) and group (if this is a 
                   13747:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  13748: 
1.1196    raeburn  13749:  output: array of five scalars --
1.1195    raeburn  13750:          $cfile -- url for file editing if editable on current server
                   13751:          $home -- homeserver of resource (i.e., for author if published,
                   13752:                                           or course if uploaded.).
                   13753:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  13754:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   13755:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  13756: 
                   13757: =item *
                   13758: 
                   13759: is_course_upload($file,$cnum,$cdom)
                   13760: 
                   13761: Used in course context to determine if current file was uploaded to 
                   13762: the course (i.e., would be found in /userfiles/docs on the course's 
                   13763: homeserver.
                   13764: 
                   13765:   input: 3 args -- filename (decluttered), course number and course domain.
                   13766:   output: boolean -- 1 if file was uploaded.
                   13767: 
1.243     albertel 13768: =back
                   13769: 
                   13770: =head2 Storing/Retreiving Data
                   13771: 
                   13772: =over 4
1.191     harris41 13773: 
                   13774: =item *
                   13775: 
1.1269    raeburn  13776: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   13777: permanently for this url; hashref needs to be given and should be a \%hashname;
                   13778: the remaining args aren't required and if they aren't passed or are '' they will
                   13779: be derived from the env (with the exception of $laststore, which is an 
                   13780: optional arg used when a user's submission is stored in grading).
                   13781: $laststore is $version=$timestamp, where $version is the most recent version
                   13782: number retrieved for the corresponding $symb in the $namespace db file, and
                   13783: $timestamp is the timestamp for that transaction (UNIX time).
                   13784: $laststore is currently only passed when cstore() is called by 
                   13785: structuretags::finalize_storage().
1.191     harris41 13786: 
                   13787: =item *
                   13788: 
1.1269    raeburn  13789: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   13790: but uses critical subroutine
1.191     harris41 13791: 
                   13792: =item *
                   13793: 
1.243     albertel 13794: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13795: all args are optional
1.191     harris41 13796: 
                   13797: =item *
                   13798: 
1.717     albertel 13799: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13800: dumps the complete (or key matching regexp) namespace into a hash
                   13801: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13802: normally &store()ed into
                   13803: 
                   13804: $range should be either an integer '100' (give me the first 100
                   13805:                                            matching records)
                   13806:               or be  two integers sperated by a - with no spaces
                   13807:                  '30-50' (give me the 30th through the 50th matching
                   13808:                           records)
                   13809: 
                   13810: 
                   13811: =item *
                   13812: 
1.1269    raeburn  13813: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 13814: replaces a &store() version of data with a replacement set of data
                   13815: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  13816: reference. If $tolog is true, the transaction is logged in the courselog
                   13817: with an action=PUTSTORE.
1.717     albertel 13818: 
                   13819: =item *
                   13820: 
1.243     albertel 13821: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13822: works very similar to store/cstore, but all data is stored in a
                   13823: temporary location and can be reset using tmpreset, $storehash should
                   13824: be a hash reference, returns nothing on success
1.191     harris41 13825: 
                   13826: =item *
                   13827: 
1.243     albertel 13828: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13829: similar to restore, but all data is stored in a temporary location and
                   13830: can be reset using tmpreset. Returns a hash of values on success,
                   13831: error string otherwise.
1.191     harris41 13832: 
                   13833: =item *
                   13834: 
1.243     albertel 13835: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13836: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13837: 
                   13838: =item *
                   13839: 
1.243     albertel 13840: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13841: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13842: 
                   13843: =item *
                   13844: 
1.243     albertel 13845: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13846: namesp ($udom and $uname are optional)
1.191     harris41 13847: 
                   13848: =item *
                   13849: 
1.702     albertel 13850: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13851: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13852: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13853: 
1.702     albertel 13854: $range should be either an integer '100' (give me the first 100
                   13855:                                            matching records)
                   13856:               or be  two integers sperated by a - with no spaces
                   13857:                  '30-50' (give me the 30th through the 50th matching
                   13858:                           records)
1.449     matthew  13859: =item *
                   13860: 
                   13861: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13862: $store can be a scalar, an array reference, or if the amount to be 
                   13863: incremented is > 1, a hash reference.
                   13864: 
                   13865: ($udom and $uname are optional)
1.191     harris41 13866: 
                   13867: =item *
                   13868: 
1.243     albertel 13869: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13870: ($udom and $uname are optional)
1.191     harris41 13871: 
                   13872: =item *
                   13873: 
1.243     albertel 13874: cput($namespace,$storehash,$udom,$uname) : critical put
                   13875: ($udom and $uname are optional)
1.191     harris41 13876: 
                   13877: =item *
                   13878: 
1.748     albertel 13879: newput($namespace,$storehash,$udom,$uname) :
                   13880: 
                   13881: Attempts to store the items in the $storehash, but only if they don't
                   13882: currently exist, if this succeeds you can be certain that you have 
                   13883: successfully created a new key value pair in the $namespace db.
                   13884: 
                   13885: 
                   13886: Args:
                   13887:  $namespace: name of database to store values to
                   13888:  $storehash: hashref to store to the db
                   13889:  $udom: (optional) domain of user containing the db
                   13890:  $uname: (optional) name of user caontaining the db
                   13891: 
                   13892: Returns:
                   13893:  'ok' -> succeeded in storing all keys of $storehash
                   13894:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13895:                         least <key> already existed in the db (other
                   13896:                         requested keys may also already exist)
1.967     bisitz   13897:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13898:  'con_lost' -> unable to contact request server
                   13899:  'refused' -> action was not allowed by remote machine
                   13900: 
                   13901: 
                   13902: =item *
                   13903: 
1.243     albertel 13904: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13905: reference filled in from namesp (encrypts the return communication)
                   13906: ($udom and $uname are optional)
1.191     harris41 13907: 
                   13908: =item *
                   13909: 
1.243     albertel 13910: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13911: critical subroutine
                   13912: 
1.806     raeburn  13913: =item *
                   13914: 
1.860     raeburn  13915: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13916: array reference filled in from namespace found in domain level on either
                   13917: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13918: 
                   13919: =item *
                   13920: 
1.860     raeburn  13921: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13922: domain level either on specified domain server ($uhome) or primary domain 
                   13923: server ($udom and $uhome are optional)
1.806     raeburn  13924: 
1.943     raeburn  13925: =item * 
                   13926: 
1.1240    raeburn  13927: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   13928: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13929: the target domain.
                   13930: 
                   13931: May also include additional key => value pairs for the following groups:
                   13932: 
                   13933: =over
                   13934: 
                   13935: =item
                   13936: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13937: 
                   13938: =over
                   13939: 
                   13940: =item defaultquota, authorquota
                   13941: 
                   13942: =back
                   13943: 
                   13944: =item
                   13945: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13946: portfolio for users).
                   13947: 
                   13948: =over
                   13949: 
                   13950: =item
                   13951: aboutme, blog, webdav, portfolio
                   13952: 
                   13953: =back
                   13954: 
                   13955: =item
                   13956: requestcourses: ability to request courses, and how requests are processed.
                   13957: 
                   13958: =over
                   13959: 
                   13960: =item
1.1246    raeburn  13961: official, unofficial, community, textbook
1.1240    raeburn  13962: 
                   13963: =back
                   13964: 
                   13965: =item
                   13966: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13967: 
                   13968: =over
                   13969: 
                   13970: =item
1.1256    raeburn  13971: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  13972: 
                   13973: =back
                   13974: 
                   13975: =item
                   13976: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13977: for course's uploaded content.
                   13978: 
                   13979: =over
                   13980: 
                   13981: =item
1.1246    raeburn  13982: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
                   13983: communityquota, textbookquota
1.1240    raeburn  13984: 
                   13985: =back
                   13986: 
                   13987: =item
                   13988: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13989: on your servers.
                   13990: 
                   13991: =over
                   13992: 
                   13993: =item 
                   13994: remotesessions, hostedsessions
                   13995: 
                   13996: =back
                   13997: 
                   13998: =back
                   13999: 
                   14000: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14001: utility to create a configuration.db file on a domain's primary library server 
                   14002: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14003: -- corresponding values are authentication type (internal, krb4, krb5,
                   14004: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   14005: will be available. Values are retrieved from cache (if current), unless the
                   14006: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14007: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14008: 
                   14009: Typical usage:
1.943     raeburn  14010: 
1.1240    raeburn  14011: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14012: 
1.243     albertel 14013: =back
                   14014: 
                   14015: =head2 Network Status Functions
                   14016: 
                   14017: =over 4
1.191     harris41 14018: 
                   14019: =item *
                   14020: 
1.1137    raeburn  14021: dirlist() : return directory list based on URI (first arg).
                   14022: 
                   14023: Inputs: 1 required, 5 optional.
                   14024: 
                   14025: =over
                   14026: 
                   14027: =item 
                   14028: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14029: 
                   14030: =item
                   14031: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14032: 
                   14033: =item
                   14034: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14035: 
                   14036: =item
                   14037: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14038: 
                   14039: =item
                   14040: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14041: 
                   14042: =item 
                   14043: $alternateRoot - path to prepend in place of path from $uri.
                   14044: 
                   14045: =back
                   14046: 
                   14047: Returns: Array of up to two items.
                   14048: 
                   14049: =over
                   14050: 
                   14051: a reference to an array of files/subdirectories
                   14052: 
                   14053: =over
                   14054: 
                   14055: Each element in the array of files/subdirectories is a & separated list of
                   14056: item name and the result of running stat on the item.  If dirlist was requested
                   14057: for a file instead of a directory, the item name will be ''. For a directory 
                   14058: listing, if the item is a metadata file, the element will end &N&M 
                   14059: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14060: default copyright set (1).  
                   14061: 
                   14062: =back
                   14063: 
                   14064: a scalar containing error condition (if encountered).
                   14065: 
                   14066: =over
                   14067: 
                   14068: =item 
                   14069: no_host (no homeserver identified for $username:$domain).
                   14070: 
                   14071: =item 
                   14072: no_such_host (server contacted for listing not identified as valid host).
                   14073: 
                   14074: =item 
                   14075: con_lost (connection to remote server failed).
                   14076: 
                   14077: =item 
                   14078: refused (invalid $username:$domain received on lond side).
                   14079: 
                   14080: =item 
                   14081: no_such_dir (directory at specified path on lond side does not exist). 
                   14082: 
                   14083: =item 
                   14084: empty (directory at specified path on lond side is empty).
                   14085: 
                   14086: =over
                   14087: 
                   14088: This is currently not encountered because the &ls3, &ls2, 
                   14089: &ls (_handler) routines on the lond side do not filter out
                   14090: . and .. from a directory listing. 
                   14091: 
                   14092: =back
                   14093: 
                   14094: =back
                   14095: 
                   14096: =back
1.191     harris41 14097: 
                   14098: =item *
                   14099: 
1.243     albertel 14100: spareserver() : find server with least workload from spare.tab
                   14101: 
1.986     foxr     14102: 
                   14103: =item *
                   14104: 
                   14105: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14106: if there is no corresponding loncapa host.
                   14107: 
1.243     albertel 14108: =back
                   14109: 
1.986     foxr     14110: 
1.243     albertel 14111: =head2 Apache Request
                   14112: 
                   14113: =over 4
1.191     harris41 14114: 
                   14115: =item *
                   14116: 
1.243     albertel 14117: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14118: localhost, posts hash
                   14119: 
                   14120: =back
                   14121: 
                   14122: =head2 Data to String to Data
                   14123: 
                   14124: =over 4
1.191     harris41 14125: 
                   14126: =item *
                   14127: 
1.243     albertel 14128: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14129: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14130: 
                   14131: =item *
                   14132: 
1.243     albertel 14133: hashref2str($hashref) : convert a hashref into a string complete with
                   14134: escaping and '=' and '&' separators, supports elements that are
                   14135: arrayrefs and hashrefs
1.191     harris41 14136: 
                   14137: =item *
                   14138: 
1.243     albertel 14139: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14140: with escaping and '&' separators, supports elements that are arrayrefs
                   14141: and hashrefs
1.191     harris41 14142: 
                   14143: =item *
                   14144: 
1.243     albertel 14145: str2hash($string) : convert string to hash using unescaping and
                   14146: splitting on '=' and '&', supports elements that are arrayrefs and
                   14147: hashrefs
1.191     harris41 14148: 
                   14149: =item *
                   14150: 
1.243     albertel 14151: str2array($string) : convert string to hash using unescaping and
                   14152: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14153: 
                   14154: =back
                   14155: 
                   14156: =head2 Logging Routines
                   14157: 
                   14158: 
                   14159: These routines allow one to make log messages in the lonnet.log and
                   14160: lonnet.perm logfiles.
1.191     harris41 14161: 
1.1119    foxr     14162: =over 4
                   14163: 
1.191     harris41 14164: =item *
                   14165: 
1.243     albertel 14166: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14167: 
                   14168: =item *
                   14169: 
1.243     albertel 14170: logthis() : append message to the normal lonnet.log file, it gets
                   14171: preiodically rolled over and deleted.
1.191     harris41 14172: 
                   14173: =item *
                   14174: 
1.243     albertel 14175: logperm() : append a permanent message to lonnet.perm.log, this log
                   14176: file never gets deleted by any automated portion of the system, only
                   14177: messages of critical importance should go in here.
                   14178: 
1.1119    foxr     14179: 
1.243     albertel 14180: =back
                   14181: 
                   14182: =head2 General File Helper Routines
                   14183: 
                   14184: =over 4
1.191     harris41 14185: 
                   14186: =item *
                   14187: 
1.481     raeburn  14188: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14189: (a) files in /uploaded
                   14190:   (i) If a local copy of the file exists - 
                   14191:       compares modification date of local copy with last-modified date for 
                   14192:       definitive version stored on home server for course. If local copy is 
                   14193:       stale, requests a new version from the home server and stores it. 
                   14194:       If the original has been removed from the home server, then local copy 
                   14195:       is unlinked.
                   14196:   (ii) If local copy does not exist -
                   14197:       requests the file from the home server and stores it. 
                   14198:   
                   14199:   If $caller is 'uploadrep':  
                   14200:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14201:     for request for files originally uploaded via DOCS. 
                   14202:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14203:   
                   14204:   Otherwise:
                   14205:      This indicates a call from the content generation phase of the request.
                   14206:      -  returns the entire contents of the file or -1.
                   14207:      
                   14208: (b) files in /res
                   14209:    - returns the entire contents of a file or -1; 
                   14210:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14211: 
1.712     albertel 14212: 
                   14213: =item *
                   14214: 
                   14215: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14216:                   reference
                   14217: 
                   14218: returns either a stat() list of data about the file or an empty list
                   14219: if the file doesn't exist or couldn't find out about it (connection
                   14220: problems or user unknown)
                   14221: 
1.191     harris41 14222: =item *
                   14223: 
1.243     albertel 14224: filelocation($dir,$file) : returns file system location of a file
                   14225: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14226: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14227: and a file of ../bob will become /a/bob)
1.191     harris41 14228: 
                   14229: =item *
                   14230: 
                   14231: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14232: filelocation except for hrefs
                   14233: 
                   14234: =item *
                   14235: 
1.1261    raeburn  14236: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14237: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14238: 
1.243     albertel 14239: =back
                   14240: 
1.608     albertel 14241: =head2 Usererfile file routines (/uploaded*)
                   14242: 
                   14243: =over 4
                   14244: 
                   14245: =item *
                   14246: 
                   14247: userfileupload(): main rotine for putting a file in a user or course's
                   14248:                   filespace, arguments are,
                   14249: 
1.620     albertel 14250:  formname - required - this is the name of the element in $env where the
1.608     albertel 14251:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14252:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14253:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14254:  context - if coursedoc, store the file in the course of the active role
                   14255:              of the current user; 
                   14256:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14257:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14258:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14259:          if undefined, it will be placed in "unknown"
                   14260: 
                   14261:  (This routine calls clean_filename() to remove any dangerous
                   14262:  characters from the filename, and then calls finuserfileupload() to
                   14263:  complete the transaction)
                   14264: 
                   14265:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14266:  and /adm/notfound.html if unsuccessful
                   14267: 
                   14268: =item *
                   14269: 
                   14270: clean_filename(): routine for cleaing a filename up for storage in
                   14271:                  userfile space, argument is:
                   14272: 
                   14273:  filename - proposed filename
                   14274: 
                   14275: returns: the new clean filename
                   14276: 
                   14277: =item *
                   14278: 
1.1090    raeburn  14279: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14280: userspace, probably shouldn't be called directly
                   14281: 
                   14282:   docuname: username or courseid of destination for the file
                   14283:   docudom: domain of user/course of destination for the file
                   14284:   formname: same as for userfileupload()
1.1090    raeburn  14285:   fname: filename (including subdirectories) for the file
                   14286:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14287:   allfiles: reference to hash used to store objects found by parser
                   14288:   codebase: reference to hash used for codebases of java objects found by parser
                   14289:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14290:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14291:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14292:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14293:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14294:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14295:   mimetype: reference to scalar to accommodate mime type determined
                   14296:             from File::MMagic if $parser = parse.
1.608     albertel 14297: 
                   14298:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14299:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14300:  was 'overwrite').
                   14301:  
1.608     albertel 14302: 
                   14303: =item *
                   14304: 
                   14305: renameuserfile(): renames an existing userfile to a new name
                   14306: 
                   14307:   Args:
                   14308:    docuname: username or courseid of destination for the file
                   14309:    docudom: domain of user/course of destination for the file
                   14310:    old: current file name (including any subdirs under userfiles)
                   14311:    new: desired file name (including any subdirs under userfiles)
                   14312: 
                   14313: =item *
                   14314: 
                   14315: mkdiruserfile(): creates a directory is a userfiles dir
                   14316: 
                   14317:   Args:
                   14318:    docuname: username or courseid of destination for the file
                   14319:    docudom: domain of user/course of destination for the file
                   14320:    dir: dir to create (including any subdirs under userfiles)
                   14321: 
                   14322: =item *
                   14323: 
                   14324: removeuserfile(): removes a file that exists in userfiles
                   14325: 
                   14326:   Args:
                   14327:    docuname: username or courseid of destination for the file
                   14328:    docudom: domain of user/course of destination for the file
                   14329:    fname: filname to delete (including any subdirs under userfiles)
                   14330: 
                   14331: =item *
                   14332: 
                   14333: removeuploadedurl(): convience function for removeuserfile()
                   14334: 
                   14335:   Args:
                   14336:    url:  a full /uploaded/... url to delete
                   14337: 
1.747     albertel 14338: =item * 
                   14339: 
                   14340: get_portfile_permissions():
                   14341:   Args:
                   14342:     domain: domain of user or course contain the portfolio files
                   14343:     user: name of user or num of course contain the portfolio files
                   14344:   Returns:
                   14345:     hashref of a dump of the proper file_permissions.db
                   14346:    
                   14347: 
                   14348: =item * 
                   14349: 
                   14350: get_access_controls():
                   14351: 
                   14352: Args:
                   14353:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14354:   group: (optional) the group you want the files associated with
                   14355:   file: (optional) the file you want access info on
                   14356: 
                   14357: Returns:
1.749     raeburn  14358:     a hash (keys are file names) of hashes containing
                   14359:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14360:         values are XML containing access control settings (see below) 
1.747     albertel 14361: 
                   14362: Internal notes:
                   14363: 
1.749     raeburn  14364:  access controls are stored in file_permissions.db as key=value pairs.
                   14365:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14366:         where scope -> public,guest,course,group,domains or users.
                   14367:               end -> UNIX time for end of access (0 -> no end date)
                   14368:               start -> UNIX time for start of access
                   14369: 
                   14370:     value -> XML description of access control
                   14371:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14372:             <start></start>
                   14373:             <end></end>
                   14374: 
                   14375:             <password></password>  for scope type = guest
                   14376: 
                   14377:             <domain></domain>     for scope type = course or group
                   14378:             <number></number>
                   14379:             <roles id="">
                   14380:              <role></role>
                   14381:              <access></access>
                   14382:              <section></section>
                   14383:              <group></group>
                   14384:             </roles>
                   14385: 
                   14386:             <dom></dom>         for scope type = domains
                   14387: 
                   14388:             <users>             for scope type = users
                   14389:              <user>
                   14390:               <uname></uname>
                   14391:               <udom></udom>
                   14392:              </user>
                   14393:             </users>
                   14394:            </scope> 
                   14395:               
                   14396:  Access data is also aggregated for each file in an additional key=value pair:
                   14397:  key -> path to file/file_name\0accesscontrol 
                   14398:  value -> reference to hash
                   14399:           hash contains key = value pairs
                   14400:           where key = uniqueID:scope_end_start
                   14401:                 value = UNIX time record was last updated
                   14402: 
                   14403:           Used to improve speed of look-ups of access controls for each file.  
                   14404:  
                   14405:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14406: 
1.1198    raeburn  14407: =item *
                   14408: 
1.749     raeburn  14409: modify_access_controls():
                   14410: 
                   14411: Modifies access controls for a portfolio file
                   14412: Args
                   14413: 1. file name
                   14414: 2. reference to hash of required changes,
                   14415: 3. domain
                   14416: 4. username
                   14417:   where domain,username are the domain of the portfolio owner 
                   14418:   (either a user or a course) 
                   14419: 
                   14420: Returns:
                   14421: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14422: 2. result of deletions ('ok' or 'error', with error message).
                   14423: 3. reference to hash of any new or updated access controls.
                   14424: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14425:    key = integer (inbound ID)
1.1198    raeburn  14426:    value = uniqueID
                   14427: 
                   14428: =item *
                   14429: 
                   14430: get_timebased_id():
                   14431: 
                   14432: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   14433: course via the Course Editor (e.g., folders, composite pages, 
                   14434: group bulletin boards).
                   14435: 
                   14436: Args: (first three required; six others optional)
                   14437: 
                   14438: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14439:    docssequence, or name of group
                   14440: 
                   14441: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14442:    e.g., num, boardids
                   14443: 
                   14444: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   14445:    file will be named nohist_namespace.db
                   14446: 
                   14447: 4. cdom: domain of course; default is current course domain from %env
                   14448: 
                   14449: 5. cnum: course number; default is current course number from %env
                   14450: 
                   14451: 6. idtype: set to concat if an additional digit is to be appended to the 
                   14452:    unix timestamp to form the suffix, if the plain timestamp is already
                   14453:    in use.  Default is to not do this, but simply increment the unix 
                   14454:    timestamp by 1 until a unique key is obtained.
                   14455: 
                   14456: 7. who: holder of locking key; defaults to user:domain for user.
                   14457: 
                   14458: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   14459:    retrying); default is 3.
                   14460: 
                   14461: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   14462: 
                   14463: Returns:
                   14464: 
                   14465: 1. suffix obtained (numeric)
                   14466: 
                   14467: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14468: 
                   14469: 3. error: contains (localized) error message if an error occurred.
                   14470: 
1.747     albertel 14471: 
1.608     albertel 14472: =back
                   14473: 
1.243     albertel 14474: =head2 HTTP Helper Routines
                   14475: 
                   14476: =over 4
                   14477: 
1.191     harris41 14478: =item *
                   14479: 
                   14480: escape() : unpack non-word characters into CGI-compatible hex codes
                   14481: 
                   14482: =item *
                   14483: 
                   14484: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14485: 
1.243     albertel 14486: =back
                   14487: 
                   14488: =head1 PRIVATE SUBROUTINES
                   14489: 
                   14490: =head2 Underlying communication routines (Shouldn't call)
                   14491: 
                   14492: =over 4
                   14493: 
                   14494: =item *
                   14495: 
                   14496: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14497: 
                   14498: =item *
                   14499: 
                   14500: reply() : uses subreply to send a message to remote machine, logs all failures
                   14501: 
                   14502: =item *
                   14503: 
                   14504: critical() : passes a critical message to another server; if cannot
                   14505: get through then place message in connection buffer directory and
                   14506: returns con_delayed, if incapable of saving message, returns
                   14507: con_failed
                   14508: 
                   14509: =item *
                   14510: 
                   14511: reconlonc() : tries to reconnect lonc client processes.
                   14512: 
                   14513: =back
                   14514: 
                   14515: =head2 Resource Access Logging
                   14516: 
                   14517: =over 4
                   14518: 
                   14519: =item *
                   14520: 
                   14521: flushcourselogs() : flush (save) buffer logs and access logs
                   14522: 
                   14523: =item *
                   14524: 
                   14525: courselog($what) : save message for course in hash
                   14526: 
                   14527: =item *
                   14528: 
                   14529: courseacclog($what) : save message for course using &courselog().  Perform
                   14530: special processing for specific resource types (problems, exams, quizzes, etc).
                   14531: 
1.191     harris41 14532: =item *
                   14533: 
                   14534: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14535: as a PerlChildExitHandler
1.243     albertel 14536: 
                   14537: =back
                   14538: 
                   14539: =head2 Other
                   14540: 
                   14541: =over 4
                   14542: 
                   14543: =item *
                   14544: 
                   14545: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14546: 
                   14547: =back
                   14548: 
                   14549: =cut
1.877     foxr     14550: 

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