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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1291  ! raeburn     4: # $Id: lonnet.pm,v 1.1290 2015/08/05 18:47:25 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:     my $hostname = &hostname($lonid);
                    426:     if ($lonid) {
                    427: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    428: 	if ($hostname && -e $peerfile) {
                    429: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    430: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    431: 					     Type    => SOCK_STREAM,
                    432: 					     Timeout => 10);
                    433: 	    if ($client) {
                    434: 		print $client ("reset_retries\n");
                    435: 		my $answer=<$client>;
                    436: 		#reset just this one.
                    437: 	    }
                    438: 	}
                    439: 	return;
                    440:     }
                    441: 
1.836     www       442:     &logthis("Trying to reconnect lonc");
1.1       albertel  443:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  444:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  445: 	my $loncpid=<$fh>;
                    446:         chomp($loncpid);
                    447:         if (kill 0 => $loncpid) {
                    448: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    449:             kill USR1 => $loncpid;
                    450:             sleep 1;
1.836     www       451:          } else {
1.12      www       452: 	    &logthis(
1.672     albertel  453:                "<font color=\"blue\">WARNING:".
1.12      www       454:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  455:         }
                    456:     } else {
1.836     www       457: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  458:     }
                    459: }
                    460: 
                    461: # ------------------------------------------------------ Critical communication
1.12      www       462: 
1.1       albertel  463: sub critical {
                    464:     my ($cmd,$server)=@_;
1.838     albertel  465:     unless (&hostname($server)) {
1.672     albertel  466:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       467:                " Critical message to unknown server ($server)</font>");
                    468:         return 'no_such_host';
                    469:     }
1.1       albertel  470:     my $answer=reply($cmd,$server);
                    471:     if ($answer eq 'con_lost') {
                    472: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  473: 	my $answer=reply($cmd,$server);
1.1       albertel  474:         if ($answer eq 'con_lost') {
                    475:             my $now=time;
                    476:             my $middlename=$cmd;
1.5       www       477:             $middlename=substr($middlename,0,16);
1.1       albertel  478:             $middlename=~s/\W//g;
                    479:             my $dfilename=
1.305     www       480:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    481:             $dumpcount++;
1.1       albertel  482:             {
1.448     albertel  483: 		my $dfh;
                    484: 		if (open($dfh,">$dfilename")) {
                    485: 		    print $dfh "$cmd\n"; 
                    486: 		    close($dfh);
                    487: 		}
1.1       albertel  488:             }
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)) {
                   1562: 	my $idlist=join('&',@ids);
                   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]) {
                   1572: 		$returnhash{$ids[$i]}=$answer[$i];
                   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.1208    raeburn  2983:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2984:                     $incourse = 1;
                   2985:                     if ($env{'form.forceedit'}) {
                   2986:                         $forceview = 1;
                   2987:                     } else {
                   2988:                         $forceedit = 1;
                   2989:                     }
                   2990:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  2991:                 }
                   2992:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2993:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2994:                 if (&is_on_map($template)) { 
                   2995:                     $incourse = 1;
                   2996:                     $forceview = 1;
                   2997:                     $cfile = $template;
1.1193    raeburn  2998:                 }
1.1199    raeburn  2999:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3000:                     $incourse = 1;
                   3001:                     if ($env{'form.forceedit'}) {
                   3002:                         $forceview = 1;
                   3003:                     } else {
                   3004:                         $forceedit = 1;
                   3005:                     }
                   3006:                     $cfile = $resurl;
                   3007:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3008:                 $incourse = 1;
                   3009:                 $forceview = 1;
                   3010:                 if ($symb) {
                   3011:                     my ($map,$id,$res)=&decode_symb($symb);
                   3012:                     $env{'request.symb'} = $symb;
                   3013:                     $cfile = &clutter($res);
                   3014:                 } else {
                   3015:                     $cfile = $env{'form.suppurl'};
                   3016:                     $cfile =~ s{^http://}{};
                   3017:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3018:                 }
1.1234    raeburn  3019:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3020:                 if ($env{'form.forceedit'}) {
                   3021:                     $forceview = 1;
                   3022:                 } else {
                   3023:                     $forceedit = 1;
                   3024:                 }
                   3025:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3026:             }
                   3027:         }
1.1194    raeburn  3028:         if ($uploaded || $incourse) {
                   3029:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3030:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3031:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3032:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3033:             # Check that the user has permission to edit this resource
                   3034:             my $setpriv = 1;
                   3035:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3036:             if (defined($cfudom)) {
                   3037:                 $home=&homeserver($cfuname,$cfudom);
                   3038:                 $cfile=$file;
                   3039:             }
                   3040:         }
1.1194    raeburn  3041:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3042:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3043:             my @ids=&current_machine_ids();
                   3044:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3045:                 $switchserver=1;
                   3046:             }
                   3047:         }
                   3048:     }
1.1194    raeburn  3049:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3050: }
                   3051: 
                   3052: sub is_course_upload {
                   3053:     my ($file,$cnum,$cdom) = @_;
                   3054:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3055:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3056:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3057:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3058:         return 1;
                   3059:     }
                   3060:     return;
                   3061: }
                   3062: 
1.1194    raeburn  3063: sub in_course {
1.1195    raeburn  3064:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3065:     if ($hideprivileged) {
                   3066:         my $skipuser;
1.1219    raeburn  3067:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3068:         my @possdoms = ($cdom);  
                   3069:         if ($coursehash{'checkforpriv'}) { 
                   3070:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3071:         }
                   3072:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3073:             $skipuser = 1;
                   3074:             if ($coursehash{'nothideprivileged'}) {
                   3075:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3076:                     my $user;
                   3077:                     if ($item =~ /:/) {
                   3078:                         $user = $item;
                   3079:                     } else {
                   3080:                         $user = join(':',split(/[\@]/,$item));
                   3081:                     }
                   3082:                     if ($user eq $uname.':'.$udom) {
                   3083:                         undef($skipuser);
                   3084:                         last;
                   3085:                     }
                   3086:                 }
                   3087:             }
                   3088:             if ($skipuser) {
                   3089:                 return 0;
                   3090:             }
                   3091:         }
                   3092:     }
1.1194    raeburn  3093:     $type ||= 'any';
                   3094:     if (!defined($cdom) || !defined($cnum)) {
                   3095:         my $cid  = $env{'request.course.id'};
                   3096:         $cdom = $env{'course.'.$cid.'.domain'};
                   3097:         $cnum = $env{'course.'.$cid.'.num'};
                   3098:     }
                   3099:     my $typesref;
1.1195    raeburn  3100:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3101:         $typesref = ['active','previous','future'];
                   3102:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3103:         $typesref = [$type];
                   3104:     }
                   3105:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3106:                               $typesref,undef,[$cdom]);
                   3107:     my ($tmp) = keys(%roles);
                   3108:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3109:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3110:     if (@course_roles > 0) {
                   3111:         return 1;
                   3112:     }
                   3113:     return 0;
                   3114: }
                   3115: 
1.478     albertel 3116: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3117: # input: action, courseID, current domain, intended
1.637     raeburn  3118: #        path to file, source of file, instruction to parse file for objects,
                   3119: #        ref to hash for embedded objects,
                   3120: #        ref to hash for codebase of java objects.
1.1095    raeburn  3121: #        reference to scalar to accommodate mime type determined
                   3122: #          from File::MMagic if $parser = parse.
1.637     raeburn  3123: #
1.485     raeburn  3124: # output: url to file (if action was uploaddoc), 
                   3125: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3126: #
1.478     albertel 3127: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3128: # course.
1.477     raeburn  3129: #
1.478     albertel 3130: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3131: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3132: #          course's home server.
1.477     raeburn  3133: #
1.478     albertel 3134: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3135: #          be copied from $source (current location) to 
                   3136: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3137: #         and will then be copied to
                   3138: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3139: #         course's home server.
1.485     raeburn  3140: #
1.481     raeburn  3141: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3142: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3143: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3144: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3145: #         in course's home server.
1.637     raeburn  3146: #
1.477     raeburn  3147: 
                   3148: sub process_coursefile {
1.1095    raeburn  3149:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3150:         $mimetype)=@_;
1.477     raeburn  3151:     my $fetchresult;
1.638     albertel 3152:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3153:     if ($action eq 'propagate') {
1.638     albertel 3154:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3155: 			     $home);
1.481     raeburn  3156:     } else {
1.477     raeburn  3157:         my $fpath = '';
                   3158:         my $fname = $file;
1.478     albertel 3159:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3160:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3161:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3162:         if ($action eq 'copy') {
                   3163:             if ($source eq '') {
                   3164:                 $fetchresult = 'no source file';
                   3165:                 return $fetchresult;
                   3166:             } else {
                   3167:                 my $destination = $filepath.'/'.$fname;
                   3168:                 rename($source,$destination);
                   3169:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3170:                                  $home);
1.481     raeburn  3171:             }
                   3172:         } elsif ($action eq 'uploaddoc') {
                   3173:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3174:             print $fh $env{'form.'.$source};
1.481     raeburn  3175:             close($fh);
1.637     raeburn  3176:             if ($parser eq 'parse') {
1.1024    raeburn  3177:                 my $mm = new File::MMagic;
1.1095    raeburn  3178:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3179:                 if ($type eq 'text/html') {
1.1024    raeburn  3180:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3181:                     unless ($parse_result eq 'ok') {
                   3182:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3183:                     }
1.637     raeburn  3184:                 }
1.1095    raeburn  3185:                 if (ref($mimetype)) {
                   3186:                     $$mimetype = $type;
                   3187:                 } 
1.637     raeburn  3188:             }
1.477     raeburn  3189:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3190:                                  $home);
1.481     raeburn  3191:             if ($fetchresult eq 'ok') {
                   3192:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3193:             } else {
                   3194:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3195:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3196:                 return '/adm/notfound.html';
                   3197:             }
1.477     raeburn  3198:         }
                   3199:     }
1.485     raeburn  3200:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3201:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3202:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3203:     }
                   3204:     return $fetchresult;
                   3205: }
                   3206: 
1.637     raeburn  3207: sub build_filepath {
                   3208:     my ($fpath) = @_;
                   3209:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3210:     unless ($fpath eq '') {
                   3211:         my @parts=split('/',$fpath);
                   3212:         foreach my $part (@parts) {
                   3213:             $filepath.= '/'.$part;
                   3214:             if ((-e $filepath)!=1) {
                   3215:                 mkdir($filepath,0777);
                   3216:             }
                   3217:         }
                   3218:     }
                   3219:     return $filepath;
                   3220: }
                   3221: 
                   3222: sub store_edited_file {
1.638     albertel 3223:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3224:     my $file = $primary_url;
                   3225:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3226:     my $fpath = '';
                   3227:     my $fname = $file;
                   3228:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3229:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3230:     my $filepath = &build_filepath($fpath);
                   3231:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3232:     print $fh $content;
                   3233:     close($fh);
1.638     albertel 3234:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3235:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3236: 			  $home);
1.637     raeburn  3237:     if ($$fetchresult eq 'ok') {
                   3238:         return '/uploaded/'.$fpath.'/'.$fname;
                   3239:     } else {
1.638     albertel 3240:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3241: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3242:         return '/adm/notfound.html';
                   3243:     }
                   3244: }
                   3245: 
1.531     albertel 3246: sub clean_filename {
1.831     albertel 3247:     my ($fname,$args)=@_;
1.315     www      3248: # Replace Windows backslashes by forward slashes
1.257     www      3249:     $fname=~s/\\/\//g;
1.831     albertel 3250:     if (!$args->{'keep_path'}) {
                   3251:         # Get rid of everything but the actual filename
                   3252: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3253:     }
1.315     www      3254: # Replace spaces by underscores
                   3255:     $fname=~s/\s+/\_/g;
                   3256: # Replace all other weird characters by nothing
1.831     albertel 3257:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3258: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3259: # numbers
                   3260:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3261:     return $fname;
                   3262: }
1.1051    raeburn  3263: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3264: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3265: # image with the same aspect ratio as the original, but with dimensions which do 
                   3266: # not exceed $resizewidth and $resizeheight.
                   3267:  
1.984     neumanie 3268: sub resizeImage {
1.1051    raeburn  3269:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3270:     my $ima = Image::Magick->new;
                   3271:     my $resized;
                   3272:     if (-e $img_path) {
                   3273:         $ima->Read($img_path);
                   3274:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3275:             my $width = $ima->Get('width');
                   3276:             my $height = $ima->Get('height');
                   3277:             if ($width > $resizewidth) {
                   3278: 	        my $factor = $width/$resizewidth;
                   3279:                 my $newheight = $height/$factor;
                   3280:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3281:                 $resized = 1;
                   3282:             }
                   3283:         }
                   3284:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3285:             my $width = $ima->Get('width');
                   3286:             my $height = $ima->Get('height');
                   3287:             if ($height > $resizeheight) {
                   3288:                 my $factor = $height/$resizeheight;
                   3289:                 my $newwidth = $width/$factor;
                   3290:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3291:                 $resized = 1;
                   3292:             }
                   3293:         }
                   3294:         if ($resized) {
                   3295:             $ima->Write($img_path);
                   3296:         }
                   3297:     }
                   3298:     return;
1.977     amueller 3299: }
                   3300: 
1.608     albertel 3301: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3302: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3303: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3304: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3305: #                                    canceloverwrite, or ''. 
                   3306: #                   if 'coursedoc': upload to the current course
                   3307: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3308: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3309: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3310: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3311: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3312: #        $allfiles - reference to hash for embedded objects
                   3313: #        $codebase - reference to hash for codebase of java objects
                   3314: #        $desuname - username for permanent storage of uploaded file
                   3315: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3316: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3317: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3318: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3319: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3320: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3321: #                    from File::MMagic.
1.858     raeburn  3322: # 
1.686     albertel 3323: # output: url of file in userspace, or error: <message> 
                   3324: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3325: 
1.531     albertel 3326: sub userfileupload {
1.1090    raeburn  3327:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3328:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3329:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3330:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3331:     $fname=&clean_filename($fname);
1.1090    raeburn  3332:     # See if there is anything left
1.257     www      3333:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3334:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3335:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3336:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3337:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3338:         my $now = time;
1.1090    raeburn  3339:         my $filepath;
1.1095    raeburn  3340:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3341:              $filepath = 'tmp/helprequests/'.$now;
                   3342:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3343:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3344:                          '_'.$env{'user.domain'}.'/pending';
                   3345:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3346:             my ($docuname,$docudom);
                   3347:             if ($destudom) {
                   3348:                 $docudom = $destudom;
                   3349:             } else {
                   3350:                 $docudom = $env{'user.domain'};
                   3351:             }
                   3352:             if ($destuname) {
                   3353:                 $docuname = $destuname;
                   3354:             } else {
                   3355:                 $docuname = $env{'user.name'};
                   3356:             }
                   3357:             if (exists($env{'form.group'})) {
                   3358:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3359:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3360:             }
                   3361:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3362:             if ($context eq 'canceloverwrite') {
                   3363:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3364:                 if (-e  $tempfile) {
                   3365:                     my @info = stat($tempfile);
                   3366:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3367:                         unlink($tempfile);
                   3368:                     }
                   3369:                 }
                   3370:                 return;
1.523     raeburn  3371:             }
                   3372:         }
1.1090    raeburn  3373:         # Create the directory if not present
1.741     raeburn  3374:         my @parts=split(/\//,$filepath);
                   3375:         my $fullpath = $perlvar{'lonDaemons'};
                   3376:         for (my $i=0;$i<@parts;$i++) {
                   3377:             $fullpath .= '/'.$parts[$i];
                   3378:             if ((-e $fullpath)!=1) {
                   3379:                 mkdir($fullpath,0777);
                   3380:             }
                   3381:         }
                   3382:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3383:         print $fh $env{'form.'.$formname};
                   3384:         close($fh);
1.1090    raeburn  3385:         if ($context eq 'existingfile') {
                   3386:             my @info = stat($fullpath.'/'.$fname);
                   3387:             return ($fullpath.'/'.$fname,$info[9]);
                   3388:         } else {
                   3389:             return $fullpath.'/'.$fname;
                   3390:         }
1.523     raeburn  3391:     }
1.995     raeburn  3392:     if ($subdir eq 'scantron') {
                   3393:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3394:     } else {
1.995     raeburn  3395:         $fname="$subdir/$fname";
                   3396:     }
1.1090    raeburn  3397:     if ($context eq 'coursedoc') {
1.638     albertel 3398: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3399: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3400:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3401:             return &finishuserfileupload($docuname,$docudom,
                   3402: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3403: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3404:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3405:         } else {
1.1218    raeburn  3406:             if ($env{'form.folder'}) {
                   3407:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3408:             }
1.638     albertel 3409:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3410: 				       $fname,$formname,$parser,
1.1095    raeburn  3411: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3412:         }
1.719     banghart 3413:     } elsif (defined($destuname)) {
                   3414:         my $docuname=$destuname;
                   3415:         my $docudom=$destudom;
1.860     raeburn  3416: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3417: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3418:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3419:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3420:     } else {
1.638     albertel 3421:         my $docuname=$env{'user.name'};
                   3422:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3423:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3424:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3425:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3426:         }
1.860     raeburn  3427: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3428: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3429:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3430:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3431:     }
1.271     www      3432: }
                   3433: 
                   3434: sub finishuserfileupload {
1.860     raeburn  3435:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3436:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3437:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3438:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3439:   
1.860     raeburn  3440:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3441:     $file=$fname;
                   3442:     if ($fname=~m|/|) {
                   3443:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3444: 	$path.=$fnamepath.'/';
                   3445:     }
1.259     www      3446:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3447:     my $count;
                   3448:     for ($count=4;$count<=$#parts;$count++) {
                   3449:         $filepath.="/$parts[$count]";
                   3450:         if ((-e $filepath)!=1) {
                   3451: 	    mkdir($filepath,0777);
                   3452:         }
                   3453:     }
1.984     neumanie 3454: 
1.258     www      3455: # Save the file
                   3456:     {
1.701     albertel 3457: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3458: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3459: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3460: 	    return '/adm/notfound.html';
                   3461: 	}
1.1090    raeburn  3462:         if ($context eq 'overwrite') {
1.1117    foxr     3463:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3464:             my $target = $filepath.'/'.$file;
                   3465:             if (-e $source) {
                   3466:                 my @info = stat($source);
                   3467:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3468:                     unless (&File::Copy::move($source,$target)) {
                   3469:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3470:                         return "Moving from $source failed";
                   3471:                     }
                   3472:                 } else {
                   3473:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3474:                 }
                   3475:             } else {
                   3476:                 return "Temporary file: $source missing";
                   3477:             }
                   3478:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3479: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3480: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3481: 	    return '/adm/notfound.html';
                   3482: 	}
1.570     albertel 3483: 	close(FH);
1.1051    raeburn  3484:         if ($resizewidth && $resizeheight) {
                   3485:             my $mm = new File::MMagic;
                   3486:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3487:             if ($mime_type =~ m{^image/}) {
                   3488: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3489:             }  
1.977     amueller 3490: 	}
1.258     www      3491:     }
1.1152    raeburn  3492:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3493:         if (ref($mimetype)) {
                   3494:             if ($$mimetype eq '') {
                   3495:                 my $mm = new File::MMagic;
                   3496:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3497:                 $$mimetype = $type;
                   3498:             }
                   3499:         }
                   3500:     }
1.637     raeburn  3501:     if ($parser eq 'parse') {
1.1152    raeburn  3502:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3503:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3504:                                                        $allfiles,$codebase);
                   3505:             unless ($parse_result eq 'ok') {
                   3506:                 &logthis('Failed to parse '.$filepath.$file.
                   3507: 	   	         ' for embedded media: '.$parse_result); 
                   3508:             }
1.637     raeburn  3509:         }
                   3510:     }
1.860     raeburn  3511:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3512:         my $input = $filepath.'/'.$file;
                   3513:         my $output = $filepath.'/'.'tn-'.$file;
                   3514:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3515:         system("convert -sample $thumbsize $input $output");
                   3516:         if (-e $filepath.'/'.'tn-'.$file) {
                   3517:             $fetchthumb  = 1; 
                   3518:         }
                   3519:     }
1.858     raeburn  3520:  
1.259     www      3521: # Notify homeserver to grep it
                   3522: #
1.984     neumanie 3523:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3524:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3525:     if ($fetchresult eq 'ok') {
1.860     raeburn  3526:         if ($fetchthumb) {
                   3527:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3528:             if ($thumbresult ne 'ok') {
                   3529:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3530:                          $docuhome.': '.$thumbresult);
                   3531:             }
                   3532:         }
1.259     www      3533: #
1.258     www      3534: # Return the URL to it
1.494     albertel 3535:         return '/uploaded/'.$path.$file;
1.263     www      3536:     } else {
1.494     albertel 3537:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3538: 		 ': '.$fetchresult);
1.263     www      3539:         return '/adm/notfound.html';
1.858     raeburn  3540:     }
1.493     albertel 3541: }
                   3542: 
1.637     raeburn  3543: sub extract_embedded_items {
1.961     raeburn  3544:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3545:     my @state = ();
1.1164    raeburn  3546:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3547:     my %javafiles = (
                   3548:                       codebase => '',
                   3549:                       code => '',
                   3550:                       archive => ''
                   3551:                     );
                   3552:     my %mediafiles = (
                   3553:                       src => '',
                   3554:                       movie => '',
                   3555:                      );
1.648     raeburn  3556:     my $p;
                   3557:     if ($content) {
                   3558:         $p = HTML::LCParser->new($content);
                   3559:     } else {
1.961     raeburn  3560:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3561:     }
1.641     albertel 3562:     while (my $t=$p->get_token()) {
1.640     albertel 3563: 	if ($t->[0] eq 'S') {
                   3564: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3565: 	    push(@state, $tagname);
1.648     raeburn  3566:             if (lc($tagname) eq 'allow') {
                   3567:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3568:             }
1.640     albertel 3569: 	    if (lc($tagname) eq 'img') {
                   3570: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3571: 	    }
1.886     albertel 3572: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3573:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3574:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3575:                 }
1.886     albertel 3576: 	    }
1.645     raeburn  3577:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3578:                 my $src;
1.645     raeburn  3579:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3580:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3581:                 } else {
1.1164    raeburn  3582:                     if ($attr->{'src'} ne '') {
                   3583:                         $src = $attr->{'src'};
                   3584:                         &add_filetype($allfiles,$src,'src');
                   3585:                     }
                   3586:                 }
                   3587:                 my $text = $p->get_trimmed_text();
                   3588:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3589:                     my @swfargs = split(/,/,$1);
                   3590:                     foreach my $item (@swfargs) {
                   3591:                         $item =~ s/["']//g;
                   3592:                         $item =~ s/^\s+//;
                   3593:                         $item =~ s/\s+$//;
                   3594:                     }
                   3595:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3596:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3597:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3598:                         } else {
                   3599:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3600:                         }
                   3601:                     }
1.645     raeburn  3602:                 }
                   3603:             }
                   3604:             if (lc($tagname) eq 'link') {
                   3605:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3606:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3607:                 }
                   3608:             }
1.640     albertel 3609: 	    if (lc($tagname) eq 'object' ||
                   3610: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3611: 		foreach my $item (keys(%javafiles)) {
                   3612: 		    $javafiles{$item} = '';
                   3613: 		}
1.1164    raeburn  3614:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3615:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3616:                 }
1.640     albertel 3617: 	    }
                   3618: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3619: 		my $name = lc($attr->{'name'});
                   3620: 		foreach my $item (keys(%javafiles)) {
                   3621: 		    if ($name eq $item) {
                   3622: 			$javafiles{$item} = $attr->{'value'};
                   3623: 			last;
                   3624: 		    }
                   3625: 		}
1.1164    raeburn  3626:                 my $pathfrom;
1.640     albertel 3627: 		foreach my $item (keys(%mediafiles)) {
                   3628: 		    if ($name eq $item) {
1.1164    raeburn  3629:                         $pathfrom = $attr->{'value'};
                   3630:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3631: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3632: 			last;
                   3633: 		    }
                   3634: 		}
1.1164    raeburn  3635:                 if ($name eq 'flashvars') {
                   3636:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3637:                 }
                   3638:                 if ($pathfrom ne '') {
                   3639:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3640:                                          $pathfrom);
                   3641:                 }
1.640     albertel 3642: 	    }
                   3643: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3644: 		foreach my $item (keys(%javafiles)) {
                   3645: 		    if ($attr->{$item}) {
                   3646: 			$javafiles{$item} = $attr->{$item};
                   3647: 			last;
                   3648: 		    }
                   3649: 		}
                   3650: 		foreach my $item (keys(%mediafiles)) {
                   3651: 		    if ($attr->{$item}) {
                   3652: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3653: 			last;
                   3654: 		    }
                   3655: 		}
1.1164    raeburn  3656:                 if (lc($tagname) eq 'embed') {
                   3657:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3658:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3659:                                              $attr->{'src'});
                   3660:                     }
                   3661:                 }
1.640     albertel 3662: 	    }
1.1243    raeburn  3663:             if (lc($tagname) eq 'iframe') {
                   3664:                 my $src = $attr->{'src'} ;
                   3665:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3666:                     &add_filetype($allfiles,$src,'src');
                   3667:                 } elsif ($src =~ m{^/}) {
                   3668:                     if ($env{'request.course.id'}) {
                   3669:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3670:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3671:                         my $url = &hreflocation('',$fullpath);
                   3672:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3673:                             my $relpath = $1;
                   3674:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3675:                                 &add_filetype($allfiles,$1,'src');
                   3676:                             }
                   3677:                         }
                   3678:                     }
                   3679:                 }
                   3680:             }
1.1164    raeburn  3681:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3682:                 pop(@state);
1.1164    raeburn  3683:             }
1.640     albertel 3684: 	} elsif ($t->[0] eq 'E') {
                   3685: 	    my ($tagname) = ($t->[1]);
                   3686: 	    if ($javafiles{'codebase'} ne '') {
                   3687: 		$javafiles{'codebase'} .= '/';
                   3688: 	    }  
                   3689: 	    if (lc($tagname) eq 'applet' ||
                   3690: 		lc($tagname) eq 'object' ||
                   3691: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3692: 		) {
                   3693: 		foreach my $item (keys(%javafiles)) {
                   3694: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3695: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3696: 			&add_filetype($allfiles,$file,$item);
                   3697: 		    }
                   3698: 		}
                   3699: 	    } 
                   3700: 	    pop @state;
                   3701: 	}
                   3702:     }
1.1164    raeburn  3703:     foreach my $id (sort(keys(%flashvars))) {
                   3704:         if ($shockwave{$id} ne '') {
                   3705:             my @pairs = split(/\&/,$flashvars{$id});
                   3706:             foreach my $pair (@pairs) {
                   3707:                 my ($key,$value) = split(/\=/,$pair);
                   3708:                 if ($key eq 'thumb') {
                   3709:                     &add_filetype($allfiles,$value,$key);
                   3710:                 } elsif ($key eq 'content') {
                   3711:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3712:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3713:                     if ($ext ne '') {
                   3714:                         &add_filetype($allfiles,$path.$value,$ext);
                   3715:                     }
                   3716:                 }
                   3717:             }
                   3718:         }
                   3719:     }
1.637     raeburn  3720:     return 'ok';
                   3721: }
                   3722: 
1.639     albertel 3723: sub add_filetype {
                   3724:     my ($allfiles,$file,$type)=@_;
                   3725:     if (exists($allfiles->{$file})) {
                   3726: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3727: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3728: 	}
                   3729:     } else {
                   3730: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3731:     }
                   3732: }
                   3733: 
1.1164    raeburn  3734: sub embedded_dependency {
                   3735:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3736:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3737:         if (($identifier ne '') &&
                   3738:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3739:             ($pathfrom ne '')) {
                   3740:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3741:             foreach my $dep (@{$related->{$identifier}}) {
                   3742:                 &add_filetype($allfiles,$path.$dep,'object');
                   3743:             }
                   3744:         }
                   3745:     }
                   3746:     return;
                   3747: }
                   3748: 
1.493     albertel 3749: sub removeuploadedurl {
1.984     neumanie 3750:     my ($url)=@_;	
                   3751:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3752:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3753: }
                   3754: 
                   3755: sub removeuserfile {
                   3756:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3757:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3758:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3759:     if ($result eq 'ok') {	
1.798     raeburn  3760:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3761:             my $metafile = $fname.'.meta';
                   3762:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3763: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3764:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3765:             my $sqlresult = 
1.823     albertel 3766:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3767:                                         'portfolio_metadata',$group,
                   3768:                                         'delete');
1.798     raeburn  3769:         }
                   3770:     }
                   3771:     return $result;
1.257     www      3772: }
1.15      www      3773: 
1.530     albertel 3774: sub mkdiruserfile {
                   3775:     my ($docuname,$docudom,$dir)=@_;
                   3776:     my $home=&homeserver($docuname,$docudom);
                   3777:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3778: }
                   3779: 
1.531     albertel 3780: sub renameuserfile {
                   3781:     my ($docuname,$docudom,$old,$new)=@_;
                   3782:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3783:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3784:                         &escape("$old").':'.&escape("$new"),$home);
                   3785:     if ($result eq 'ok') {
                   3786:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3787:             my $oldmeta = $old.'.meta';
                   3788:             my $newmeta = $new.'.meta';
                   3789:             my $metaresult = 
                   3790:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3791: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3792:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3793:             my $sqlresult = 
1.823     albertel 3794:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3795:                                         'portfolio_metadata',$group,
                   3796:                                         'delete');
1.798     raeburn  3797:         }
                   3798:     }
                   3799:     return $result;
1.531     albertel 3800: }
                   3801: 
1.14      www      3802: # ------------------------------------------------------------------------- Log
                   3803: 
                   3804: sub log {
                   3805:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3806:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3807: }
                   3808: 
                   3809: # ------------------------------------------------------------------ Course Log
1.352     www      3810: #
                   3811: # This routine flushes several buffers of non-mission-critical nature
                   3812: #
1.157     www      3813: 
                   3814: sub flushcourselogs {
1.352     www      3815:     &logthis('Flushing log buffers');
                   3816: #
                   3817: # course logs
                   3818: # This is a log of all transactions in a course, which can be used
                   3819: # for data mining purposes
                   3820: #
                   3821: # It also collects the courseid database, which lists last transaction
                   3822: # times and course titles for all courseids
                   3823: #
                   3824:     my %courseidbuffer=();
1.921     raeburn  3825:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3826:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3827: 		          &escape($courselogs{$crsid}),
                   3828: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3829: 	    delete $courselogs{$crsid};
                   3830:         } else {
                   3831:             &logthis('Failed to flush log buffer for '.$crsid);
                   3832:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3833:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3834:                         " exceeded maximum size, deleting.</font>");
                   3835:                delete $courselogs{$crsid};
                   3836:             }
1.352     www      3837:         }
1.920     raeburn  3838:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3839:             'description' => $coursedescrbuf{$crsid},
                   3840:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3841:             'type'        => $coursetypebuf{$crsid},
                   3842:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3843:         };
1.191     harris41 3844:     }
1.352     www      3845: #
                   3846: # Write course id database (reverse lookup) to homeserver of courses 
                   3847: # Is used in pickcourse
                   3848: #
1.840     albertel 3849:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3850:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3851:                                     $courseidbuffer{$crs_home},
                   3852:                                     $crs_home,'timeonly');
1.352     www      3853:     }
                   3854: #
                   3855: # File accesses
                   3856: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3857: #
1.449     matthew  3858:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3859:         if ($entry =~ /___count$/) {
                   3860:             my ($dom,$name);
1.807     albertel 3861:             ($dom,$name,undef)=
1.811     albertel 3862: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3863:             if (! defined($dom) || $dom eq '' || 
                   3864:                 ! defined($name) || $name eq '') {
1.620     albertel 3865:                 my $cid = $env{'request.course.id'};
                   3866:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3867:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3868:             }
1.450     matthew  3869:             my $value = $accesshash{$entry};
                   3870:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3871:             my %temphash=($url => $value);
1.449     matthew  3872:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3873:             if ($result eq 'ok') {
                   3874:                 delete $accesshash{$entry};
                   3875:             }
                   3876:         } else {
1.811     albertel 3877:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3878:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3879:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3880:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3881:                 delete $accesshash{$entry};
                   3882:             }
1.185     www      3883:         }
1.191     harris41 3884:     }
1.352     www      3885: #
                   3886: # Roles
                   3887: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3888: #
1.800     albertel 3889:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3890:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3891: 	    split(/\:/,$entry);
                   3892:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3893:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3894:                 $rudom,$runame) eq 'ok') {
                   3895: 	    delete $userrolehash{$entry};
                   3896:         }
                   3897:     }
1.662     raeburn  3898: #
                   3899: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3900: #
                   3901:     my %domrolebuffer = ();
1.1000    raeburn  3902:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3903:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3904:         if ($domrolebuffer{$rudom}) {
                   3905:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3906:                       '='.&escape($domainrolehash{$entry});
                   3907:         } else {
                   3908:             $domrolebuffer{$rudom}.=&escape($entry).
                   3909:                       '='.&escape($domainrolehash{$entry});
                   3910:         }
                   3911:         delete $domainrolehash{$entry};
                   3912:     }
                   3913:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3914: 	my %servers = &get_servers($dom,'library');
                   3915: 	foreach my $tryserver (keys(%servers)) {
                   3916: 	    unless (&reply('domroleput:'.$dom.':'.
                   3917: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3918: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3919: 	    }
1.662     raeburn  3920:         }
                   3921:     }
1.186     www      3922:     $dumpcount++;
1.157     www      3923: }
                   3924: 
                   3925: sub courselog {
                   3926:     my $what=shift;
1.158     www      3927:     $what=time.':'.$what;
1.620     albertel 3928:     unless ($env{'request.course.id'}) { return ''; }
                   3929:     $coursedombuf{$env{'request.course.id'}}=
                   3930:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3931:     $coursenumbuf{$env{'request.course.id'}}=
                   3932:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3933:     $coursehombuf{$env{'request.course.id'}}=
                   3934:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3935:     $coursedescrbuf{$env{'request.course.id'}}=
                   3936:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3937:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3938:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3939:     $courseownerbuf{$env{'request.course.id'}}=
                   3940:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3941:     $coursetypebuf{$env{'request.course.id'}}=
                   3942:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3943:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3944: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3945:     } else {
1.620     albertel 3946: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3947:     }
1.620     albertel 3948:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3949: 	&flushcourselogs();
                   3950:     }
1.158     www      3951: }
                   3952: 
                   3953: sub courseacclog {
                   3954:     my $fnsymb=shift;
1.620     albertel 3955:     unless ($env{'request.course.id'}) { return ''; }
                   3956:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3957:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3958:         $what.=':POST';
1.583     matthew  3959:         # FIXME: Probably ought to escape things....
1.800     albertel 3960: 	foreach my $key (keys(%env)) {
                   3961:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3962:                 my $formitem = $1;
                   3963:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3964:                     $what.=':'.$formitem.'='.$env{$key};
                   3965:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3966:                     $what.=':'.$formitem.'='.$env{$key};
                   3967:                 }
1.158     www      3968:             }
1.191     harris41 3969:         }
1.583     matthew  3970:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3971:         # FIXME: We should not be depending on a form parameter that someone
                   3972:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3973:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3974:             $what.= ':POST';
                   3975:             # FIXME: Probably ought to escape things....
                   3976:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3977:                                  'crsdiscuss') {
1.620     albertel 3978:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3979:             }
                   3980:         }
1.158     www      3981:     }
                   3982:     &courselog($what);
1.149     www      3983: }
                   3984: 
1.185     www      3985: sub countacc {
                   3986:     my $url=&declutter(shift);
1.458     matthew  3987:     return if (! defined($url) || $url eq '');
1.620     albertel 3988:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3989: #
                   3990: # Mark that this url was used in this course
                   3991: #
1.620     albertel 3992:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3993: #
                   3994: # Increase the access count for this resource in this child process
                   3995: #
1.281     www      3996:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3997:     $accesshash{$key}++;
1.185     www      3998: }
1.349     www      3999: 
1.361     www      4000: sub linklog {
                   4001:     my ($from,$to)=@_;
                   4002:     $from=&declutter($from);
                   4003:     $to=&declutter($to);
                   4004:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4005:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4006: }
1.1160    www      4007: 
                   4008: sub statslog {
                   4009:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4010:     if ($users<2) { return; }
                   4011:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4012:             'course'       => $env{'request.course.id'},
                   4013:             'sections'     => '"all"',
                   4014:             'num_students' => $users,
                   4015:             'part'         => $part,
                   4016:             'symb'         => $symb,
                   4017:             'mean_tries'   => $av_attempts,
                   4018:             'deg_of_diff'  => $degdiff});
                   4019:     foreach my $key (keys(%dynstore)) {
                   4020:         $accesshash{$key}=$dynstore{$key};
                   4021:     }
                   4022: }
1.361     www      4023:   
1.349     www      4024: sub userrolelog {
                   4025:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4026:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4027:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4028:        $userrolehash
                   4029:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4030:                     =$tend.':'.$tstart;
1.662     raeburn  4031:     }
1.1169    droeschl 4032:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4033:        $userrolehash
                   4034:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4035:                     =$tend.':'.$tstart;
                   4036:     }
1.1169    droeschl 4037:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  4038:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4039:        $domainrolehash
                   4040:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4041:                     = $tend.':'.$tstart;
                   4042:     }
1.351     www      4043: }
                   4044: 
1.957     raeburn  4045: sub courserolelog {
                   4046:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4047:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4048:         my $cdom = $1;
                   4049:         my $cnum = $2;
                   4050:         my $sec = $3;
                   4051:         my $namespace = 'rolelog';
                   4052:         my %storehash = (
                   4053:                            role    => $trole,
                   4054:                            start   => $tstart,
                   4055:                            end     => $tend,
                   4056:                            selfenroll => $selfenroll,
                   4057:                            context    => $context,
                   4058:                         );
                   4059:         if ($trole eq 'gr') {
                   4060:             $namespace = 'groupslog';
                   4061:             $storehash{'group'} = $sec;
                   4062:         } else {
                   4063:             $storehash{'section'} = $sec;
                   4064:         }
1.1188    raeburn  4065:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4066:                    $domain,$cnum,$cdom);
1.1184    raeburn  4067:         if (($trole ne 'st') || ($sec ne '')) {
                   4068:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4069:         }
                   4070:     }
                   4071:     return;
                   4072: }
                   4073: 
1.1184    raeburn  4074: sub domainrolelog {
                   4075:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4076:     if ($area =~ m{^/($match_domain)/$}) {
                   4077:         my $cdom = $1;
                   4078:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4079:         my $namespace = 'rolelog';
                   4080:         my %storehash = (
                   4081:                            role    => $trole,
                   4082:                            start   => $tstart,
                   4083:                            end     => $tend,
                   4084:                            context => $context,
                   4085:                         );
1.1188    raeburn  4086:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4087:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4088:     }
                   4089:     return;
                   4090: 
                   4091: }
                   4092: 
                   4093: sub coauthorrolelog {
                   4094:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4095:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4096:         my $audom = $1;
                   4097:         my $auname = $2;
                   4098:         my $namespace = 'rolelog';
                   4099:         my %storehash = (
                   4100:                            role    => $trole,
                   4101:                            start   => $tstart,
                   4102:                            end     => $tend,
                   4103:                            context => $context,
                   4104:                         );
1.1188    raeburn  4105:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4106:                    $domain,$auname,$audom);
1.1184    raeburn  4107:     }
                   4108:     return;
                   4109: }
                   4110: 
1.351     www      4111: sub get_course_adv_roles {
1.948     raeburn  4112:     my ($cid,$codes) = @_;
1.620     albertel 4113:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4114:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4115:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4116:     my %nothide=();
1.800     albertel 4117:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4118:         if ($user !~ /:/) {
                   4119: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4120:         } else {
                   4121:             $nothide{$user}=1;
                   4122:         }
1.470     www      4123:     }
1.1219    raeburn  4124:     my @possdoms = ($coursehash{'domain'});
                   4125:     if ($coursehash{'checkforpriv'}) {
                   4126:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4127:     }
1.351     www      4128:     my %returnhash=();
                   4129:     my %dumphash=
                   4130:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4131:     my $now=time;
1.997     raeburn  4132:     my %privileged;
1.1000    raeburn  4133:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4134: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4135:         if (($tstart) && ($tstart<0)) { next; }
                   4136:         if (($tend) && ($tend<$now)) { next; }
                   4137:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4138:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4139: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4140:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4141:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4142: 	if ($role eq 'cr') { next; }
1.948     raeburn  4143:         if ($codes) {
                   4144:             if ($section) { $role .= ':'.$section; }
                   4145:             if ($returnhash{$role}) {
                   4146:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4147:             } else {
                   4148:                 $returnhash{$role}=$username.':'.$domain;
                   4149:             }
1.351     www      4150:         } else {
1.988     raeburn  4151:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4152:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4153:             if ($returnhash{$key}) {
                   4154: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4155:             } else {
                   4156:                 $returnhash{$key}=$username.':'.$domain;
                   4157:             }
1.351     www      4158:         }
1.948     raeburn  4159:     }
1.400     www      4160:     return %returnhash;
                   4161: }
                   4162: 
                   4163: sub get_my_roles {
1.937     raeburn  4164:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4165:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4166:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4167:     my (%dumphash,%nothide);
1.1086    raeburn  4168:     if ($context eq 'userroles') {
1.1166    raeburn  4169:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4170:     } else {
1.1219    raeburn  4171:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4172:         if ($hidepriv) {
                   4173:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4174:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4175:                 if ($user !~ /:/) {
                   4176:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4177:                 } else {
                   4178:                     $nothide{$user} = 1;
                   4179:                 }
                   4180:             }
                   4181:         }
1.858     raeburn  4182:     }
1.400     www      4183:     my %returnhash=();
                   4184:     my $now=time;
1.999     raeburn  4185:     my %privileged;
1.800     albertel 4186:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4187:         my ($role,$tend,$tstart);
                   4188:         if ($context eq 'userroles') {
1.1149    raeburn  4189:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4190: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4191:         } else {
                   4192:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4193:         }
1.400     www      4194:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4195:         my $status = 'active';
1.939     raeburn  4196:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4197:             $status = 'previous';
                   4198:         } 
                   4199:         if (($tstart) && ($now<$tstart)) {
                   4200:             $status = 'future';
                   4201:         }
                   4202:         if (ref($types) eq 'ARRAY') {
                   4203:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4204:                 next;
                   4205:             } 
                   4206:         } else {
                   4207:             if ($status ne 'active') {
                   4208:                 next;
                   4209:             }
                   4210:         }
1.867     raeburn  4211:         my ($rolecode,$username,$domain,$section,$area);
                   4212:         if ($context eq 'userroles') {
1.1186    raeburn  4213:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4214:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4215:         } else {
                   4216:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4217:         }
1.832     raeburn  4218:         if (ref($roledoms) eq 'ARRAY') {
                   4219:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4220:                 next;
                   4221:             }
                   4222:         }
                   4223:         if (ref($roles) eq 'ARRAY') {
                   4224:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4225:                 if ($role =~ /^cr\//) {
                   4226:                     if (!grep(/^cr$/,@{$roles})) {
                   4227:                         next;
                   4228:                     }
1.1104    raeburn  4229:                 } elsif ($role =~ /^gr\//) {
                   4230:                     if (!grep(/^gr$/,@{$roles})) {
                   4231:                         next;
                   4232:                     }
1.922     raeburn  4233:                 } else {
                   4234:                     next;
                   4235:                 }
1.832     raeburn  4236:             }
1.867     raeburn  4237:         }
1.937     raeburn  4238:         if ($hidepriv) {
1.1219    raeburn  4239:             my @privroles = ('dc','su');
1.999     raeburn  4240:             if ($context eq 'userroles') {
1.1219    raeburn  4241:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4242:             } else {
1.1219    raeburn  4243:                 my $possdoms = [$domain];
                   4244:                 if (ref($roledoms) eq 'ARRAY') {
                   4245:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4246:                 }
1.1219    raeburn  4247:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4248:                     if (!$nothide{$username.':'.$domain}) {
                   4249:                         next;
                   4250:                     }
                   4251:                 }
1.937     raeburn  4252:             }
                   4253:         }
1.933     raeburn  4254:         if ($withsec) {
                   4255:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4256:                 $tstart.':'.$tend;
                   4257:         } else {
                   4258:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4259:         }
1.832     raeburn  4260:     }
1.373     www      4261:     return %returnhash;
1.399     www      4262: }
                   4263: 
                   4264: # ----------------------------------------------------- Frontpage Announcements
                   4265: #
                   4266: #
                   4267: 
                   4268: sub postannounce {
                   4269:     my ($server,$text)=@_;
1.844     albertel 4270:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4271:     unless ($text=~/\w/) { $text=''; }
                   4272:     return &reply('setannounce:'.&escape($text),$server);
                   4273: }
                   4274: 
                   4275: sub getannounce {
1.448     albertel 4276: 
                   4277:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4278: 	my $announcement='';
1.800     albertel 4279: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4280: 	close($fh);
1.399     www      4281: 	if ($announcement=~/\w/) { 
                   4282: 	    return 
                   4283:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4284:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4285: 	} else {
                   4286: 	    return '';
                   4287: 	}
                   4288:     } else {
                   4289: 	return '';
                   4290:     }
1.351     www      4291: }
1.353     www      4292: 
                   4293: # ---------------------------------------------------------- Course ID routines
                   4294: # Deal with domain's nohist_courseid.db files
                   4295: #
                   4296: 
                   4297: sub courseidput {
1.921     raeburn  4298:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4299:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4300:     my $outcome;
                   4301:     if ($caller eq 'timeonly') {
                   4302:         my $cids = '';
                   4303:         foreach my $item (keys(%$storehash)) {
                   4304:             $cids.=&escape($item).'&';
                   4305:         }
                   4306:         $cids=~s/\&$//;
                   4307:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4308:                           $coursehome);       
                   4309:     } else {
                   4310:         my $items = '';
                   4311:         foreach my $item (keys(%$storehash)) {
                   4312:             $items.= &escape($item).'='.
                   4313:                      &freeze_escape($$storehash{$item}).'&';
                   4314:         }
                   4315:         $items=~s/\&$//;
                   4316:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4317:                           $coursehome);
1.918     raeburn  4318:     }
                   4319:     if ($outcome eq 'unknown_cmd') {
                   4320:         my $what;
                   4321:         foreach my $cid (keys(%$storehash)) {
                   4322:             $what .= &escape($cid).'=';
1.921     raeburn  4323:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4324:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4325:             }
                   4326:             $what =~ s/\:$/&/;
                   4327:         }
                   4328:         $what =~ s/\&$//;  
                   4329:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4330:     } else {
                   4331:         return $outcome;
                   4332:     }
1.353     www      4333: }
                   4334: 
                   4335: sub courseiddump {
1.921     raeburn  4336:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4337:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4338:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4339:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4340:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4341:     my $as_hash = 1;
                   4342:     my %returnhash;
                   4343:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4344:     my %libserv = &all_library();
                   4345:     foreach my $tryserver (keys(%libserv)) {
                   4346:         if ( (  $hostidflag == 1 
                   4347: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4348: 	     || (!defined($hostidflag)) ) {
                   4349: 
1.918     raeburn  4350: 	    if (($domfilter eq '') ||
                   4351: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4352:                 my $rep;
                   4353:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4354:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4355:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4356:                                 &escape($descfilter), &escape($instcodefilter), 
                   4357:                                 &escape($ownerfilter), &escape($coursefilter),
                   4358:                                 &escape($typefilter), &escape($regexp_ok), 
                   4359:                                 $as_hash, &escape($selfenrollonly), 
                   4360:                                 &escape($catfilter), $showhidden, $caller, 
                   4361:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4362:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  4363:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4364:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 4365:                 } else {
                   4366:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4367:                              $sincefilter.':'.&escape($descfilter).':'.
                   4368:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4369:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4370:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4371:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4372:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4373:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4374:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  4375:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4376:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 4377:                 }
                   4378:                      
1.918     raeburn  4379:                 my @pairs=split(/\&/,$rep);
                   4380:                 foreach my $item (@pairs) {
                   4381:                     my ($key,$value)=split(/\=/,$item,2);
                   4382:                     $key = &unescape($key);
                   4383:                     next if ($key =~ /^error: 2 /);
                   4384:                     my $result = &thaw_unescape($value);
                   4385:                     if (ref($result) eq 'HASH') {
                   4386:                         $returnhash{$key}=$result;
                   4387:                     } else {
1.921     raeburn  4388:                         my @responses = split(/:/,$value);
                   4389:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4390:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4391:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4392:                         }
1.1008    raeburn  4393:                     }
1.353     www      4394:                 }
                   4395:             }
                   4396:         }
                   4397:     }
                   4398:     return %returnhash;
                   4399: }
                   4400: 
1.1055    raeburn  4401: sub courselastaccess {
                   4402:     my ($cdom,$cnum,$hostidref) = @_;
                   4403:     my %returnhash;
                   4404:     if ($cdom && $cnum) {
                   4405:         my $chome = &homeserver($cnum,$cdom);
                   4406:         if ($chome ne 'no_host') {
                   4407:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4408:             &extract_lastaccess(\%returnhash,$rep);
                   4409:         }
                   4410:     } else {
                   4411:         if (!$cdom) { $cdom=''; }
                   4412:         my %libserv = &all_library();
                   4413:         foreach my $tryserver (keys(%libserv)) {
                   4414:             if (ref($hostidref) eq 'ARRAY') {
                   4415:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4416:             } 
                   4417:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4418:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4419:                 &extract_lastaccess(\%returnhash,$rep);
                   4420:             }
                   4421:         }
                   4422:     }
                   4423:     return %returnhash;
                   4424: }
                   4425: 
                   4426: sub extract_lastaccess {
                   4427:     my ($returnhash,$rep) = @_;
                   4428:     if (ref($returnhash) eq 'HASH') {
                   4429:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4430:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4431:                  $rep eq '') {
                   4432:             my @pairs=split(/\&/,$rep);
                   4433:             foreach my $item (@pairs) {
                   4434:                 my ($key,$value)=split(/\=/,$item,2);
                   4435:                 $key = &unescape($key);
                   4436:                 next if ($key =~ /^error: 2 /);
                   4437:                 $returnhash->{$key} = &thaw_unescape($value);
                   4438:             }
                   4439:         }
                   4440:     }
                   4441:     return;
                   4442: }
                   4443: 
1.658     raeburn  4444: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4445: 
                   4446: sub dcmailput {
1.685     raeburn  4447:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4448:     my $status = &Apache::lonnet::critical(
1.740     www      4449:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4450:        &escape($message),$server);
1.662     raeburn  4451:     return $status;
                   4452: }
                   4453: 
1.658     raeburn  4454: sub dcmaildump {
                   4455:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4456:     my %returnhash=();
1.846     albertel 4457: 
                   4458:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4459:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4460:                                                          &escape($enddate).':';
                   4461: 	my @esc_senders=map { &escape($_)} @$senders;
                   4462: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4463: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4464:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4465:             if (($key) && ($value)) {
                   4466:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4467:             }
                   4468:         }
                   4469:     }
                   4470:     return %returnhash;
                   4471: }
1.662     raeburn  4472: # ---------------------------------------------------------- Domain roles
                   4473: 
                   4474: sub get_domain_roles {
                   4475:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4476:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4477:         $startdate = '.';
                   4478:     }
1.1018    raeburn  4479:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4480:         $enddate = '.';
                   4481:     }
1.922     raeburn  4482:     my $rolelist;
                   4483:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4484:         $rolelist = join('&',@{$roles});
1.922     raeburn  4485:     }
1.662     raeburn  4486:     my %personnel = ();
1.841     albertel 4487: 
                   4488:     my %servers = &get_servers($dom,'library');
                   4489:     foreach my $tryserver (keys(%servers)) {
                   4490: 	%{$personnel{$tryserver}}=();
                   4491: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4492: 					    &escape($startdate).':'.
                   4493: 					    &escape($enddate).':'.
                   4494: 					    &escape($rolelist), $tryserver))) {
                   4495: 	    my ($key,$value) = split(/\=/,$line,2);
                   4496: 	    if (($key) && ($value)) {
                   4497: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4498: 	    }
                   4499: 	}
1.662     raeburn  4500:     }
                   4501:     return %personnel;
                   4502: }
1.658     raeburn  4503: 
1.1057    www      4504: # ----------------------------------------------------------- Interval timing 
1.149     www      4505: 
1.1153    www      4506: {
                   4507: # Caches needed for speedup of navmaps
                   4508: # We don't want to cache this for very long at all (5 seconds at most)
                   4509: # 
                   4510: # The user for whom we cache
                   4511: my $cachedkey='';
                   4512: # The cached times for this user
                   4513: my %cachedtimes=();
                   4514: # When this was last done
1.1282    raeburn  4515: my $cachedtime='';
1.1153    www      4516: 
                   4517: sub load_all_first_access {
1.1154    raeburn  4518:     my ($uname,$udom)=@_;
1.1156    www      4519:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4520:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4521:         return;
                   4522:     }
                   4523:     $cachedtime=time;
                   4524:     $cachedkey=$uname.':'.$udom;
                   4525:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4526: }
                   4527: 
1.504     albertel 4528: sub get_first_access {
1.1162    raeburn  4529:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4530:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4531:     if ($argsymb) { $symb=$argsymb; }
                   4532:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4533:     if ($argmap) { $map = $argmap; }
1.926     albertel 4534:     if ($type eq 'course') {
                   4535: 	$res='course';
                   4536:     } elsif ($type eq 'map') {
1.588     albertel 4537: 	$res=&symbread($map);
                   4538:     } else {
                   4539: 	$res=$symb;
                   4540:     }
1.1153    www      4541:     &load_all_first_access($uname,$udom);
                   4542:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4543: }
                   4544: 
                   4545: sub set_first_access {
1.1162    raeburn  4546:     my ($type,$interval)=@_;
1.790     albertel 4547:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4548:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4549:     if ($type eq 'course') {
                   4550: 	$res='course';
                   4551:     } elsif ($type eq 'map') {
1.588     albertel 4552: 	$res=&symbread($map);
                   4553:     } else {
                   4554: 	$res=$symb;
                   4555:     }
1.1153    www      4556:     $cachedkey='';
1.1162    raeburn  4557:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4558:     if (!$firstaccess) {
1.1162    raeburn  4559:         my $start = time;
                   4560: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4561:                           $udom,$uname);
                   4562:         if ($putres eq 'ok') {
                   4563:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4564:                  $udom,$uname); 
                   4565:             &appenv(
                   4566:                      {
                   4567:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4568:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4569:                      }
                   4570:                   );
                   4571:         }
                   4572:         return $putres;
1.505     albertel 4573:     }
                   4574:     return 'already_set';
1.504     albertel 4575: }
1.1153    www      4576: }
1.1282    raeburn  4577: 
1.110     www      4578: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4579: 
                   4580: sub expirespread {
                   4581:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4582:     my $cid=$env{'request.course.id'}; 
1.110     www      4583:     if ($cid) {
                   4584:        my $now=time;
                   4585:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4586:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4587:                             $env{'course.'.$cid.'.num'}.
1.110     www      4588: 	        	    ':nohist_expirationdates:'.
                   4589:                             &escape($key).'='.$now,
1.620     albertel 4590:                             $env{'course.'.$cid.'.home'})
1.110     www      4591:     }
                   4592:     return 'ok';
1.14      www      4593: }
                   4594: 
1.109     www      4595: # ----------------------------------------------------- Devalidate Spreadsheets
                   4596: 
                   4597: sub devalidate {
1.325     www      4598:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4599:     my $cid=$env{'request.course.id'}; 
1.109     www      4600:     if ($cid) {
1.391     matthew  4601:         # delete the stored spreadsheets for
                   4602:         # - the student level sheet of this user in course's homespace
                   4603:         # - the assessment level sheet for this resource 
                   4604:         #   for this user in user's homespace
1.553     albertel 4605: 	# - current conditional state info
1.325     www      4606: 	my $key=$uname.':'.$udom.':';
1.109     www      4607:         my $status=
1.299     matthew  4608: 	    &del('nohist_calculatedsheets',
1.391     matthew  4609: 		 [$key.'studentcalc:'],
1.620     albertel 4610: 		 $env{'course.'.$cid.'.domain'},
                   4611: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4612: 		.' '.
                   4613: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4614: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4615:         unless ($status eq 'ok ok') {
                   4616:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4617:                     $uname.' at '.$udom.' for '.
1.109     www      4618: 		    $symb.': '.$status);
1.133     albertel 4619:         }
1.553     albertel 4620: 	&delenv('user.state.'.$cid);
1.109     www      4621:     }
                   4622: }
                   4623: 
1.265     albertel 4624: sub get_scalar {
                   4625:     my ($string,$end) = @_;
                   4626:     my $value;
                   4627:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4628: 	$value = $1;
                   4629:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4630: 	$value = $1;
                   4631:     }
                   4632:     return &unescape($value);
                   4633: }
                   4634: 
                   4635: sub array2str {
                   4636:   my (@array) = @_;
                   4637:   my $result=&arrayref2str(\@array);
                   4638:   $result=~s/^__ARRAY_REF__//;
                   4639:   $result=~s/__END_ARRAY_REF__$//;
                   4640:   return $result;
                   4641: }
                   4642: 
1.204     albertel 4643: sub arrayref2str {
                   4644:   my ($arrayref) = @_;
1.265     albertel 4645:   my $result='__ARRAY_REF__';
1.204     albertel 4646:   foreach my $elem (@$arrayref) {
1.265     albertel 4647:     if(ref($elem) eq 'ARRAY') {
                   4648:       $result.=&arrayref2str($elem).'&';
                   4649:     } elsif(ref($elem) eq 'HASH') {
                   4650:       $result.=&hashref2str($elem).'&';
                   4651:     } elsif(ref($elem)) {
                   4652:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4653:     } else {
                   4654:       $result.=&escape($elem).'&';
                   4655:     }
                   4656:   }
                   4657:   $result=~s/\&$//;
1.265     albertel 4658:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4659:   return $result;
                   4660: }
                   4661: 
1.168     albertel 4662: sub hash2str {
1.204     albertel 4663:   my (%hash) = @_;
                   4664:   my $result=&hashref2str(\%hash);
1.265     albertel 4665:   $result=~s/^__HASH_REF__//;
                   4666:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4667:   return $result;
                   4668: }
                   4669: 
                   4670: sub hashref2str {
                   4671:   my ($hashref)=@_;
1.265     albertel 4672:   my $result='__HASH_REF__';
1.800     albertel 4673:   foreach my $key (sort(keys(%$hashref))) {
                   4674:     if (ref($key) eq 'ARRAY') {
                   4675:       $result.=&arrayref2str($key).'=';
                   4676:     } elsif (ref($key) eq 'HASH') {
                   4677:       $result.=&hashref2str($key).'=';
                   4678:     } elsif (ref($key)) {
1.265     albertel 4679:       $result.='=';
1.800     albertel 4680:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4681:     } else {
1.1132    raeburn  4682: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4683:     }
                   4684: 
1.800     albertel 4685:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4686:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4687:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4688:       $result.=&hashref2str($hashref->{$key}).'&';
                   4689:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4690:        $result.='&';
1.800     albertel 4691:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4692:     } else {
1.800     albertel 4693:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4694:     }
                   4695:   }
1.168     albertel 4696:   $result=~s/\&$//;
1.265     albertel 4697:   $result .= '__END_HASH_REF__';
1.168     albertel 4698:   return $result;
                   4699: }
                   4700: 
                   4701: sub str2hash {
1.265     albertel 4702:     my ($string)=@_;
                   4703:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4704:     return %$hash;
                   4705: }
                   4706: 
                   4707: sub str2hashref {
1.168     albertel 4708:   my ($string) = @_;
1.265     albertel 4709: 
                   4710:   my %hash;
                   4711: 
                   4712:   if($string !~ /^__HASH_REF__/) {
                   4713:       if (! ($string eq '' || !defined($string))) {
                   4714: 	  $hash{'error'}='Not hash reference';
                   4715:       }
                   4716:       return (\%hash, $string);
                   4717:   }
                   4718: 
                   4719:   $string =~ s/^__HASH_REF__//;
                   4720: 
                   4721:   while($string !~ /^__END_HASH_REF__/) {
                   4722:       #key
                   4723:       my $key='';
                   4724:       if($string =~ /^__HASH_REF__/) {
                   4725:           ($key, $string)=&str2hashref($string);
                   4726:           if(defined($key->{'error'})) {
                   4727:               $hash{'error'}='Bad data';
                   4728:               return (\%hash, $string);
                   4729:           }
                   4730:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4731:           ($key, $string)=&str2arrayref($string);
                   4732:           if($key->[0] eq 'Array reference error') {
                   4733:               $hash{'error'}='Bad data';
                   4734:               return (\%hash, $string);
                   4735:           }
                   4736:       } else {
                   4737:           $string =~ s/^(.*?)=//;
1.267     albertel 4738: 	  $key=&unescape($1);
1.265     albertel 4739:       }
                   4740:       $string =~ s/^=//;
                   4741: 
                   4742:       #value
                   4743:       my $value='';
                   4744:       if($string =~ /^__HASH_REF__/) {
                   4745:           ($value, $string)=&str2hashref($string);
                   4746:           if(defined($value->{'error'})) {
                   4747:               $hash{'error'}='Bad data';
                   4748:               return (\%hash, $string);
                   4749:           }
                   4750:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4751:           ($value, $string)=&str2arrayref($string);
                   4752:           if($value->[0] eq 'Array reference error') {
                   4753:               $hash{'error'}='Bad data';
                   4754:               return (\%hash, $string);
                   4755:           }
                   4756:       } else {
                   4757: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4758:       }
                   4759:       $string =~ s/^&//;
                   4760: 
                   4761:       $hash{$key}=$value;
1.204     albertel 4762:   }
1.265     albertel 4763: 
                   4764:   $string =~ s/^__END_HASH_REF__//;
                   4765: 
                   4766:   return (\%hash, $string);
1.204     albertel 4767: }
                   4768: 
                   4769: sub str2array {
1.265     albertel 4770:     my ($string)=@_;
                   4771:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4772:     return @$array;
                   4773: }
                   4774: 
                   4775: sub str2arrayref {
1.204     albertel 4776:   my ($string) = @_;
1.265     albertel 4777:   my @array;
                   4778: 
                   4779:   if($string !~ /^__ARRAY_REF__/) {
                   4780:       if (! ($string eq '' || !defined($string))) {
                   4781: 	  $array[0]='Array reference error';
                   4782:       }
                   4783:       return (\@array, $string);
                   4784:   }
                   4785: 
                   4786:   $string =~ s/^__ARRAY_REF__//;
                   4787: 
                   4788:   while($string !~ /^__END_ARRAY_REF__/) {
                   4789:       my $value='';
                   4790:       if($string =~ /^__HASH_REF__/) {
                   4791:           ($value, $string)=&str2hashref($string);
                   4792:           if(defined($value->{'error'})) {
                   4793:               $array[0] ='Array reference error';
                   4794:               return (\@array, $string);
                   4795:           }
                   4796:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4797:           ($value, $string)=&str2arrayref($string);
                   4798:           if($value->[0] eq 'Array reference error') {
                   4799:               $array[0] ='Array reference error';
                   4800:               return (\@array, $string);
                   4801:           }
                   4802:       } else {
                   4803: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4804:       }
                   4805:       $string =~ s/^&//;
                   4806: 
                   4807:       push(@array, $value);
1.191     harris41 4808:   }
1.265     albertel 4809: 
                   4810:   $string =~ s/^__END_ARRAY_REF__//;
                   4811: 
                   4812:   return (\@array, $string);
1.168     albertel 4813: }
                   4814: 
1.167     albertel 4815: # -------------------------------------------------------------------Temp Store
                   4816: 
1.168     albertel 4817: sub tmpreset {
                   4818:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4819:   if (!$symb) {
                   4820:     $symb=&symbread();
1.620     albertel 4821:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4822:   }
                   4823:   $symb=escape($symb);
                   4824: 
1.620     albertel 4825:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4826:   $namespace=~s/\//\_/g;
                   4827:   $namespace=~s/\W//g;
                   4828: 
1.620     albertel 4829:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4830:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4831:   if ($domain eq 'public' && $stuname eq 'public') {
                   4832:       $stuname=$ENV{'REMOTE_ADDR'};
                   4833:   }
1.1117    foxr     4834:   my $path=LONCAPA::tempdir();
1.168     albertel 4835:   my %hash;
                   4836:   if (tie(%hash,'GDBM_File',
                   4837: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4838: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4839:     foreach my $key (keys(%hash)) {
1.180     albertel 4840:       if ($key=~ /:$symb/) {
1.168     albertel 4841: 	delete($hash{$key});
                   4842:       }
                   4843:     }
                   4844:   }
                   4845: }
                   4846: 
1.167     albertel 4847: sub tmpstore {
1.168     albertel 4848:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4849: 
                   4850:   if (!$symb) {
                   4851:     $symb=&symbread();
1.620     albertel 4852:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4853:   }
                   4854:   $symb=escape($symb);
                   4855: 
                   4856:   if (!$namespace) {
                   4857:     # I don't think we would ever want to store this for a course.
                   4858:     # it seems this will only be used if we don't have a course.
1.620     albertel 4859:     #$namespace=$env{'request.course.id'};
1.168     albertel 4860:     #if (!$namespace) {
1.620     albertel 4861:       $namespace=$env{'request.state'};
1.168     albertel 4862:     #}
                   4863:   }
                   4864:   $namespace=~s/\//\_/g;
                   4865:   $namespace=~s/\W//g;
1.620     albertel 4866:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4867:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4868:   if ($domain eq 'public' && $stuname eq 'public') {
                   4869:       $stuname=$ENV{'REMOTE_ADDR'};
                   4870:   }
1.168     albertel 4871:   my $now=time;
                   4872:   my %hash;
1.1117    foxr     4873:   my $path=LONCAPA::tempdir();
1.168     albertel 4874:   if (tie(%hash,'GDBM_File',
                   4875: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4876: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4877:     $hash{"version:$symb"}++;
                   4878:     my $version=$hash{"version:$symb"};
                   4879:     my $allkeys=''; 
                   4880:     foreach my $key (keys(%$storehash)) {
                   4881:       $allkeys.=$key.':';
1.591     albertel 4882:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4883:     }
                   4884:     $hash{"$version:$symb:timestamp"}=$now;
                   4885:     $allkeys.='timestamp';
                   4886:     $hash{"$version:keys:$symb"}=$allkeys;
                   4887:     if (untie(%hash)) {
                   4888:       return 'ok';
                   4889:     } else {
                   4890:       return "error:$!";
                   4891:     }
                   4892:   } else {
                   4893:     return "error:$!";
                   4894:   }
                   4895: }
1.167     albertel 4896: 
1.168     albertel 4897: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4898: 
1.168     albertel 4899: sub tmprestore {
                   4900:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4901: 
1.168     albertel 4902:   if (!$symb) {
                   4903:     $symb=&symbread();
1.620     albertel 4904:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4905:   }
                   4906:   $symb=escape($symb);
                   4907: 
1.620     albertel 4908:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4909: 
1.620     albertel 4910:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4911:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4912:   if ($domain eq 'public' && $stuname eq 'public') {
                   4913:       $stuname=$ENV{'REMOTE_ADDR'};
                   4914:   }
1.168     albertel 4915:   my %returnhash;
                   4916:   $namespace=~s/\//\_/g;
                   4917:   $namespace=~s/\W//g;
                   4918:   my %hash;
1.1117    foxr     4919:   my $path=LONCAPA::tempdir();
1.168     albertel 4920:   if (tie(%hash,'GDBM_File',
                   4921: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4922: 	  &GDBM_READER(),0640)) {
1.168     albertel 4923:     my $version=$hash{"version:$symb"};
                   4924:     $returnhash{'version'}=$version;
                   4925:     my $scope;
                   4926:     for ($scope=1;$scope<=$version;$scope++) {
                   4927:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4928:       my @keys=split(/:/,$vkeys);
                   4929:       my $key;
                   4930:       $returnhash{"$scope:keys"}=$vkeys;
                   4931:       foreach $key (@keys) {
1.591     albertel 4932: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4933: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4934:       }
                   4935:     }
1.168     albertel 4936:     if (!(untie(%hash))) {
                   4937:       return "error:$!";
                   4938:     }
                   4939:   } else {
                   4940:     return "error:$!";
                   4941:   }
                   4942:   return %returnhash;
1.167     albertel 4943: }
                   4944: 
1.9       www      4945: # ----------------------------------------------------------------------- Store
                   4946: 
                   4947: sub store {
1.1269    raeburn  4948:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      4949:     my $home='';
                   4950: 
1.168     albertel 4951:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4952: 
1.213     www      4953:     $symb=&symbclean($symb);
1.122     albertel 4954:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4955: 
1.620     albertel 4956:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4957:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4958: 
                   4959:     &devalidate($symb,$stuname,$domain);
1.109     www      4960: 
                   4961:     $symb=escape($symb);
1.187     www      4962:     if (!$namespace) { 
1.620     albertel 4963:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4964:           return ''; 
                   4965:        } 
                   4966:     }
1.620     albertel 4967:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4968: 
                   4969:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4970:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4971: 
1.12      www      4972:     my $namevalue='';
1.800     albertel 4973:     foreach my $key (keys(%$storehash)) {
                   4974:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4975:     }
1.12      www      4976:     $namevalue=~s/\&$//;
1.187     www      4977:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  4978:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      4979: }
                   4980: 
1.47      www      4981: # -------------------------------------------------------------- Critical Store
                   4982: 
                   4983: sub cstore {
1.1269    raeburn  4984:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      4985:     my $home='';
                   4986: 
1.168     albertel 4987:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4988: 
1.213     www      4989:     $symb=&symbclean($symb);
1.122     albertel 4990:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4991: 
1.620     albertel 4992:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4993:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4994: 
                   4995:     &devalidate($symb,$stuname,$domain);
1.109     www      4996: 
                   4997:     $symb=escape($symb);
1.187     www      4998:     if (!$namespace) { 
1.620     albertel 4999:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5000:           return ''; 
                   5001:        } 
                   5002:     }
1.620     albertel 5003:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5004: 
                   5005:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5006:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5007: 
1.47      www      5008:     my $namevalue='';
1.800     albertel 5009:     foreach my $key (keys(%$storehash)) {
                   5010:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5011:     }
1.47      www      5012:     $namevalue=~s/\&$//;
1.187     www      5013:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5014:     return critical
1.1269    raeburn  5015:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5016: }
                   5017: 
1.9       www      5018: # --------------------------------------------------------------------- Restore
                   5019: 
                   5020: sub restore {
1.124     www      5021:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5022:     my $home='';
                   5023: 
1.168     albertel 5024:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5025: 
1.122     albertel 5026:     if (!$symb) {
1.1224    raeburn  5027:         return if ($namespace eq 'courserequests');
                   5028:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5029:     } else {
1.1224    raeburn  5030:         unless ($namespace eq 'courserequests') {
                   5031:             $symb=&escape(&symbclean($symb));
                   5032:         }
1.122     albertel 5033:     }
1.188     www      5034:     if (!$namespace) { 
1.620     albertel 5035:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5036:           return ''; 
                   5037:        } 
                   5038:     }
1.620     albertel 5039:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5040:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5041:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5042:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5043: 
1.12      www      5044:     my %returnhash=();
1.800     albertel 5045:     foreach my $line (split(/\&/,$answer)) {
                   5046: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5047:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5048:     }
1.75      www      5049:     my $version;
                   5050:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5051:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5052:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5053:        }
1.75      www      5054:     }
1.13      www      5055:     return %returnhash;
1.34      www      5056: }
                   5057: 
                   5058: # ---------------------------------------------------------- Course Description
1.1118    foxr     5059: #
                   5060: #  
1.34      www      5061: 
                   5062: sub coursedescription {
1.731     albertel 5063:     my ($courseid,$args)=@_;
1.34      www      5064:     $courseid=~s/^\///;
1.49      www      5065:     $courseid=~s/\_/\//g;
1.34      www      5066:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5067:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5068:     my $normalid=$cdomain.'_'.$cnum;
                   5069:     # need to always cache even if we get errors otherwise we keep 
                   5070:     # trying and trying and trying to get the course description.
                   5071:     my %envhash=();
                   5072:     my %returnhash=();
1.731     albertel 5073:     
                   5074:     my $expiretime=600;
                   5075:     if ($env{'request.course.id'} eq $normalid) {
                   5076: 	$expiretime=120;
                   5077:     }
                   5078: 
                   5079:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5080:     if (!$args->{'freshen_cache'}
                   5081: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5082: 	foreach my $key (keys(%env)) {
                   5083: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5084: 	    my ($setting) = $1;
                   5085: 	    $returnhash{$setting} = $env{$key};
                   5086: 	}
                   5087: 	return %returnhash;
                   5088:     }
                   5089: 
1.1118    foxr     5090:     # get the data again
                   5091: 
1.731     albertel 5092:     if (!$args->{'one_time'}) {
                   5093: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5094:     }
1.811     albertel 5095: 
1.34      www      5096:     if ($chome ne 'no_host') {
1.302     albertel 5097:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5098:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5099: 	   my $username = $env{'user.name'}; # Defult username
                   5100: 	   if(defined $args->{'user'}) {
                   5101: 	       $username = $args->{'user'};
                   5102: 	   }
1.129     albertel 5103:            $returnhash{'home'}= $chome;
                   5104: 	   $returnhash{'domain'} = $cdomain;
                   5105: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5106:            if (!defined($returnhash{'type'})) {
                   5107:                $returnhash{'type'} = 'Course';
                   5108:            }
1.130     albertel 5109:            while (my ($name,$value) = each %returnhash) {
1.53      www      5110:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5111:            }
1.270     www      5112:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5113:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5114: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5115:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5116:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5117:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5118:        }
                   5119:     }
1.731     albertel 5120:     if (!$args->{'one_time'}) {
1.949     raeburn  5121: 	&appenv(\%envhash);
1.731     albertel 5122:     }
1.302     albertel 5123:     return %returnhash;
1.461     www      5124: }
                   5125: 
1.1080    raeburn  5126: sub update_released_required {
                   5127:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5128:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5129:         $cid = $env{'request.course.id'};
                   5130:         $cdom = $env{'course.'.$cid.'.domain'};
                   5131:         $cnum = $env{'course.'.$cid.'.num'};
                   5132:         $chome = $env{'course.'.$cid.'.home'};
                   5133:     }
                   5134:     if ($needsrelease) {
                   5135:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5136:         my $needsupdate;
                   5137:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5138:             $needsupdate = 1;
                   5139:         } else {
                   5140:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5141:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5142:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5143:                 $needsupdate = 1;
                   5144:             }
                   5145:         }
                   5146:         if ($needsupdate) {
                   5147:             my %needshash = (
                   5148:                              'internal.releaserequired' => $needsrelease,
                   5149:                             );
                   5150:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5151:             if ($putresult eq 'ok') {
                   5152:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5153:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5154:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5155:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5156:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5157:                 }
                   5158:             }
                   5159:         }
                   5160:     }
                   5161:     return;
                   5162: }
                   5163: 
1.461     www      5164: # -------------------------------------------------See if a user is privileged
                   5165: 
                   5166: sub privileged {
1.1219    raeburn  5167:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5168:     my $now = time;
1.1219    raeburn  5169:     my $roles;
                   5170:     if (ref($possroles) eq 'ARRAY') {
                   5171:         $roles = $possroles; 
                   5172:     } else {
                   5173:         $roles = ['dc','su'];
                   5174:     }
                   5175:     if (ref($possdomains) eq 'ARRAY') {
                   5176:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5177:         foreach my $dom (@{$possdomains}) {
                   5178:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5179:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5180:                 foreach my $role (@{$roles}) {
                   5181:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5182:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5183:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5184:                             return 1 unless (($end && $end < $now) ||
                   5185:                                              ($start && $start > $now));
                   5186:                         }
                   5187:                     }
                   5188:                 }
                   5189:             }
                   5190:         }
                   5191:     } else {
                   5192:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5193:         my $now = time;
1.1170    droeschl 5194: 
1.1275    musolffc 5195:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5196:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5197:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5198:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5199:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5200:             }
1.1219    raeburn  5201:         }
                   5202:     }
                   5203:     return 0;
                   5204: }
1.1170    droeschl 5205: 
1.1219    raeburn  5206: sub privileged_by_domain {
                   5207:     my ($domains,$roles) = @_;
                   5208:     my %privileged = ();
                   5209:     my $cachetime = 60*60*24;
                   5210:     my $now = time;
                   5211:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5212:         return %privileged;
                   5213:     }
                   5214:     foreach my $dom (@{$domains}) {
                   5215:         next if (ref($privileged{$dom}) eq 'HASH');
                   5216:         my $needroles;
                   5217:         foreach my $role (@{$roles}) {
                   5218:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5219:             if (defined($cached)) {
                   5220:                 if (ref($result) eq 'HASH') {
                   5221:                     $privileged{$dom}{$role} = $result;
                   5222:                 }
                   5223:             } else {
                   5224:                 $needroles = 1;
                   5225:             }
                   5226:         }
                   5227:         if ($needroles) {
                   5228:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5229:             $privileged{$dom} = {};
                   5230:             foreach my $server (keys(%dompersonnel)) {
                   5231:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5232:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5233:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5234:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5235:                         next if ($end && $end < $now);
                   5236:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5237:                             $dompersonnel{$server}{$item};
                   5238:                     }
                   5239:                 }
                   5240:             }
                   5241:             if (ref($privileged{$dom}) eq 'HASH') {
                   5242:                 foreach my $role (@{$roles}) {
                   5243:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5244:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5245:                     } else {
                   5246:                         my %hash = ();
                   5247:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5248:                     }
                   5249:                 }
                   5250:             }
                   5251:         }
                   5252:     }
                   5253:     return %privileged;
1.9       www      5254: }
1.1       albertel 5255: 
1.103     harris41 5256: # -------------------------------------------------------- Get user privileges
1.11      www      5257: 
                   5258: sub rolesinit {
1.1169    droeschl 5259:     my ($domain, $username) = @_;
                   5260:     my %userroles = ('user.login.time' => time);
                   5261:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5262: 
                   5263:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5264:     # also, blocking can be triggered by an activating timer
                   5265:     # it's saved in the user's %env.
                   5266:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5267:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5268:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5269:         %timerintchk, %timerintenv);
                   5270: 
1.1162    raeburn  5271:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5272:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5273:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5274:     }
1.1169    droeschl 5275: 
1.1162    raeburn  5276:     foreach my $key (keys(%timerinterval)) {
                   5277:         my ($cid,$rest) = split(/\0/,$key);
                   5278:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5279:     }
1.1169    droeschl 5280: 
1.11      www      5281:     my %allroles=();
1.1162    raeburn  5282:     my %allgroups=();
1.11      www      5283: 
1.1274    raeburn  5284:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5285:         my $role = $rolesdump{$area};
                   5286:         $area =~ s/\_\w\w$//;
                   5287: 
                   5288:         my ($trole, $tend, $tstart, $group_privs);
                   5289: 
                   5290:         if ($role =~ /^cr/) {
                   5291:         # Custom role, defined by a user 
                   5292:         # e.g., user.role.cr/msu/smith/mynewrole
                   5293:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5294:                 $trole = $1;
                   5295:                 ($tend, $tstart) = split('_', $2);
                   5296:             } else {
                   5297:                 $trole = $role;
                   5298:             }
                   5299:         } elsif ($role =~ m|^gr/|) {
                   5300:         # Role of member in a group, defined within a course/community
                   5301:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5302:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5303:             next if $tstart eq '-1';
                   5304:             ($trole, $group_privs) = split(/\//, $trole);
                   5305:             $group_privs = &unescape($group_privs);
                   5306:         } else {
                   5307:         # Just a normal role, defined in roles.tab
                   5308:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5309:         }
                   5310: 
                   5311:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5312:                  $username);
                   5313:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5314: 
                   5315:         # role expired or not available yet?
                   5316:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5317:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5318: 
                   5319:         next if $area eq '' or $trole eq '';
                   5320: 
                   5321:         my $spec = "$trole.$area";
                   5322:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5323: 
                   5324:         if ($trole =~ /^cr\//) {
                   5325:         # Custom role, defined by a user
                   5326:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5327:         } elsif ($trole eq 'gr') {
                   5328:         # Role of a member in a group, defined within a course/community
                   5329:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5330:             next;
                   5331:         } else {
                   5332:         # Normal role, defined in roles.tab
                   5333:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5334:         }
                   5335: 
                   5336:         my $cid = $tdomain.'_'.$trest;
                   5337:         unless ($firstaccchk{$cid}) {
                   5338:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5339:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5340:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5341:                         $coursetimerstarts{$cid}{$item}; 
                   5342:                 }
                   5343:             }
                   5344:             $firstaccchk{$cid} = 1;
                   5345:         }
                   5346:         unless ($timerintchk{$cid}) {
                   5347:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5348:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5349:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5350:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5351:                 }
1.12      www      5352:             }
1.1169    droeschl 5353:             $timerintchk{$cid} = 1;
1.191     harris41 5354:         }
1.11      www      5355:     }
1.1169    droeschl 5356: 
                   5357:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5358:         \%allroles, \%allgroups);
                   5359:     $env{'user.adv'} = $userroles{'user.adv'};
                   5360: 
1.1162    raeburn  5361:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5362: }
                   5363: 
1.567     raeburn  5364: sub set_arearole {
1.1215    raeburn  5365:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5366:     unless ($nolog) {
1.567     raeburn  5367: # log the associated role with the area
1.1215    raeburn  5368:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5369:     }
1.743     albertel 5370:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5371: }
                   5372: 
                   5373: sub custom_roleprivs {
                   5374:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5375:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5376:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5377:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5378:         my ($rdummy,$roledef)=
                   5379:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5380:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5381:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5382:             if (defined($syspriv)) {
1.1043    raeburn  5383:                 if ($trest =~ /^$match_community$/) {
                   5384:                     $syspriv =~ s/bre\&S//; 
                   5385:                 }
1.567     raeburn  5386:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5387:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5388:             }
                   5389:             if ($tdomain ne '') {
                   5390:                 if (defined($dompriv)) {
                   5391:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5392:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5393:                 }
                   5394:                 if (($trest ne '') && (defined($coursepriv))) {
                   5395:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5396:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5397:                 }
                   5398:             }
                   5399:         }
                   5400:     }
                   5401: }
                   5402: 
1.678     raeburn  5403: sub group_roleprivs {
                   5404:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5405:     my $access = 1;
                   5406:     my $now = time;
                   5407:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5408:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5409:     if ($access) {
1.811     albertel 5410:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5411:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5412:     }
                   5413: }
1.567     raeburn  5414: 
                   5415: sub standard_roleprivs {
                   5416:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5417:     if (defined($pr{$trole.':s'})) {
                   5418:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5419:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5420:     }
                   5421:     if ($tdomain ne '') {
                   5422:         if (defined($pr{$trole.':d'})) {
                   5423:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5424:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5425:         }
                   5426:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5427:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5428:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5429:         }
                   5430:     }
                   5431: }
                   5432: 
                   5433: sub set_userprivs {
1.1064    raeburn  5434:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5435:     my $author=0;
                   5436:     my $adv=0;
1.678     raeburn  5437:     my %grouproles = ();
                   5438:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5439:         my @groupkeys; 
1.1000    raeburn  5440:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5441:             push(@groupkeys,$role);
                   5442:         }
                   5443:         if (ref($groups_roles) eq 'HASH') {
                   5444:             foreach my $key (keys(%{$groups_roles})) {
                   5445:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5446:                     push(@groupkeys,$key);
                   5447:                 }
                   5448:             }
                   5449:         }
                   5450:         if (@groupkeys > 0) {
                   5451:             foreach my $role (@groupkeys) {
                   5452:                 my ($trole,$area,$sec,$extendedarea);
                   5453:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5454:                     $trole = $1;
                   5455:                     $area = $2;
                   5456:                     $sec = $3;
                   5457:                     $extendedarea = $area.$sec;
                   5458:                     if (exists($$allgroups{$area})) {
                   5459:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5460:                             my $spec = $trole.'.'.$extendedarea;
                   5461:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5462:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5463:                         }
1.678     raeburn  5464:                     }
                   5465:                 }
                   5466:             }
                   5467:         }
                   5468:     }
1.800     albertel 5469:     foreach my $group (keys(%grouproles)) {
                   5470:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5471:     }
1.800     albertel 5472:     foreach my $role (keys(%{$allroles})) {
                   5473:         my %thesepriv;
1.941     raeburn  5474:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5475:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5476:             if ($item ne '') {
                   5477:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5478:                 if ($restrictions eq '') {
                   5479:                     $thesepriv{$privilege}='F';
                   5480:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5481:                     $thesepriv{$privilege}.=$restrictions;
                   5482:                 }
                   5483:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5484:             }
                   5485:         }
                   5486:         my $thesestr='';
1.1104    raeburn  5487:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5488: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5489: 	}
                   5490:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5491:     }
                   5492:     return ($author,$adv);
                   5493: }
                   5494: 
1.994     raeburn  5495: sub role_status {
1.1104    raeburn  5496:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5497:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5498:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5499:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5500:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5501:             $$where = '/'.$two;
1.994     raeburn  5502:             $$trolecode=$$role.'.'.$$where;
                   5503:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5504:             $$tstatus='is';
1.1104    raeburn  5505:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5506:                 $$tstatus='future';
1.1034    raeburn  5507:                 if ($$tstart<$now) {
                   5508:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5509:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5510:                             my (%allroles,%allgroups,$group_privs,
                   5511:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5512:                             my %userroles = (
                   5513:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5514:                             );
1.1064    raeburn  5515:                             @rolecodes = ('cm'); 
1.1002    raeburn  5516:                             my $spec=$$role.'.'.$$where;
                   5517:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5518:                             if ($$role =~ /^cr\//) {
                   5519:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5520:                                 push(@rolecodes,'cr');
1.1002    raeburn  5521:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5522:                                 push(@rolecodes,$$role);
1.1002    raeburn  5523:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5524:                                                     $env{'user.name'});
1.1064    raeburn  5525:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5526:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5527:                                 $group_privs = &unescape($group_privs);
                   5528:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5529:                                 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  5530:                                 &get_groups_roles($tdomain,$trest,
                   5531:                                                   \%course_roles,\@rolecodes,
                   5532:                                                   \%groups_roles);
1.1002    raeburn  5533:                             } else {
1.1064    raeburn  5534:                                 push(@rolecodes,$$role);
1.1002    raeburn  5535:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5536:                             }
1.1064    raeburn  5537:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5538:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5539:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5540:                         }
                   5541:                     }
1.1034    raeburn  5542:                     $$tstatus = 'is';
1.1002    raeburn  5543:                 }
1.994     raeburn  5544:             }
                   5545:             if ($$tend) {
1.1104    raeburn  5546:                 if ($$tend<$update) {
1.994     raeburn  5547:                     $$tstatus='expired';
                   5548:                 } elsif ($$tend<$now) {
                   5549:                     $$tstatus='will_not';
                   5550:                 }
                   5551:             }
                   5552:         }
                   5553:     }
                   5554: }
                   5555: 
1.1104    raeburn  5556: sub get_groups_roles {
                   5557:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5558:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5559:                   (ref($rolecodes) eq 'ARRAY') && 
                   5560:                   (ref($groups_roles) eq 'HASH')); 
                   5561:     if (keys(%{$cdom_courseroles}) > 0) {
                   5562:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5563:         if ($cdom ne '' && $cnum ne '') {
                   5564:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5565:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5566:                     my $crsrole = $1;
                   5567:                     my $crssec = $2;
                   5568:                     if ($crsrole =~ /^cr/) {
                   5569:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5570:                             push(@{$rolecodes},'cr');
                   5571:                         }
                   5572:                     } else {
                   5573:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5574:                             push(@{$rolecodes},$crsrole);
                   5575:                         }
                   5576:                     }
                   5577:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5578:                     if ($crssec ne '') {
                   5579:                         $rolekey .= "/$crssec";
                   5580:                     }
                   5581:                     $rolekey .= './';
                   5582:                     $groups_roles->{$rolekey} = $rolecodes;
                   5583:                 }
                   5584:             }
                   5585:         }
                   5586:     }
                   5587:     return;
                   5588: }
                   5589: 
                   5590: sub delete_env_groupprivs {
                   5591:     my ($where,$courseroles,$possroles) = @_;
                   5592:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5593:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5594:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5595:         %{$courseroles->{$udom}} =
                   5596:             &get_my_roles('','','userroles',['active'],
                   5597:                           $possroles,[$udom],1);
                   5598:     }
                   5599:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5600:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5601:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5602:             my $area = '/'.$cdom.'/'.$cnum;
                   5603:             my $privkey = "user.priv.$crsrole.$area";
                   5604:             if ($crssec ne '') {
                   5605:                 $privkey .= '/'.$crssec;
                   5606:             }
                   5607:             $privkey .= ".$area/$group";
                   5608:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5609:         }
                   5610:     }
                   5611:     return;
                   5612: }
                   5613: 
1.994     raeburn  5614: sub check_adhoc_privs {
1.1104    raeburn  5615:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5616:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5617:     my $setprivs;
1.994     raeburn  5618:     if ($env{$cckey}) {
                   5619:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5620:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5621:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5622:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5623:             $setprivs = 1;
1.994     raeburn  5624:         }
                   5625:     } else {
1.1088    raeburn  5626:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5627:         $setprivs = 1;
1.994     raeburn  5628:     }
1.1185    raeburn  5629:     return $setprivs;
1.994     raeburn  5630: }
                   5631: 
                   5632: sub set_adhoc_privileges {
                   5633: # role can be cc or ca
1.1088    raeburn  5634:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5635:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5636:     my $spec = $role.'.'.$area;
                   5637:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5638:                                   $env{'user.name'},1);
1.994     raeburn  5639:     my %ccrole = ();
                   5640:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5641:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5642:     &appenv(\%userroles,[$role,'cm']);
                   5643:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5644:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5645:         &appenv( {'request.role'        => $spec,
                   5646:                   'request.role.domain' => $dcdom,
                   5647:                   'request.course.sec'  => ''
                   5648:                  }
                   5649:                );
                   5650:         my $tadv=0;
                   5651:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5652:         &appenv({'request.role.adv'    => $tadv});
                   5653:     }
1.994     raeburn  5654: }
                   5655: 
1.12      www      5656: # --------------------------------------------------------------- get interface
                   5657: 
                   5658: sub get {
1.131     albertel 5659:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5660:    my $items='';
1.800     albertel 5661:    foreach my $item (@$storearr) {
                   5662:        $items.=&escape($item).'&';
1.191     harris41 5663:    }
1.12      www      5664:    $items=~s/\&$//;
1.620     albertel 5665:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5666:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5667:    my $uhome=&homeserver($uname,$udomain);
                   5668: 
1.133     albertel 5669:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5670:    my @pairs=split(/\&/,$rep);
1.273     albertel 5671:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5672:      return @pairs;
                   5673:    }
1.15      www      5674:    my %returnhash=();
1.42      www      5675:    my $i=0;
1.800     albertel 5676:    foreach my $item (@$storearr) {
                   5677:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5678:       $i++;
1.191     harris41 5679:    }
1.15      www      5680:    return %returnhash;
1.27      www      5681: }
                   5682: 
                   5683: # --------------------------------------------------------------- del interface
                   5684: 
                   5685: sub del {
1.133     albertel 5686:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5687:    my $items='';
1.800     albertel 5688:    foreach my $item (@$storearr) {
                   5689:        $items.=&escape($item).'&';
1.191     harris41 5690:    }
1.984     neumanie 5691: 
1.27      www      5692:    $items=~s/\&$//;
1.620     albertel 5693:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5694:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5695:    my $uhome=&homeserver($uname,$udomain);
                   5696:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5697: }
                   5698: 
                   5699: # -------------------------------------------------------------- dump interface
                   5700: 
1.1180    droeschl 5701: sub unserialize {
                   5702:     my ($rep, $escapedkeys) = @_;
                   5703: 
                   5704:     return {} if $rep =~ /^error/;
                   5705: 
                   5706:     my %returnhash=();
1.1252    raeburn  5707: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 5708: 	    my ($key, $value) = split(/=/, $item, 2);
                   5709: 	    $key = unescape($key) unless $escapedkeys;
                   5710: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  5711: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 5712: 	}
                   5713:     #return %returnhash;
                   5714:     return \%returnhash;
                   5715: }        
                   5716: 
                   5717: # see Lond::dump_with_regexp
                   5718: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5719: sub dump {
1.1180    droeschl 5720:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5721:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5722:     if (!$uname) { $uname=$env{'user.name'}; }
                   5723:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5724: 
1.1266    raeburn  5725:     if ($regexp) {
                   5726:         $regexp=&escape($regexp);
                   5727:     } else {
                   5728:         $regexp='.';
                   5729:     }
1.1180    droeschl 5730:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5731:         # user is hosted on this machine
1.1266    raeburn  5732:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5733:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5734:         return %{unserialize($reply, $escapedkeys)};
                   5735:     }
1.1166    raeburn  5736:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5737:     my @pairs=split(/\&/,$rep);
                   5738:     my %returnhash=();
1.1098    foxr     5739:     if (!($rep =~ /^error/ )) {
                   5740: 	foreach my $item (@pairs) {
                   5741: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5742:         $key = unescape($key) unless $escapedkeys;
                   5743:         #$key = &unescape($key);
1.1098    foxr     5744: 	    next if ($key =~ /^error: 2 /);
                   5745: 	    $returnhash{$key}=&thaw_unescape($value);
                   5746: 	}
1.755     albertel 5747:     }
                   5748:     return %returnhash;
1.407     www      5749: }
                   5750: 
1.1098    foxr     5751: 
1.717     albertel 5752: # --------------------------------------------------------- dumpstore interface
                   5753: 
                   5754: sub dumpstore {
                   5755:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5756:    # same as dump but keys must be escaped. They may contain colon separated
                   5757:    # lists of values that may themself contain colons (e.g. symbs).
                   5758:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5759: }
                   5760: 
1.407     www      5761: # -------------------------------------------------------------- keys interface
                   5762: 
                   5763: sub getkeys {
                   5764:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5765:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5766:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5767:    my $uhome=&homeserver($uname,$udomain);
                   5768:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5769:    my @keyarray=();
1.800     albertel 5770:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5771:       next if ($key =~ /^error: 2 /);
1.800     albertel 5772:       push(@keyarray,&unescape($key));
1.407     www      5773:    }
                   5774:    return @keyarray;
1.318     matthew  5775: }
                   5776: 
1.319     matthew  5777: # --------------------------------------------------------------- currentdump
                   5778: sub currentdump {
1.328     matthew  5779:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5780:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5781:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5782:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5783:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5784:    my $rep;
                   5785: 
                   5786:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5787:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5788:                    $courseid)));
                   5789:    } else {
                   5790:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5791:    }
                   5792: 
1.318     matthew  5793:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5794:    #
1.318     matthew  5795:    my %returnhash=();
1.319     matthew  5796:    #
                   5797:    if ($rep eq "unknown_cmd") { 
                   5798:        # an old lond will not know currentdump
                   5799:        # Do a dump and make it look like a currentdump
1.822     albertel 5800:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5801:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5802:        my %hash = @tmp;
                   5803:        @tmp=();
1.424     matthew  5804:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5805:    } else {
                   5806:        my @pairs=split(/\&/,$rep);
1.800     albertel 5807:        foreach my $pair (@pairs) {
                   5808:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5809:            my ($symb,$param) = split(/:/,$key);
                   5810:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5811:                                                         &thaw_unescape($value);
1.319     matthew  5812:        }
1.191     harris41 5813:    }
1.12      www      5814:    return %returnhash;
1.424     matthew  5815: }
                   5816: 
                   5817: sub convert_dump_to_currentdump{
                   5818:     my %hash = %{shift()};
                   5819:     my %returnhash;
                   5820:     # Code ripped from lond, essentially.  The only difference
                   5821:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5822:     # we might run in to problems with parameter names =~ /^v\./
                   5823:     while (my ($key,$value) = each(%hash)) {
                   5824:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5825: 	$symb  = &unescape($symb);
                   5826: 	$param = &unescape($param);
1.424     matthew  5827:         next if ($v eq 'version' || $symb eq 'keys');
                   5828:         next if (exists($returnhash{$symb}) &&
                   5829:                  exists($returnhash{$symb}->{$param}) &&
                   5830:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5831:         $returnhash{$symb}->{$param}=$value;
                   5832:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5833:     }
                   5834:     #
                   5835:     # Remove all of the keys in the hashes which keep track of
                   5836:     # the version of the parameter.
                   5837:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5838:         # use a foreach because we are going to delete from the hash.
                   5839:         foreach my $key (keys(%$param_hash)) {
                   5840:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5841:         }
                   5842:     }
                   5843:     return \%returnhash;
1.12      www      5844: }
                   5845: 
1.627     albertel 5846: # ------------------------------------------------------ critical inc interface
                   5847: 
                   5848: sub cinc {
                   5849:     return &inc(@_,'critical');
                   5850: }
                   5851: 
1.449     matthew  5852: # --------------------------------------------------------------- inc interface
                   5853: 
                   5854: sub inc {
1.627     albertel 5855:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5856:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5857:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5858:     my $uhome=&homeserver($uname,$udomain);
                   5859:     my $items='';
                   5860:     if (! ref($store)) {
                   5861:         # got a single value, so use that instead
                   5862:         $items = &escape($store).'=&';
                   5863:     } elsif (ref($store) eq 'SCALAR') {
                   5864:         $items = &escape($$store).'=&';        
                   5865:     } elsif (ref($store) eq 'ARRAY') {
                   5866:         $items = join('=&',map {&escape($_);} @{$store});
                   5867:     } elsif (ref($store) eq 'HASH') {
                   5868:         while (my($key,$value) = each(%{$store})) {
                   5869:             $items.= &escape($key).'='.&escape($value).'&';
                   5870:         }
                   5871:     }
                   5872:     $items=~s/\&$//;
1.627     albertel 5873:     if ($critical) {
                   5874: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5875:     } else {
                   5876: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5877:     }
1.449     matthew  5878: }
                   5879: 
1.12      www      5880: # --------------------------------------------------------------- put interface
                   5881: 
                   5882: sub put {
1.134     albertel 5883:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5884:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5885:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5886:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5887:    my $items='';
1.800     albertel 5888:    foreach my $item (keys(%$storehash)) {
                   5889:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5890:    }
1.12      www      5891:    $items=~s/\&$//;
1.134     albertel 5892:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5893: }
                   5894: 
1.631     albertel 5895: # ------------------------------------------------------------ newput interface
                   5896: 
                   5897: sub newput {
                   5898:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5899:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5900:    if (!$uname) { $uname=$env{'user.name'}; }
                   5901:    my $uhome=&homeserver($uname,$udomain);
                   5902:    my $items='';
                   5903:    foreach my $key (keys(%$storehash)) {
                   5904:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5905:    }
                   5906:    $items=~s/\&$//;
                   5907:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5908: }
                   5909: 
                   5910: # ---------------------------------------------------------  putstore interface
                   5911: 
1.524     raeburn  5912: sub putstore {
1.1269    raeburn  5913:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 5914:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5915:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5916:    my $uhome=&homeserver($uname,$udomain);
                   5917:    my $items='';
1.715     albertel 5918:    foreach my $key (keys(%$storehash)) {
                   5919:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5920:    }
1.715     albertel 5921:    $items=~s/\&$//;
1.716     albertel 5922:    my $esc_symb=&escape($symb);
                   5923:    my $esc_v=&escape($version);
1.715     albertel 5924:    my $reply =
1.716     albertel 5925:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5926: 	      $uhome);
1.1269    raeburn  5927:    if (($tolog) && ($reply eq 'ok')) {
                   5928:        my $namevalue='';
                   5929:        foreach my $key (keys(%{$storehash})) {
                   5930:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   5931:        }
                   5932:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   5933:                      '&host='.&escape($perlvar{'lonHostID'}).
                   5934:                      '&version='.$esc_v.
                   5935:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   5936:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   5937:    }
1.715     albertel 5938:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5939:        # gfall back to way things use to be done
1.715     albertel 5940:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5941: 			    $uname);
1.524     raeburn  5942:    }
1.715     albertel 5943:    return $reply;
                   5944: }
                   5945: 
                   5946: sub old_putstore {
1.716     albertel 5947:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5948:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5949:     if (!$uname) { $uname=$env{'user.name'}; }
                   5950:     my $uhome=&homeserver($uname,$udomain);
                   5951:     my %newstorehash;
1.800     albertel 5952:     foreach my $item (keys(%$storehash)) {
                   5953: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5954: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5955:     }
                   5956:     my $items='';
                   5957:     my %allitems = ();
1.800     albertel 5958:     foreach my $item (keys(%newstorehash)) {
                   5959: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5960: 	    my $key = $1.':keys:'.$2;
                   5961: 	    $allitems{$key} .= $3.':';
                   5962: 	}
1.800     albertel 5963: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5964:     }
1.800     albertel 5965:     foreach my $item (keys(%allitems)) {
                   5966: 	$allitems{$item} =~ s/\:$//;
                   5967: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5968:     }
                   5969:     $items=~s/\&$//;
                   5970:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5971: }
                   5972: 
1.47      www      5973: # ------------------------------------------------------ critical put interface
                   5974: 
                   5975: sub cput {
1.134     albertel 5976:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5977:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5978:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5979:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5980:    my $items='';
1.800     albertel 5981:    foreach my $item (keys(%$storehash)) {
                   5982:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5983:    }
1.47      www      5984:    $items=~s/\&$//;
1.134     albertel 5985:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5986: }
                   5987: 
                   5988: # -------------------------------------------------------------- eget interface
                   5989: 
                   5990: sub eget {
1.133     albertel 5991:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5992:    my $items='';
1.800     albertel 5993:    foreach my $item (@$storearr) {
                   5994:        $items.=&escape($item).'&';
1.191     harris41 5995:    }
1.12      www      5996:    $items=~s/\&$//;
1.620     albertel 5997:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5998:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5999:    my $uhome=&homeserver($uname,$udomain);
                   6000:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6001:    my @pairs=split(/\&/,$rep);
                   6002:    my %returnhash=();
1.42      www      6003:    my $i=0;
1.800     albertel 6004:    foreach my $item (@$storearr) {
                   6005:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6006:       $i++;
1.191     harris41 6007:    }
1.12      www      6008:    return %returnhash;
                   6009: }
                   6010: 
1.667     albertel 6011: # ------------------------------------------------------------ tmpput interface
                   6012: sub tmpput {
1.802     raeburn  6013:     my ($storehash,$server,$context)=@_;
1.667     albertel 6014:     my $items='';
1.800     albertel 6015:     foreach my $item (keys(%$storehash)) {
                   6016: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6017:     }
                   6018:     $items=~s/\&$//;
1.802     raeburn  6019:     if (defined($context)) {
                   6020:         $items .= ':'.&escape($context);
                   6021:     }
1.667     albertel 6022:     return &reply("tmpput:$items",$server);
                   6023: }
                   6024: 
                   6025: # ------------------------------------------------------------ tmpget interface
                   6026: sub tmpget {
1.688     albertel 6027:     my ($token,$server)=@_;
                   6028:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6029:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6030:     my %returnhash;
                   6031:     foreach my $item (split(/\&/,$rep)) {
                   6032: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6033:         next if ($key =~ /^error: 2 /);
1.667     albertel 6034: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6035:     }
                   6036:     return %returnhash;
                   6037: }
                   6038: 
1.1113    raeburn  6039: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6040: sub tmpdel {
                   6041:     my ($token,$server)=@_;
                   6042:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6043:     return &reply("tmpdel:$token",$server);
                   6044: }
                   6045: 
1.1198    raeburn  6046: # ------------------------------------------------------------ get_timebased_id 
                   6047: 
                   6048: sub get_timebased_id {
                   6049:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6050:         $maxtries) = @_;
                   6051:     my ($newid,$error,$dellock);
                   6052:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6053:         return ('','ok','invalid call to get suffix');
                   6054:     }
                   6055: 
                   6056: # set defaults for any optional args for which values were not supplied
                   6057:     if ($who eq '') {
                   6058:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6059:     }
                   6060:     if (!$locktries) {
                   6061:         $locktries = 3;
                   6062:     }
                   6063:     if (!$maxtries) {
                   6064:         $maxtries = 10;
                   6065:     }
                   6066:     
                   6067:     if (($cdom eq '') || ($cnum eq '')) {
                   6068:         if ($env{'request.course.id'}) {
                   6069:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6070:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6071:         }
                   6072:         if (($cdom eq '') || ($cnum eq '')) {
                   6073:             return ('','ok','call to get suffix not in course context');
                   6074:         }
                   6075:     }
                   6076: 
                   6077: # construct locking item
                   6078:     my $lockhash = {
                   6079:                       $prefix."\0".'locked_'.$keyid => $who,
                   6080:                    };
                   6081:     my $tries = 0;
                   6082: 
                   6083: # attempt to get lock on nohist_$namespace file
                   6084:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6085:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6086:         $tries ++;
                   6087:         sleep 1;
                   6088:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6089:     }
                   6090: 
                   6091: # attempt to get unique identifier, based on current timestamp
                   6092:     if ($gotlock eq 'ok') {
                   6093:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6094:         my $id = time;
                   6095:         $newid = $id;
1.1268    raeburn  6096:         if ($idtype eq 'addcode') {
                   6097:             $newid .= &sixnum_code();
                   6098:         }
1.1198    raeburn  6099:         my $idtries = 0;
                   6100:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6101:             if ($idtype eq 'concat') {
                   6102:                 $newid = $id.$idtries;
1.1268    raeburn  6103:             } elsif ($idtype eq 'addcode') {
                   6104:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6105:             } else {
                   6106:                 $newid ++;
                   6107:             }
                   6108:             $idtries ++;
                   6109:         }
                   6110:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6111:             my %new_item =  (
                   6112:                               $prefix."\0".$newid => $who,
                   6113:                             );
                   6114:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6115:                                                  $cdom,$cnum);
                   6116:             if ($putresult ne 'ok') {
                   6117:                 undef($newid);
                   6118:                 $error = 'error saving new item: '.$putresult;
                   6119:             }
                   6120:         } else {
1.1268    raeburn  6121:              undef($newid);
1.1198    raeburn  6122:              $error = ('error: no unique suffix available for the new item ');
                   6123:         }
                   6124: #  remove lock
                   6125:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6126:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6127:     } else {
                   6128:         $error = "error: could not obtain lockfile\n";
                   6129:         $dellock = 'ok';
1.1276    raeburn  6130:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6131:             $dellock = 'nolock';
                   6132:         }
1.1198    raeburn  6133:     }
                   6134:     return ($newid,$dellock,$error);
                   6135: }
                   6136: 
1.1268    raeburn  6137: sub sixnum_code {
                   6138:     my $code;
                   6139:     for (0..6) {
                   6140:         $code .= int( rand(9) );
                   6141:     }
                   6142:     return $code;
                   6143: }
                   6144: 
1.765     albertel 6145: # -------------------------------------------------- portfolio access checking
                   6146: 
                   6147: sub portfolio_access {
1.1270    raeburn  6148:     my ($requrl,$clientip) = @_;
1.765     albertel 6149:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6150:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6151:     if ($result) {
                   6152:         my %setters;
                   6153:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6154:             my ($startblock,$endblock) =
                   6155:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6156:             if ($startblock && $endblock) {
                   6157:                 return 'B';
                   6158:             }
                   6159:         } else {
                   6160:             my ($startblock,$endblock) =
                   6161:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6162:             if ($startblock && $endblock) {
                   6163:                 return 'B';
                   6164:             }
                   6165:         }
                   6166:     }
1.765     albertel 6167:     if ($result eq 'ok') {
1.766     albertel 6168:        return 'F';
1.765     albertel 6169:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6170:        return 'A';
1.765     albertel 6171:     }
1.766     albertel 6172:     return '';
1.765     albertel 6173: }
                   6174: 
                   6175: sub get_portfolio_access {
1.1270    raeburn  6176:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6177: 
                   6178:     if (!ref($access_hash)) {
                   6179: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6180: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6181: 						   $file_name);
                   6182: 	$access_hash = $access_controls{$file_name};
                   6183:     }
                   6184: 
1.1270    raeburn  6185:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6186:     my $now = time;
                   6187:     if (ref($access_hash) eq 'HASH') {
                   6188:         foreach my $key (keys(%{$access_hash})) {
                   6189:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6190:             if ($start > $now) {
                   6191:                 next;
                   6192:             }
                   6193:             if ($end && $end<$now) {
                   6194:                 next;
                   6195:             }
                   6196:             if ($scope eq 'public') {
                   6197:                 $public = $key;
                   6198:                 last;
                   6199:             } elsif ($scope eq 'guest') {
                   6200:                 $guest = $key;
                   6201:             } elsif ($scope eq 'domains') {
                   6202:                 push(@domains,$key);
                   6203:             } elsif ($scope eq 'users') {
                   6204:                 push(@users,$key);
                   6205:             } elsif ($scope eq 'course') {
                   6206:                 push(@courses,$key);
                   6207:             } elsif ($scope eq 'group') {
                   6208:                 push(@groups,$key);
1.1270    raeburn  6209:             } elsif ($scope eq 'ip') {
                   6210:                 push(@ips,$key);
1.765     albertel 6211:             }
                   6212:         }
                   6213:         if ($public) {
                   6214:             return 'ok';
1.1270    raeburn  6215:         } elsif (@ips > 0) {
                   6216:             my $allowed;
                   6217:             foreach my $ipkey (@ips) {
                   6218:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6219:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6220:                         $allowed = 1;
                   6221:                         last; 
                   6222:                     }
                   6223:                 }
                   6224:             }
                   6225:             if ($allowed) {
                   6226:                 return 'ok';
                   6227:             }
1.765     albertel 6228:         }
                   6229:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6230:             if ($guest) {
                   6231:                 return $guest;
                   6232:             }
                   6233:         } else {
                   6234:             if (@domains > 0) {
                   6235:                 foreach my $domkey (@domains) {
                   6236:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6237:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6238:                             return 'ok';
                   6239:                         }
                   6240:                     }
                   6241:                 }
                   6242:             }
                   6243:             if (@users > 0) {
                   6244:                 foreach my $userkey (@users) {
1.865     raeburn  6245:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6246:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6247:                             if (ref($item) eq 'HASH') {
                   6248:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6249:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6250:                                     return 'ok';
                   6251:                                 }
                   6252:                             }
                   6253:                         }
                   6254:                     } 
1.765     albertel 6255:                 }
                   6256:             }
                   6257:             my %roleshash;
                   6258:             my @courses_and_groups = @courses;
                   6259:             push(@courses_and_groups,@groups); 
                   6260:             if (@courses_and_groups > 0) {
                   6261:                 my (%allgroups,%allroles); 
                   6262:                 my ($start,$end,$role,$sec,$group);
                   6263:                 foreach my $envkey (%env) {
1.1060    raeburn  6264:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6265:                         my $cid = $2.'_'.$3; 
                   6266:                         if ($1 eq 'gr') {
                   6267:                             $group = $4;
                   6268:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6269:                         } else {
                   6270:                             if ($4 eq '') {
                   6271:                                 $sec = 'none';
                   6272:                             } else {
                   6273:                                 $sec = $4;
                   6274:                             }
                   6275:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6276:                         }
1.811     albertel 6277:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6278:                         my $cid = $2.'_'.$3;
                   6279:                         if ($4 eq '') {
                   6280:                             $sec = 'none';
                   6281:                         } else {
                   6282:                             $sec = $4;
                   6283:                         }
                   6284:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6285:                     }
                   6286:                 }
                   6287:                 if (keys(%allroles) == 0) {
                   6288:                     return;
                   6289:                 }
                   6290:                 foreach my $key (@courses_and_groups) {
                   6291:                     my %content = %{$$access_hash{$key}};
                   6292:                     my $cnum = $content{'number'};
                   6293:                     my $cdom = $content{'domain'};
                   6294:                     my $cid = $cdom.'_'.$cnum;
                   6295:                     if (!exists($allroles{$cid})) {
                   6296:                         next;
                   6297:                     }    
                   6298:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6299:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6300:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6301:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6302:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6303:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6304:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6305:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6306:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6307:                                         if (grep/^all$/,@sections) {
                   6308:                                             return 'ok';
                   6309:                                         } else {
                   6310:                                             if (grep/^$sec$/,@sections) {
                   6311:                                                 return 'ok';
                   6312:                                             }
                   6313:                                         }
                   6314:                                     }
                   6315:                                 }
                   6316:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6317:                                     if (grep/^none$/,@groups) {
                   6318:                                         return 'ok';
                   6319:                                     }
                   6320:                                 } else {
                   6321:                                     if (grep/^all$/,@groups) {
                   6322:                                         return 'ok';
                   6323:                                     } 
                   6324:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6325:                                         if (grep/^$group$/,@groups) {
                   6326:                                             return 'ok';
                   6327:                                         }
                   6328:                                     }
                   6329:                                 } 
                   6330:                             }
                   6331:                         }
                   6332:                     }
                   6333:                 }
                   6334:             }
                   6335:             if ($guest) {
                   6336:                 return $guest;
                   6337:             }
                   6338:         }
                   6339:     }
                   6340:     return;
                   6341: }
                   6342: 
                   6343: sub course_group_datechecker {
                   6344:     my ($dates,$now,$status) = @_;
                   6345:     my ($start,$end) = split(/\./,$dates);
                   6346:     if (!$start && !$end) {
                   6347:         return 'ok';
                   6348:     }
                   6349:     if (grep/^active$/,@{$status}) {
                   6350:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6351:             return 'ok';
                   6352:         }
                   6353:     }
                   6354:     if (grep/^previous$/,@{$status}) {
                   6355:         if ($end > $now ) {
                   6356:             return 'ok';
                   6357:         }
                   6358:     }
                   6359:     if (grep/^future$/,@{$status}) {
                   6360:         if ($start > $now) {
                   6361:             return 'ok';
                   6362:         }
                   6363:     }
                   6364:     return; 
                   6365: }
                   6366: 
                   6367: sub parse_portfolio_url {
                   6368:     my ($url) = @_;
                   6369: 
                   6370:     my ($type,$udom,$unum,$group,$file_name);
                   6371:     
1.823     albertel 6372:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6373: 	$type = 1;
                   6374:         $udom = $1;
                   6375:         $unum = $2;
                   6376:         $file_name = $3;
1.823     albertel 6377:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6378: 	$type = 2;
                   6379:         $udom = $1;
                   6380:         $unum = $2;
                   6381:         $group = $3;
                   6382:         $file_name = $3.'/'.$4;
                   6383:     }
                   6384:     if (wantarray) {
                   6385: 	return ($type,$udom,$unum,$file_name,$group);
                   6386:     }
                   6387:     return $type;
                   6388: }
                   6389: 
                   6390: sub is_portfolio_url {
                   6391:     my ($url) = @_;
                   6392:     return scalar(&parse_portfolio_url($url));
                   6393: }
                   6394: 
1.798     raeburn  6395: sub is_portfolio_file {
                   6396:     my ($file) = @_;
1.820     raeburn  6397:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6398:         return 1;
                   6399:     }
                   6400:     return;
                   6401: }
                   6402: 
1.976     raeburn  6403: sub usertools_access {
1.1084    raeburn  6404:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6405:     my ($access,%tools);
                   6406:     if ($context eq '') {
                   6407:         $context = 'tools';
                   6408:     }
                   6409:     if ($context eq 'requestcourses') {
                   6410:         %tools = (
                   6411:                       official   => 1,
                   6412:                       unofficial => 1,
1.1006    raeburn  6413:                       community  => 1,
1.1246    raeburn  6414:                       textbook   => 1,
1.985     raeburn  6415:                  );
1.1183    raeburn  6416:     } elsif ($context eq 'requestauthor') {
                   6417:         %tools = (
                   6418:                       requestauthor => 1,
                   6419:                  );
1.985     raeburn  6420:     } else {
                   6421:         %tools = (
                   6422:                       aboutme   => 1,
                   6423:                       blog      => 1,
1.1177    raeburn  6424:                       webdav    => 1,
1.985     raeburn  6425:                       portfolio => 1,
                   6426:                  );
                   6427:     }
1.976     raeburn  6428:     return if (!defined($tools{$tool}));
                   6429: 
1.1242    raeburn  6430:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6431:         $udom = $env{'user.domain'};
                   6432:         $uname = $env{'user.name'};
                   6433:     }
                   6434: 
1.978     raeburn  6435:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6436:         if ($action ne 'reload') {
1.985     raeburn  6437:             if ($context eq 'requestcourses') {
                   6438:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6439:             } elsif ($context eq 'requestauthor') {
                   6440:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6441:             } else {
                   6442:                 return $env{'environment.availabletools.'.$tool};
                   6443:             }
                   6444:         }
1.976     raeburn  6445:     }
                   6446: 
1.1183    raeburn  6447:     my ($toolstatus,$inststatus,$envkey);
                   6448:     if ($context eq 'requestauthor') {
                   6449:         $envkey = $context; 
                   6450:     } else {
                   6451:         $envkey = $context.'.'.$tool;
                   6452:     }
1.976     raeburn  6453: 
1.985     raeburn  6454:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6455:          ($action ne 'reload')) {
1.1183    raeburn  6456:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6457:         $inststatus = $env{'environment.inststatus'};
                   6458:     } else {
1.1084    raeburn  6459:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6460:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6461:             $inststatus = $userenvref->{'inststatus'};
                   6462:         } else {
1.1183    raeburn  6463:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6464:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6465:             $inststatus = $userenv{'inststatus'};
                   6466:         }
1.976     raeburn  6467:     }
                   6468: 
                   6469:     if ($toolstatus ne '') {
                   6470:         if ($toolstatus) {
                   6471:             $access = 1;
                   6472:         } else {
                   6473:             $access = 0;
                   6474:         }
                   6475:         return $access;
                   6476:     }
                   6477: 
1.1084    raeburn  6478:     my ($is_adv,%domdef);
                   6479:     if (ref($is_advref) eq 'HASH') {
                   6480:         $is_adv = $is_advref->{'is_adv'};
                   6481:     } else {
                   6482:         $is_adv = &is_advanced_user($udom,$uname);
                   6483:     }
                   6484:     if (ref($domdefref) eq 'HASH') {
                   6485:         %domdef = %{$domdefref};
                   6486:     } else {
                   6487:         %domdef = &get_domain_defaults($udom);
                   6488:     }
1.976     raeburn  6489:     if (ref($domdef{$tool}) eq 'HASH') {
                   6490:         if ($is_adv) {
                   6491:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6492:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6493:                     $access = 1;
                   6494:                 } else {
                   6495:                     $access = 0;
                   6496:                 }
                   6497:                 return $access;
                   6498:             }
                   6499:         }
                   6500:         if ($inststatus ne '') {
                   6501:             my ($hasaccess,$hasnoaccess);
                   6502:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6503:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6504:                     if ($domdef{$tool}{$affiliation}) {
                   6505:                         $hasaccess = 1;
                   6506:                     } else {
                   6507:                         $hasnoaccess = 1;
                   6508:                     }
                   6509:                 }
                   6510:             }
                   6511:             if ($hasaccess || $hasnoaccess) {
                   6512:                 if ($hasaccess) {
                   6513:                     $access = 1;
                   6514:                 } elsif ($hasnoaccess) {
                   6515:                     $access = 0; 
                   6516:                 }
                   6517:                 return $access;
                   6518:             }
                   6519:         } else {
                   6520:             if ($domdef{$tool}{'default'} ne '') {
                   6521:                 if ($domdef{$tool}{'default'}) {
                   6522:                     $access = 1;
                   6523:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6524:                     $access = 0;
                   6525:                 }
                   6526:                 return $access;
                   6527:             }
                   6528:         }
                   6529:     } else {
1.1177    raeburn  6530:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6531:             $access = 1;
                   6532:         } else {
                   6533:             $access = 0;
                   6534:         }
1.976     raeburn  6535:         return $access;
                   6536:     }
                   6537: }
                   6538: 
1.1050    raeburn  6539: sub is_course_owner {
                   6540:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6541:     if (($udom eq '') || ($uname eq '')) {
                   6542:         $udom = $env{'user.domain'};
                   6543:         $uname = $env{'user.name'};
                   6544:     }
                   6545:     unless (($udom eq '') || ($uname eq '')) {
                   6546:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6547:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6548:                 return 1;
                   6549:             } else {
                   6550:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6551:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6552:                     return 1;
                   6553:                 }
                   6554:             }
                   6555:         }
                   6556:     }
                   6557:     return;
                   6558: }
                   6559: 
1.976     raeburn  6560: sub is_advanced_user {
                   6561:     my ($udom,$uname) = @_;
1.1085    raeburn  6562:     if ($udom ne '' && $uname ne '') {
                   6563:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6564:             if (wantarray) {
                   6565:                 return ($env{'user.adv'},$env{'user.author'});
                   6566:             } else {
                   6567:                 return $env{'user.adv'};
                   6568:             }
1.1085    raeburn  6569:         }
                   6570:     }
1.976     raeburn  6571:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6572:     my %allroles;
1.1128    raeburn  6573:     my ($is_adv,$is_author);
1.976     raeburn  6574:     foreach my $role (keys(%roleshash)) {
                   6575:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6576:         my $area = '/'.$tdomain.'/'.$trest;
                   6577:         if ($sec ne '') {
                   6578:             $area .= '/'.$sec;
                   6579:         }
                   6580:         if (($area ne '') && ($trole ne '')) {
                   6581:             my $spec=$trole.'.'.$area;
                   6582:             if ($trole =~ /^cr\//) {
                   6583:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6584:             } elsif ($trole ne 'gr') {
                   6585:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6586:             }
1.1128    raeburn  6587:             if ($trole eq 'au') {
                   6588:                 $is_author = 1;
                   6589:             }
1.976     raeburn  6590:         }
                   6591:     }
                   6592:     foreach my $role (keys(%allroles)) {
                   6593:         last if ($is_adv);
                   6594:         foreach my $item (split(/:/,$allroles{$role})) {
                   6595:             if ($item ne '') {
                   6596:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6597:                 if ($privilege eq 'adv') {
                   6598:                     $is_adv = 1;
                   6599:                     last;
                   6600:                 }
                   6601:             }
                   6602:         }
                   6603:     }
1.1128    raeburn  6604:     if (wantarray) {
                   6605:         return ($is_adv,$is_author);
                   6606:     }
1.976     raeburn  6607:     return $is_adv;
                   6608: }
1.798     raeburn  6609: 
1.1035    raeburn  6610: sub check_can_request {
1.1036    raeburn  6611:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6612:     my $canreq = 0;
                   6613:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6614:     my @options = ('approval','validate','autolimit');
                   6615:     my $optregex = join('|',@options);
                   6616:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6617:         foreach my $type (@{$types}) {
                   6618:             if (&usertools_access($env{'user.name'},
                   6619:                                   $env{'user.domain'},
                   6620:                                   $type,undef,'requestcourses')) {
                   6621:                 $canreq ++;
1.1036    raeburn  6622:                 if (ref($request_domains) eq 'HASH') {
                   6623:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6624:                 }
1.1035    raeburn  6625:                 if ($dom eq $env{'user.domain'}) {
                   6626:                     $can_request->{$type} = 1;
                   6627:                 }
                   6628:             }
                   6629:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6630:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6631:                 if (@curr > 0) {
1.1036    raeburn  6632:                     foreach my $item (@curr) {
                   6633:                         if (ref($request_domains) eq 'HASH') {
                   6634:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6635:                             if ($otherdom ne '') {
                   6636:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6637:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6638:                                         push(@{$request_domains->{$type}},$otherdom);
                   6639:                                     }
                   6640:                                 } else {
                   6641:                                     push(@{$request_domains->{$type}},$otherdom);
                   6642:                                 }
                   6643:                             }
                   6644:                         }
                   6645:                     }
                   6646:                     unless($dom eq $env{'user.domain'}) {
                   6647:                         $canreq ++;
1.1035    raeburn  6648:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6649:                             $can_request->{$type} = 1;
                   6650:                         }
                   6651:                     }
                   6652:                 }
                   6653:             }
                   6654:         }
                   6655:     }
                   6656:     return $canreq;
                   6657: }
                   6658: 
1.341     www      6659: # ---------------------------------------------- Custom access rule evaluation
                   6660: 
                   6661: sub customaccess {
                   6662:     my ($priv,$uri)=@_;
1.807     albertel 6663:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6664:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6665:     $udom = &LONCAPA::clean_domain($udom);
                   6666:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6667:     my $access=0;
1.800     albertel 6668:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6669: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6670: 	if ($type eq 'user') {
                   6671: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6672: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6673: 		if ($tdom) {
                   6674: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6675: 		}
1.896     albertel 6676: 		if ($tuname) {
                   6677: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6678: 		}
                   6679: 		$access=($effect eq 'allow');
                   6680: 		last;
                   6681: 	    }
                   6682: 	} else {
                   6683: 	    if ($role) {
                   6684: 		if ($role ne $urole) { next; }
                   6685: 	    }
                   6686: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6687: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6688: 		if ($tdom) {
                   6689: 		    if ($tdom ne $udom) { next; }
                   6690: 		}
                   6691: 		if ($tcrs) {
                   6692: 		    if ($tcrs ne $ucrs) { next; }
                   6693: 		}
                   6694: 		if ($tsec) {
                   6695: 		    if ($tsec ne $usec) { next; }
                   6696: 		}
                   6697: 		$access=($effect eq 'allow');
                   6698: 		last;
                   6699: 	    }
                   6700: 	    if ($realm eq '' && $role eq '') {
                   6701: 		$access=($effect eq 'allow');
                   6702: 	    }
1.402     bowersj2 6703: 	}
1.341     www      6704:     }
                   6705:     return $access;
                   6706: }
                   6707: 
1.103     harris41 6708: # ------------------------------------------------- Check for a user privilege
1.12      www      6709: 
                   6710: sub allowed {
1.1281    raeburn  6711:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 6712:     my $ver_orguri=$uri;
1.439     www      6713:     $uri=&deversion($uri);
1.152     www      6714:     my $orguri=$uri;
1.52      www      6715:     $uri=&declutter($uri);
1.809     raeburn  6716: 
1.810     raeburn  6717:     if ($priv eq 'evb') {
                   6718: # Evade communication block restrictions for specified role in a course
                   6719:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6720:             return $1;
                   6721:         } else {
                   6722:             return;
                   6723:         }
                   6724:     }
                   6725: 
1.620     albertel 6726:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6727: # Free bre access to adm and meta resources
1.775     albertel 6728:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6729: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6730: 	&& ($priv eq 'bre')) {
1.14      www      6731: 	return 'F';
1.159     www      6732:     }
                   6733: 
1.545     banghart 6734: # Free bre access to user's own portfolio contents
1.714     raeburn  6735:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6736:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6737: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6738:         my %setters;
                   6739:         my ($startblock,$endblock) = 
                   6740:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6741:         if ($startblock && $endblock) {
                   6742:             return 'B';
                   6743:         } else {
                   6744:             return 'F';
                   6745:         }
1.545     banghart 6746:     }
                   6747: 
1.762     raeburn  6748: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6749:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6750:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6751:         if (exists($env{'request.course.id'})) {
                   6752:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6753:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6754:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6755:                 my $courseprivid=$env{'request.course.id'};
                   6756:                 $courseprivid=~s/\_/\//;
                   6757:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6758:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6759:                     return $1; 
1.762     raeburn  6760:                 } else {
                   6761:                     if ($env{'request.course.sec'}) {
                   6762:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6763:                     }
                   6764:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6765:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6766:                         return $2;
                   6767:                     }
1.714     raeburn  6768:                 }
                   6769:             }
                   6770:         }
                   6771:     }
                   6772: 
1.159     www      6773: # Free bre to public access
                   6774: 
                   6775:     if ($priv eq 'bre') {
1.238     www      6776:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6777: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6778:            return 'F'; 
                   6779:         }
1.238     www      6780:         if ($copyright eq 'priv') {
                   6781:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6782: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6783: 		return '';
                   6784:             }
                   6785:         }
                   6786:         if ($copyright eq 'domain') {
                   6787:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6788: 	    unless (($env{'user.domain'} eq $1) ||
                   6789:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6790: 		return '';
                   6791:             }
1.262     matthew  6792:         }
1.620     albertel 6793:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6794:             # Library role, so allow browsing of resources in this domain.
                   6795:             return 'F';
1.238     www      6796:         }
1.341     www      6797:         if ($copyright eq 'custom') {
                   6798: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6799:         }
1.14      www      6800:     }
1.264     matthew  6801:     # Domain coordinator is trying to create a course
1.620     albertel 6802:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6803:         # uri is the requested domain in this case.
                   6804:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6805:         # a role of dc for the domain in question.
1.620     albertel 6806:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6807:     }
1.29      www      6808: 
1.52      www      6809:     my $thisallowed='';
                   6810:     my $statecond=0;
                   6811:     my $courseprivid='';
                   6812: 
1.1039    raeburn  6813:     my $ownaccess;
1.1043    raeburn  6814:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6815:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6816:         if ($uri eq '') {
                   6817:             $ownaccess = 1;
                   6818:         } else {
                   6819:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6820:                 my $udom = $env{'user.domain'};
                   6821:                 my $uname = $env{'user.name'};
                   6822:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6823:                     $ownaccess = 1;
1.1040    raeburn  6824:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6825:                     unless ($uri =~ m{\.\./}) {
                   6826:                         $ownaccess = 1;
                   6827:                     }
                   6828:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6829:                     my $now = time;
                   6830:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6831:                         my $adom = $1;
                   6832:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6833:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6834:                                 my ($start,$end) = split('.',$env{$key});
                   6835:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6836:                                     $ownaccess = 1;
                   6837:                                     last;
                   6838:                                 }
                   6839:                             }
                   6840:                         }
                   6841:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6842:                         my $adom = $1;
                   6843:                         my $aname = $2;
1.1042    raeburn  6844:                         foreach my $role ('ca','aa') { 
                   6845:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6846:                                 my ($start,$end) =
                   6847:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6848:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6849:                                     $ownaccess = 1;
                   6850:                                     last;
                   6851:                                 }
1.1039    raeburn  6852:                             }
                   6853:                         }
                   6854:                     }
                   6855:                 }
                   6856:             }
                   6857:         }
                   6858:     }
                   6859: 
1.52      www      6860: # Course
                   6861: 
1.620     albertel 6862:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6863:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6864:             $thisallowed.=$1;
                   6865:         }
1.52      www      6866:     }
1.29      www      6867: 
1.52      www      6868: # Domain
                   6869: 
1.620     albertel 6870:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6871:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6872:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6873:             $thisallowed.=$1;
                   6874:         }
1.12      www      6875:     }
1.52      www      6876: 
1.1141    raeburn  6877: # User who is not author or co-author might still be able to edit
                   6878: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6879:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6880:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6881:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6882:             $thisallowed.=$1;
                   6883:         }
                   6884:     }
                   6885: 
1.52      www      6886: # Course: uri itself is a course
1.66      www      6887:     my $courseuri=$uri;
                   6888:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6889:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6890: 
1.620     albertel 6891:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
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.29      www      6897: 
1.665     albertel 6898: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6899: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6900:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6901: 	$thisallowed='';
1.671     raeburn  6902:         my ($match)=&is_on_map($uri);
                   6903:         if ($match) {
                   6904:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6905:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  6906:                 my $value = $1;
                   6907:                 if ($noblockcheck) {
                   6908:                     $thisallowed.=$value;
1.1162    raeburn  6909:                 } else {
1.1281    raeburn  6910:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6911:                     if (@blockers > 0) {
                   6912:                         $thisallowed = 'B';
                   6913:                     } else {
                   6914:                         $thisallowed.=$value;
                   6915:                     }
1.1162    raeburn  6916:                 }
1.671     raeburn  6917:             }
                   6918:         } else {
1.705     albertel 6919:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6920:             if ($refuri) {
                   6921:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6922:                     $thisallowed='F';
1.671     raeburn  6923:                 } else {
                   6924:                     $refuri=&declutter($refuri);
                   6925:                     my ($match) = &is_on_map($refuri);
                   6926:                     if ($match) {
1.1281    raeburn  6927:                         if ($noblockcheck) {
                   6928:                             $thisallowed='F';
1.1162    raeburn  6929:                         } else {
1.1281    raeburn  6930:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6931:                             if (@blockers > 0) {
                   6932:                                 $thisallowed = 'B';
                   6933:                             } else {
                   6934:                                 $thisallowed='F';
                   6935:                             }
1.1162    raeburn  6936:                         }
1.671     raeburn  6937:                     }
1.669     raeburn  6938:                 }
1.671     raeburn  6939:             }
                   6940:         }
1.314     www      6941:     }
1.492     albertel 6942: 
1.766     albertel 6943:     if ($priv eq 'bre'
                   6944: 	&& $thisallowed ne 'F' 
                   6945: 	&& $thisallowed ne '2'
                   6946: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  6947: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 6948:     }
1.1250    raeburn  6949: 
1.52      www      6950: # Full access at system, domain or course-wide level? Exit.
1.29      www      6951:     if ($thisallowed=~/F/) {
                   6952: 	return 'F';
                   6953:     }
                   6954: 
1.52      www      6955: # If this is generating or modifying users, exit with special codes
1.29      www      6956: 
1.643     www      6957:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6958: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6959: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6960: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6961: 	    unless ($auname) { return $thisallowed; }
                   6962: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6963: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6964: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6965: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6966: 	}
1.52      www      6967: 	return $thisallowed;
                   6968:     }
                   6969: #
1.103     harris41 6970: # Gathered so far: system, domain and course wide privileges
1.52      www      6971: #
                   6972: # Course: See if uri or referer is an individual resource that is part of 
                   6973: # the course
                   6974: 
1.620     albertel 6975:     if ($env{'request.course.id'}) {
1.232     www      6976: 
1.620     albertel 6977:        $courseprivid=$env{'request.course.id'};
                   6978:        if ($env{'request.course.sec'}) {
                   6979:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6980:        }
                   6981:        $courseprivid=~s/\_/\//;
                   6982:        my $checkreferer=1;
1.232     www      6983:        my ($match,$cond)=&is_on_map($uri);
                   6984:        if ($match) {
                   6985:            $statecond=$cond;
1.620     albertel 6986:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6987:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6988:                my $value = $1;
                   6989:                if ($priv eq 'bre') {
1.1281    raeburn  6990:                    if ($noblockcheck) {
                   6991:                        $thisallowed.=$value;
1.1162    raeburn  6992:                    } else {
1.1281    raeburn  6993:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6994:                        if (@blockers > 0) {
                   6995:                            $thisallowed = 'B';
                   6996:                        } else {
                   6997:                            $thisallowed.=$value;
                   6998:                        }
1.1162    raeburn  6999:                    }
                   7000:                } else {
                   7001:                    $thisallowed.=$value;
                   7002:                }
1.52      www      7003:                $checkreferer=0;
                   7004:            }
1.29      www      7005:        }
1.83      www      7006:        
1.148     www      7007:        if ($checkreferer) {
1.620     albertel 7008: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7009:             unless ($refuri) {
1.800     albertel 7010:                 foreach my $key (keys(%env)) {
                   7011: 		    if ($key=~/^httpref\..*\*/) {
                   7012: 			my $pattern=$key;
1.156     www      7013:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7014:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7015:                         $pattern=~s/\//\\\//g;
1.152     www      7016:                         if ($orguri=~/$pattern/) {
1.800     albertel 7017: 			    $refuri=$env{$key};
1.148     www      7018:                         }
                   7019:                     }
1.191     harris41 7020:                 }
1.148     www      7021:             }
1.232     www      7022: 
1.148     www      7023:          if ($refuri) { 
1.152     www      7024: 	  $refuri=&declutter($refuri);
1.232     www      7025:           my ($match,$cond)=&is_on_map($refuri);
                   7026:             if ($match) {
                   7027:               my $refstatecond=$cond;
1.620     albertel 7028:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7029:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7030:                   my $value = $1;
                   7031:                   if ($priv eq 'bre') {
1.1281    raeburn  7032:                       if ($noblockcheck) {
                   7033:                           $thisallowed.=$value;
1.1162    raeburn  7034:                       } else {
1.1281    raeburn  7035:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7036:                           if (@blockers > 0) {
                   7037:                               $thisallowed = 'B';
                   7038:                           } else {
                   7039:                               $thisallowed.=$value;
                   7040:                           }
1.1162    raeburn  7041:                       }
                   7042:                   } else {
                   7043:                       $thisallowed.=$value;
                   7044:                   }
1.53      www      7045:                   $uri=$refuri;
                   7046:                   $statecond=$refstatecond;
1.52      www      7047:               }
                   7048:           }
1.148     www      7049:         }
1.29      www      7050:        }
1.52      www      7051:    }
1.29      www      7052: 
1.52      www      7053: #
1.103     harris41 7054: # Gathered now: all privileges that could apply, and condition number
1.52      www      7055: # 
                   7056: #
                   7057: # Full or no access?
                   7058: #
1.29      www      7059: 
1.52      www      7060:     if ($thisallowed=~/F/) {
                   7061: 	return 'F';
                   7062:     }
1.29      www      7063: 
1.52      www      7064:     unless ($thisallowed) {
                   7065:         return '';
                   7066:     }
1.29      www      7067: 
1.52      www      7068: # Restrictions exist, deal with them
                   7069: #
                   7070: #   C:according to course preferences
                   7071: #   R:according to resource settings
                   7072: #   L:unless locked
                   7073: #   X:according to user session state
                   7074: #
                   7075: 
                   7076: # Possibly locked functionality, check all courses
1.54      www      7077: # Locks might take effect only after 10 minutes cache expiration for other
                   7078: # courses, and 2 minutes for current course
1.52      www      7079: 
                   7080:     my $envkey;
                   7081:     if ($thisallowed=~/L/) {
1.1000    raeburn  7082:         foreach $envkey (keys(%env)) {
1.54      www      7083:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7084:                my $courseid=$2;
                   7085:                my $roleid=$1.'.'.$2;
1.92      www      7086:                $courseid=~s/^\///;
1.54      www      7087:                my $expiretime=600;
1.620     albertel 7088:                if ($env{'request.role'} eq $roleid) {
1.54      www      7089: 		  $expiretime=120;
                   7090:                }
                   7091: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7092:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7093:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7094: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7095:                }
1.620     albertel 7096:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7097:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7098: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7099:                        &log($env{'user.domain'},$env{'user.name'},
                   7100:                             $env{'user.home'},
1.57      www      7101:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7102:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7103:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7104: 		       return '';
                   7105:                    }
                   7106:                }
1.620     albertel 7107:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7108:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7109: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7110:                        &log($env{'user.domain'},$env{'user.name'},
                   7111:                             $env{'user.home'},
1.57      www      7112:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7113:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7114:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7115: 		       return '';
                   7116:                    }
                   7117:                }
                   7118: 	   }
1.29      www      7119:        }
1.52      www      7120:     }
                   7121:    
                   7122: #
                   7123: # Rest of the restrictions depend on selected course
                   7124: #
                   7125: 
1.620     albertel 7126:     unless ($env{'request.course.id'}) {
1.766     albertel 7127: 	if ($thisallowed eq 'A') {
                   7128: 	    return 'A';
1.814     raeburn  7129:         } elsif ($thisallowed eq 'B') {
                   7130:             return 'B';
1.766     albertel 7131: 	} else {
                   7132: 	    return '1';
                   7133: 	}
1.52      www      7134:     }
1.29      www      7135: 
1.52      www      7136: #
                   7137: # Now user is definitely in a course
                   7138: #
1.53      www      7139: 
                   7140: 
                   7141: # Course preferences
                   7142: 
                   7143:    if ($thisallowed=~/C/) {
1.620     albertel 7144:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7145:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7146:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7147: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7148: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7149: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7150: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7151: 			$env{'request.course.id'});
                   7152: 	   }
1.237     www      7153:            return '';
                   7154:        }
                   7155: 
1.620     albertel 7156:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7157: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7158: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7159: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7160: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7161: 			$env{'request.course.id'});
                   7162: 	   }
1.54      www      7163:            return '';
                   7164:        }
1.53      www      7165:    }
                   7166: 
                   7167: # Resource preferences
                   7168: 
                   7169:    if ($thisallowed=~/R/) {
1.620     albertel 7170:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7171:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7172: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7173: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7174: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7175: 	   }
                   7176: 	   return '';
1.54      www      7177:        }
1.53      www      7178:    }
1.30      www      7179: 
1.246     www      7180: # Restricted by state or randomout?
1.30      www      7181: 
1.52      www      7182:    if ($thisallowed=~/X/) {
1.620     albertel 7183:       if ($env{'acc.randomout'}) {
1.579     albertel 7184: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7185:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7186:             return ''; 
                   7187:          }
1.247     www      7188:       }
                   7189:       if (&condval($statecond)) {
1.52      www      7190: 	 return '2';
                   7191:       } else {
                   7192:          return '';
                   7193:       }
                   7194:    }
1.30      www      7195: 
1.766     albertel 7196:     if ($thisallowed eq 'A') {
                   7197: 	return 'A';
1.814     raeburn  7198:     } elsif ($thisallowed eq 'B') {
                   7199:         return 'B';
1.766     albertel 7200:     }
1.52      www      7201:    return 'F';
1.232     www      7202: }
1.1162    raeburn  7203: 
1.1192    raeburn  7204: # ------------------------------------------- Check construction space access
                   7205: 
                   7206: sub constructaccess {
                   7207:     my ($url,$setpriv)=@_;
                   7208: 
                   7209: # We do not allow editing of previous versions of files
                   7210:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7211: 
                   7212: # Get username and domain from URL
                   7213:     my ($ownername,$ownerdomain,$ownerhome);
                   7214: 
                   7215:     ($ownerdomain,$ownername) =
                   7216:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   7217: 
                   7218: # The URL does not really point to any authorspace, forget it
                   7219:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7220: 
                   7221: # Now we need to see if the user has access to the authorspace of
                   7222: # $ownername at $ownerdomain
                   7223: 
                   7224:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7225: # Real author for this?
                   7226:        $ownerhome = $env{'user.home'};
                   7227:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7228:           return ($ownername,$ownerdomain,$ownerhome);
                   7229:        }
                   7230:     } else {
                   7231: # Co-author for this?
                   7232:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7233:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7234:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7235:             return ($ownername,$ownerdomain,$ownerhome);
                   7236:         }
                   7237:     }
                   7238: 
                   7239: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7240: # we might as well leave
                   7241:    unless ($setpriv) { return ''; }
                   7242: 
                   7243: # Backdoor access?
                   7244:     my $allowed=&allowed('eco',$ownerdomain);
                   7245: # Nope
                   7246:     unless ($allowed) { return ''; }
                   7247: # Looks like we may have access, but could be locked by the owner of the construction space
                   7248:     if ($allowed eq 'U') {
                   7249:         my %blocked=&get('environment',['domcoord.author'],
                   7250:                          $ownerdomain,$ownername);
                   7251: # Is blocked by owner
                   7252:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7253:     }
                   7254:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7255: # Grant temporary access
                   7256:         my $then=$env{'user.login.time'};
1.1209    raeburn  7257:         my $update=$env{'user.update.time'};
1.1192    raeburn  7258:         if (!$update) { $update = $then; }
                   7259:         my $refresh=$env{'user.refresh.time'};
                   7260:         if (!$refresh) { $refresh = $update; }
                   7261:         my $now = time;
                   7262:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7263:                            $now,'ca','constructaccess');
                   7264:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7265:         return($ownername,$ownerdomain,$ownerhome);
                   7266:     }
                   7267: # No business here
                   7268:     return '';
                   7269: }
                   7270: 
1.1282    raeburn  7271: # ----------------------------------------------------------- Content Blocking
                   7272: 
                   7273: {
                   7274: # Caches for faster Course Contents display where content blocking
                   7275: # is in operation (i.e., interval param set) for timed quiz.
                   7276: #
                   7277: # User for whom data are being temporarily cached.
                   7278: my $cacheduser='';
                   7279: # Cached blockers for this user (a hash of blocking items). 
                   7280: my %cachedblockers=();
                   7281: # When the data were last cached.
                   7282: my $cachedlast='';
                   7283: 
                   7284: sub load_all_blockers {
                   7285:     my ($uname,$udom,$blocks)=@_;
                   7286:     if (($uname ne '') && ($udom ne '')) { 
                   7287:         if (($cacheduser eq $uname.':'.$udom) &&
                   7288:             (abs($cachedlast-time)<5)) {
                   7289:             return;
                   7290:         }
                   7291:     }
                   7292:     $cachedlast=time;
                   7293:     $cacheduser=$uname.':'.$udom;
                   7294:     %cachedblockers = &get_commblock_resources($blocks);
                   7295: }
                   7296: 
1.1162    raeburn  7297: sub get_comm_blocks {
                   7298:     my ($cdom,$cnum) = @_;
                   7299:     if ($cdom eq '' || $cnum eq '') {
                   7300:         return unless ($env{'request.course.id'});
                   7301:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7302:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7303:     }
                   7304:     my %commblocks;
                   7305:     my $hashid=$cdom.'_'.$cnum;
                   7306:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7307:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7308:         %commblocks = %{$blocksref};
                   7309:     } else {
                   7310:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7311:         my $cachetime = 600;
                   7312:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7313:     }
                   7314:     return %commblocks;
                   7315: }
                   7316: 
1.1282    raeburn  7317: sub get_commblock_resources {
                   7318:     my ($blocks) = @_;
                   7319:     my %blockers = ();
                   7320:     return %blockers unless ($env{'request.course.id'});
                   7321:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7322:     my %commblocks;
                   7323:     if (ref($blocks) eq 'HASH') {
                   7324:         %commblocks = %{$blocks};
                   7325:     } else {
                   7326:         %commblocks = &get_comm_blocks();
                   7327:     }
1.1282    raeburn  7328:     return %blockers unless (keys(%commblocks) > 0); 
                   7329:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7330:     return %blockers unless (ref($navmap));
1.1162    raeburn  7331:     my $now = time;
                   7332:     foreach my $block (keys(%commblocks)) {
                   7333:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7334:             my ($start,$end) = ($1,$2);
                   7335:             if ($start <= $now && $end >= $now) {
                   7336:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7337:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7338:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  7339:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7340:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  7341:                             }
                   7342:                         }
                   7343:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  7344:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7345:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7346:                             }
                   7347:                         }
                   7348:                     }
                   7349:                 }
                   7350:             }
                   7351:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7352:             my $item = $1;
1.1163    raeburn  7353:             my @to_test;
1.1162    raeburn  7354:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7355:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  7356:                     my @interval;
                   7357:                     my $type = 'map';
                   7358:                     if ($item eq 'course') {
                   7359:                         $type = 'course';
                   7360:                         @interval=&EXT("resource.0.interval");
                   7361:                     } else {
                   7362:                         if ($item =~ /___\d+___/) {
                   7363:                             $type = 'resource';
                   7364:                             @interval=&EXT("resource.0.interval",$item);
                   7365:                             if (ref($navmap)) {                        
                   7366:                                 my $res = $navmap->getBySymb($item); 
                   7367:                                 push(@to_test,$res);
                   7368:                             }
1.1162    raeburn  7369:                         } else {
1.1282    raeburn  7370:                             my $mapsymb = &symbread($item,1);
                   7371:                             if ($mapsymb) {
                   7372:                                 if (ref($navmap)) {
                   7373:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7374:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7375:                                     foreach my $res (@to_test) {
                   7376:                                         my $symb = $res->symb();
                   7377:                                         next if ($symb eq $mapsymb);
                   7378:                                         if ($symb ne '') {
                   7379:                                             @interval=&EXT("resource.0.interval",$symb);
                   7380:                                             if ($interval[1] eq 'map') {
                   7381:                                                 last;
1.1162    raeburn  7382:                                             }
                   7383:                                         }
                   7384:                                     }
                   7385:                                 }
                   7386:                             }
                   7387:                         }
1.1282    raeburn  7388:                     }
                   7389:                     if ($interval[0] =~ /^\d+$/) {
                   7390:                         my $first_access;
                   7391:                         if ($type eq 'resource') {
                   7392:                             $first_access=&get_first_access($interval[1],$item);
                   7393:                         } elsif ($type eq 'map') {
                   7394:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7395:                         } else {
                   7396:                             $first_access=&get_first_access($interval[1]);
                   7397:                         }
                   7398:                         if ($first_access) {
                   7399:                             my $timesup = $first_access+$interval[0];
                   7400:                             if ($timesup > $now) {
                   7401:                                 my $activeblock;
                   7402:                                 foreach my $res (@to_test) {
1.1283    raeburn  7403:                                     if ($res->answerable()) {
1.1282    raeburn  7404:                                         $activeblock = 1;
                   7405:                                         last;
                   7406:                                     }
                   7407:                                 }
                   7408:                                 if ($activeblock) {
                   7409:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7410:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7411:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7412:                                          }
                   7413:                                     }
                   7414:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7415:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7416:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7417:                                         }
1.1162    raeburn  7418:                                     }
                   7419:                                 }
                   7420:                             }
                   7421:                         }
                   7422:                     }
                   7423:                 }
                   7424:             }
                   7425:         }
                   7426:     }
1.1282    raeburn  7427:     return %blockers;
1.1162    raeburn  7428: }
                   7429: 
1.1282    raeburn  7430: sub has_comm_blocking {
                   7431:     my ($priv,$symb,$uri,$blocks) = @_;
                   7432:     my @blockers;
                   7433:     return unless ($env{'request.course.id'});
                   7434:     return unless ($priv eq 'bre');
                   7435:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7436:     return if ($env{'request.state'} eq 'construct');
                   7437:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7438:     return unless (keys(%cachedblockers) > 0);
                   7439:     my (%possibles,@symbs);
                   7440:     if (!$symb) {
                   7441:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7442:     }
1.1282    raeburn  7443:     if ($symb) {
                   7444:         @symbs = ($symb);
                   7445:     } elsif (keys(%possibles)) { 
                   7446:         @symbs = keys(%possibles);
                   7447:     }
                   7448:     my $noblock;
                   7449:     foreach my $symb (@symbs) {
                   7450:         last if ($noblock);
                   7451:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7452:         foreach my $block (keys(%cachedblockers)) {
                   7453:             if ($block =~ /^firstaccess____(.+)$/) {
                   7454:                 my $item = $1;
                   7455:                 if (($item eq $map) || ($item eq $symb)) {
                   7456:                     $noblock = 1;
                   7457:                     last;
                   7458:                 }
                   7459:             }
                   7460:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7461:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7462:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7463:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7464:                             push(@blockers,$block);
                   7465:                         }
                   7466:                     }
                   7467:                 }
1.1162    raeburn  7468:             }
1.1282    raeburn  7469:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7470:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7471:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7472:                         push(@blockers,$block);
                   7473:                     }
                   7474:                 }
1.1162    raeburn  7475:             }
                   7476:         }
                   7477:     }
1.1282    raeburn  7478:     return if ($noblock);
                   7479:     return @blockers;
                   7480: }
1.1162    raeburn  7481: }
                   7482: 
1.1282    raeburn  7483: # -------------------------------- Deversion and split uri into path an filename   
                   7484: 
1.1133    foxr     7485: #
1.1282    raeburn  7486: #   Removes the version from a URI and
1.1133    foxr     7487: #   splits it in to its filename and path to the filename.
                   7488: #   Seems like File::Basename could have done this more clearly.
                   7489: #   Parameters:
                   7490: #      $uri   - input URI
                   7491: #   Returns:
                   7492: #     Two element list consisting of 
                   7493: #     $pathname  - the URI up to and excluding the trailing /
                   7494: #     $filename  - The part of the URI following the last /
                   7495: #  NOTE:
                   7496: #    Another realization of this is simply:
                   7497: #    use File::Basename;
                   7498: #    ...
                   7499: #    $uri = shift;
                   7500: #    $filename = basename($uri);
                   7501: #    $path     = dirname($uri);
                   7502: #    return ($filename, $path);
                   7503: #
                   7504: #     The implementation below is probably faster however.
                   7505: #
1.710     albertel 7506: sub split_uri_for_cond {
                   7507:     my $uri=&deversion(&declutter(shift));
                   7508:     my @uriparts=split(/\//,$uri);
                   7509:     my $filename=pop(@uriparts);
                   7510:     my $pathname=join('/',@uriparts);
                   7511:     return ($pathname,$filename);
                   7512: }
1.232     www      7513: # --------------------------------------------------- Is a resource on the map?
                   7514: 
                   7515: sub is_on_map {
1.710     albertel 7516:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7517:     #Trying to find the conditional for the file
1.620     albertel 7518:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7519: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7520:     if ($match) {
1.289     bowersj2 7521: 	return (1,$1);
                   7522:     } else {
1.434     www      7523: 	return (0,0);
1.289     bowersj2 7524:     }
1.12      www      7525: }
                   7526: 
1.427     www      7527: # --------------------------------------------------------- Get symb from alias
                   7528: 
                   7529: sub get_symb_from_alias {
                   7530:     my $symb=shift;
                   7531:     my ($map,$resid,$url)=&decode_symb($symb);
                   7532: # Already is a symb
                   7533:     if ($url) { return $symb; }
                   7534: # Must be an alias
                   7535:     my $aliassymb='';
                   7536:     my %bighash;
1.620     albertel 7537:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7538:                             &GDBM_READER(),0640)) {
                   7539:         my $rid=$bighash{'mapalias_'.$symb};
                   7540: 	if ($rid) {
                   7541: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7542: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7543: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7544: 	}
                   7545:         untie %bighash;
                   7546:     }
                   7547:     return $aliassymb;
                   7548: }
                   7549: 
1.12      www      7550: # ----------------------------------------------------------------- Define Role
                   7551: 
                   7552: sub definerole {
                   7553:   if (allowed('mcr','/')) {
                   7554:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7555:     foreach my $role (split(':',$sysrole)) {
                   7556: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7557:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7558:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7559: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7560:                return "refused:s:$crole&$cqual"; 
                   7561:             }
                   7562:         }
1.191     harris41 7563:     }
1.800     albertel 7564:     foreach my $role (split(':',$domrole)) {
                   7565: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7566:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7567:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7568: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7569:                return "refused:d:$crole&$cqual"; 
                   7570:             }
                   7571:         }
1.191     harris41 7572:     }
1.800     albertel 7573:     foreach my $role (split(':',$courole)) {
                   7574: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7575:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7576:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7577: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7578:                return "refused:c:$crole&$cqual"; 
                   7579:             }
                   7580:         }
1.191     harris41 7581:     }
1.620     albertel 7582:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7583:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7584: 	        "rolesdef_$rolename=".
                   7585:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7586:     return reply($command,$env{'user.home'});
1.12      www      7587:   } else {
                   7588:     return 'refused';
                   7589:   }
1.105     harris41 7590: }
                   7591: 
                   7592: # ---------------- Make a metadata query against the network of library servers
                   7593: 
                   7594: sub metadata_query {
1.1237    raeburn  7595:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7596:     my %rhash;
1.845     albertel 7597:     my %libserv = &all_library();
1.244     matthew  7598:     my @server_list = (defined($server_array) ? @$server_array
                   7599:                                               : keys(%libserv) );
                   7600:     for my $server (@server_list) {
1.1237    raeburn  7601:         my $domains = ''; 
                   7602:         if (ref($domains_hash) eq 'HASH') {
                   7603:             $domains = $domains_hash->{$server}; 
                   7604:         }
1.118     harris41 7605: 	unless ($custom or $customshow) {
1.1237    raeburn  7606: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7607: 	    $rhash{$server}=$reply;
                   7608: 	}
                   7609: 	else {
                   7610: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7611: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7612: 			     $server);
                   7613: 	    $rhash{$server}=$reply;
                   7614: 	}
1.112     harris41 7615:     }
1.118     harris41 7616:     return \%rhash;
1.240     www      7617: }
                   7618: 
                   7619: # ----------------------------------------- Send log queries and wait for reply
                   7620: 
                   7621: sub log_query {
                   7622:     my ($uname,$udom,$query,%filters)=@_;
                   7623:     my $uhome=&homeserver($uname,$udom);
                   7624:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7625:     my $uhost=&hostname($uhome);
1.800     albertel 7626:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7627:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7628:                        $uhome);
1.479     albertel 7629:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7630:     return get_query_reply($queryid);
                   7631: }
                   7632: 
1.818     raeburn  7633: # -------------------------- Update MySQL table for portfolio file
                   7634: 
                   7635: sub update_portfolio_table {
1.821     raeburn  7636:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7637:     if ($group ne '') {
                   7638:         $file_name =~s /^\Q$group\E//;
                   7639:     }
1.818     raeburn  7640:     my $homeserver = &homeserver($uname,$udom);
                   7641:     my $queryid=
1.821     raeburn  7642:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7643:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7644:     my $reply = &get_query_reply($queryid);
                   7645:     return $reply;
                   7646: }
                   7647: 
1.899     raeburn  7648: # -------------------------- Update MySQL allusers table
                   7649: 
                   7650: sub update_allusers_table {
                   7651:     my ($uname,$udom,$names) = @_;
                   7652:     my $homeserver = &homeserver($uname,$udom);
                   7653:     my $queryid=
                   7654:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7655:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7656:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7657:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7658:                'generation='.&escape($names->{'generation'}).'%%'.
                   7659:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7660:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7661:     return;
1.899     raeburn  7662: }
                   7663: 
1.508     raeburn  7664: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7665: 
                   7666: sub fetch_enrollment_query {
1.511     raeburn  7667:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7668:     my $homeserver;
1.547     raeburn  7669:     my $maxtries = 1;
1.508     raeburn  7670:     if ($context eq 'automated') {
                   7671:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7672:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7673:     } else {
                   7674:         $homeserver = &homeserver($cnum,$dom);
                   7675:     }
1.838     albertel 7676:     my $host=&hostname($homeserver);
1.506     raeburn  7677:     my $cmd = '';
1.1000    raeburn  7678:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7679:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7680:     }
                   7681:     $cmd =~ s/%%$//;
                   7682:     $cmd = &escape($cmd);
                   7683:     my $query = 'fetchenrollment';
1.620     albertel 7684:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7685:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7686:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7687:         return 'error: '.$queryid;
                   7688:     }
1.506     raeburn  7689:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7690:     my $tries = 1;
                   7691:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7692:         $reply = &get_query_reply($queryid);
                   7693:         $tries ++;
                   7694:     }
1.526     raeburn  7695:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7696:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7697:     } else {
1.901     albertel 7698:         my @responses = split(/:/,$reply);
1.515     raeburn  7699:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7700:             foreach my $line (@responses) {
                   7701:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7702:                 $$replyref{$key} = $value;
                   7703:             }
                   7704:         } else {
1.1117    foxr     7705:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7706:             foreach my $line (@responses) {
                   7707:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7708:                 $$replyref{$key} = $value;
                   7709:                 if ($value > 0) {
1.800     albertel 7710:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7711:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7712:                         my $destname = $pathname.'/'.$filename;
                   7713:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7714:                         if ($xml_classlist =~ /^error/) {
                   7715:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7716:                         } else {
1.506     raeburn  7717:                             if ( open(FILE,">$destname") ) {
                   7718:                                 print FILE &unescape($xml_classlist);
                   7719:                                 close(FILE);
1.526     raeburn  7720:                             } else {
                   7721:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7722:                             }
                   7723:                         }
                   7724:                     }
                   7725:                 }
                   7726:             }
                   7727:         }
                   7728:         return 'ok';
                   7729:     }
                   7730:     return 'error';
                   7731: }
                   7732: 
1.242     www      7733: sub get_query_reply {
                   7734:     my $queryid=shift;
1.1117    foxr     7735:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7736:     my $reply='';
                   7737:     for (1..100) {
1.1289    damieng  7738: 	sleep(0.2);
1.240     www      7739:         if (-e $replyfile.'.end') {
1.448     albertel 7740: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7741: 		$reply = join('',<$fh>);
                   7742: 		close($fh);
1.240     www      7743: 	   } else { return 'error: reply_file_error'; }
1.242     www      7744:            return &unescape($reply);
                   7745: 	}
1.240     www      7746:     }
1.242     www      7747:     return 'timeout:'.$queryid;
1.240     www      7748: }
                   7749: 
                   7750: sub courselog_query {
1.241     www      7751: #
                   7752: # possible filters:
                   7753: # url: url or symb
                   7754: # username
                   7755: # domain
                   7756: # action: view, submit, grade
                   7757: # start: timestamp
                   7758: # end: timestamp
                   7759: #
1.240     www      7760:     my (%filters)=@_;
1.620     albertel 7761:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7762:     if ($filters{'url'}) {
                   7763: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7764:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7765:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7766:     }
1.620     albertel 7767:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7768:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7769:     return &log_query($cname,$cdom,'courselog',%filters);
                   7770: }
                   7771: 
                   7772: sub userlog_query {
1.858     raeburn  7773: #
                   7774: # possible filters:
                   7775: # action: log check role
                   7776: # start: timestamp
                   7777: # end: timestamp
                   7778: #
1.240     www      7779:     my ($uname,$udom,%filters)=@_;
                   7780:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7781: }
                   7782: 
1.506     raeburn  7783: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7784: 
                   7785: sub auto_run {
1.508     raeburn  7786:     my ($cnum,$cdom) = @_;
1.876     raeburn  7787:     my $response = 0;
                   7788:     my $settings;
                   7789:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7790:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7791:         $settings = $domconfig{'autoenroll'};
                   7792:         if ($settings->{'run'} eq '1') {
                   7793:             $response = 1;
                   7794:         }
                   7795:     } else {
1.934     raeburn  7796:         my $homeserver;
                   7797:         if (&is_course($cdom,$cnum)) {
                   7798:             $homeserver = &homeserver($cnum,$cdom);
                   7799:         } else {
                   7800:             $homeserver = &domain($cdom,'primary');
                   7801:         }
                   7802:         if ($homeserver ne 'no_host') {
                   7803:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7804:         }
1.876     raeburn  7805:     }
1.506     raeburn  7806:     return $response;
                   7807: }
1.776     albertel 7808: 
1.506     raeburn  7809: sub auto_get_sections {
1.508     raeburn  7810:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7811:     my $homeserver;
                   7812:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7813:         $homeserver = &homeserver($cnum,$cdom);
                   7814:     }
                   7815:     if (!defined($homeserver)) { 
                   7816:         if ($cdom =~ /^$match_domain$/) {
                   7817:             $homeserver = &domain($cdom,'primary');
                   7818:         }
                   7819:     }
                   7820:     my @secs;
                   7821:     if (defined($homeserver)) {
                   7822:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7823:         unless ($response eq 'refused') {
                   7824:             @secs = split(/:/,$response);
                   7825:         }
1.506     raeburn  7826:     }
                   7827:     return @secs;
                   7828: }
1.776     albertel 7829: 
1.506     raeburn  7830: sub auto_new_course {
1.1099    raeburn  7831:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7832:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7833:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7834:     return $response;
                   7835: }
1.776     albertel 7836: 
1.506     raeburn  7837: sub auto_validate_courseID {
1.508     raeburn  7838:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7839:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7840:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7841:     return $response;
                   7842: }
1.776     albertel 7843: 
1.1007    raeburn  7844: sub auto_validate_instcode {
1.1020    raeburn  7845:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7846:     my ($homeserver,$response);
                   7847:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7848:         $homeserver = &homeserver($cnum,$cdom);
                   7849:     }
                   7850:     if (!defined($homeserver)) {
                   7851:         if ($cdom =~ /^$match_domain$/) {
                   7852:             $homeserver = &domain($cdom,'primary');
                   7853:         }
                   7854:     }
1.1065    raeburn  7855:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7856:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  7857:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7858:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7859: }
                   7860: 
1.506     raeburn  7861: sub auto_create_password {
1.873     raeburn  7862:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7863:     my ($homeserver,$response);
1.506     raeburn  7864:     my $create_passwd = 0;
                   7865:     my $authchk = '';
1.873     raeburn  7866:     if ($udom =~ /^$match_domain$/) {
                   7867:         $homeserver = &domain($udom,'primary');
                   7868:     }
                   7869:     if ($homeserver eq '') {
                   7870:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7871:             $homeserver = &homeserver($cnum,$cdom);
                   7872:         }
                   7873:     }
                   7874:     if ($homeserver eq '') {
                   7875:         $authchk = 'nodomain';
1.506     raeburn  7876:     } else {
1.873     raeburn  7877:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7878:         if ($response eq 'refused') {
                   7879:             $authchk = 'refused';
                   7880:         } else {
1.901     albertel 7881:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7882:         }
1.506     raeburn  7883:     }
                   7884:     return ($authparam,$create_passwd,$authchk);
                   7885: }
                   7886: 
1.706     raeburn  7887: sub auto_photo_permission {
                   7888:     my ($cnum,$cdom,$students) = @_;
                   7889:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7890:     my ($outcome,$perm_reqd,$conditions) = 
                   7891: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7892:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7893: 	return (undef,undef);
                   7894:     }
1.706     raeburn  7895:     return ($outcome,$perm_reqd,$conditions);
                   7896: }
                   7897: 
                   7898: sub auto_checkphotos {
                   7899:     my ($uname,$udom,$pid) = @_;
                   7900:     my $homeserver = &homeserver($uname,$udom);
                   7901:     my ($result,$resulttype);
                   7902:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7903: 				   &escape($uname).':'.&escape($pid),
                   7904: 				   $homeserver));
1.709     albertel 7905:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7906: 	return (undef,undef);
                   7907:     }
1.706     raeburn  7908:     if ($outcome) {
                   7909:         ($result,$resulttype) = split(/:/,$outcome);
                   7910:     } 
                   7911:     return ($result,$resulttype);
                   7912: }
                   7913: 
                   7914: sub auto_photochoice {
                   7915:     my ($cnum,$cdom) = @_;
                   7916:     my $homeserver = &homeserver($cnum,$cdom);
                   7917:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7918: 						       &escape($cdom),
                   7919: 						       $homeserver)));
1.709     albertel 7920:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7921: 	return (undef,undef);
                   7922:     }
1.706     raeburn  7923:     return ($update,$comment);
                   7924: }
                   7925: 
                   7926: sub auto_photoupdate {
                   7927:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7928:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7929:     my $host=&hostname($homeserver);
1.706     raeburn  7930:     my $cmd = '';
                   7931:     my $maxtries = 1;
1.800     albertel 7932:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7933:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7934:     }
                   7935:     $cmd =~ s/%%$//;
                   7936:     $cmd = &escape($cmd);
                   7937:     my $query = 'institutionalphotos';
                   7938:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7939:     unless ($queryid=~/^\Q$host\E\_/) {
                   7940:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7941:         return 'error: '.$queryid;
                   7942:     }
                   7943:     my $reply = &get_query_reply($queryid);
                   7944:     my $tries = 1;
                   7945:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7946:         $reply = &get_query_reply($queryid);
                   7947:         $tries ++;
                   7948:     }
                   7949:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7950:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7951:     } else {
                   7952:         my @responses = split(/:/,$reply);
                   7953:         my $outcome = shift(@responses); 
                   7954:         foreach my $item (@responses) {
                   7955:             my ($key,$value) = split(/=/,$item);
                   7956:             $$photo{$key} = $value;
                   7957:         }
                   7958:         return $outcome;
                   7959:     }
                   7960:     return 'error';
                   7961: }
                   7962: 
1.521     raeburn  7963: sub auto_instcode_format {
1.793     albertel 7964:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7965: 	$cat_order) = @_;
1.521     raeburn  7966:     my $courses = '';
1.772     raeburn  7967:     my @homeservers;
1.521     raeburn  7968:     if ($caller eq 'global') {
1.841     albertel 7969: 	my %servers = &get_servers($codedom,'library');
                   7970: 	foreach my $tryserver (keys(%servers)) {
                   7971: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7972: 		push(@homeservers,$tryserver);
                   7973: 	    }
1.584     raeburn  7974:         }
1.1022    raeburn  7975:     } elsif ($caller eq 'requests') {
                   7976:         if ($codedom =~ /^$match_domain$/) {
                   7977:             my $chome = &domain($codedom,'primary');
                   7978:             unless ($chome eq 'no_host') {
                   7979:                 push(@homeservers,$chome);
                   7980:             }
                   7981:         }
1.521     raeburn  7982:     } else {
1.772     raeburn  7983:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7984:     }
1.793     albertel 7985:     foreach my $code (keys(%{$instcodes})) {
                   7986:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7987:     }
                   7988:     chop($courses);
1.772     raeburn  7989:     my $ok_response = 0;
                   7990:     my $response;
                   7991:     while (@homeservers > 0 && $ok_response == 0) {
                   7992:         my $server = shift(@homeservers); 
                   7993:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7994:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7995:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7996: 		split(/:/,$response);
1.772     raeburn  7997:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7998:             push(@{$codetitles},&str2array($codetitles_str));
                   7999:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8000:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8001:             $ok_response = 1;
                   8002:         }
                   8003:     }
                   8004:     if ($ok_response) {
1.521     raeburn  8005:         return 'ok';
1.772     raeburn  8006:     } else {
                   8007:         return $response;
1.521     raeburn  8008:     }
                   8009: }
                   8010: 
1.792     raeburn  8011: sub auto_instcode_defaults {
                   8012:     my ($domain,$returnhash,$code_order) = @_;
                   8013:     my @homeservers;
1.841     albertel 8014: 
                   8015:     my %servers = &get_servers($domain,'library');
                   8016:     foreach my $tryserver (keys(%servers)) {
                   8017: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8018: 	    push(@homeservers,$tryserver);
                   8019: 	}
1.792     raeburn  8020:     }
1.841     albertel 8021: 
1.792     raeburn  8022:     my $response;
1.841     albertel 8023:     foreach my $server (@homeservers) {
1.792     raeburn  8024:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8025:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8026: 	
                   8027: 	foreach my $pair (split(/\&/,$response)) {
                   8028: 	    my ($name,$value)=split(/\=/,$pair);
                   8029: 	    if ($name eq 'code_order') {
                   8030: 		@{$code_order} = split(/\&/,&unescape($value));
                   8031: 	    } else {
                   8032: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8033: 	    }
                   8034: 	}
                   8035: 	return 'ok';
1.792     raeburn  8036:     }
1.841     albertel 8037: 
                   8038:     return $response;
1.1003    raeburn  8039: }
                   8040: 
                   8041: sub auto_possible_instcodes {
1.1007    raeburn  8042:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8043:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8044:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8045:         return;
                   8046:     }
1.1003    raeburn  8047:     my (@homeservers,$uhome);
                   8048:     if (defined(&domain($domain,'primary'))) {
                   8049:         $uhome=&domain($domain,'primary');
                   8050:         push(@homeservers,&domain($domain,'primary'));
                   8051:     } else {
                   8052:         my %servers = &get_servers($domain,'library');
                   8053:         foreach my $tryserver (keys(%servers)) {
                   8054:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8055:                 push(@homeservers,$tryserver);
                   8056:             }
                   8057:         }
                   8058:     }
                   8059:     my $response;
                   8060:     foreach my $server (@homeservers) {
                   8061:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8062:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8063:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8064:             split(':',$response);
                   8065:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8066:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8067:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8068:             my ($name,$value)=split('=',$item);
                   8069:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8070:         }
                   8071:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8072:             my ($name,$value)=split('=',$item);
                   8073:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8074:         }
                   8075:         return 'ok';
                   8076:     }
                   8077:     return $response;
                   8078: }
1.792     raeburn  8079: 
1.1010    raeburn  8080: sub auto_courserequest_checks {
                   8081:     my ($dom) = @_;
1.1020    raeburn  8082:     my ($homeserver,%validations);
                   8083:     if ($dom =~ /^$match_domain$/) {
                   8084:         $homeserver = &domain($dom,'primary');
                   8085:     }
                   8086:     unless ($homeserver eq 'no_host') {
                   8087:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8088:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8089:             my @items = split(/&/,$response);
                   8090:             foreach my $item (@items) {
                   8091:                 my ($key,$value) = split('=',$item);
                   8092:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8093:             }
                   8094:         }
                   8095:     }
1.1010    raeburn  8096:     return %validations; 
                   8097: }
                   8098: 
1.1020    raeburn  8099: sub auto_courserequest_validation {
1.1255    raeburn  8100:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8101:     my ($homeserver,$response);
                   8102:     if ($dom =~ /^$match_domain$/) {
                   8103:         $homeserver = &domain($dom,'primary');
                   8104:     }
1.1255    raeburn  8105:     unless ($homeserver eq 'no_host') {
                   8106:         my $customdata;
                   8107:         if (ref($custominfo) eq 'HASH') {
                   8108:             $customdata = &freeze_escape($custominfo);
                   8109:         }
1.1020    raeburn  8110:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8111:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8112:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8113:                                     $customdata,$homeserver));
1.1020    raeburn  8114:     }
                   8115:     return $response;
                   8116: }
                   8117: 
1.777     albertel 8118: sub auto_validate_class_sec {
1.918     raeburn  8119:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8120:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8121:     my $ownerlist;
                   8122:     if (ref($owners) eq 'ARRAY') {
                   8123:         $ownerlist = join(',',@{$owners});
                   8124:     } else {
                   8125:         $ownerlist = $owners;
                   8126:     }
1.773     raeburn  8127:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8128:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8129:     return $response;
                   8130: }
                   8131: 
1.1248    raeburn  8132: sub auto_crsreq_update {
                   8133:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8134:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8135:     my ($homeserver,%crsreqresponse);
                   8136:     if ($cdom =~ /^$match_domain$/) {
                   8137:         $homeserver = &domain($cdom,'primary');
                   8138:     }
                   8139:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8140:         my $info;
                   8141:         if (ref($inbound) eq 'HASH') {
                   8142:             $info = &freeze_escape($inbound);
                   8143:         }
                   8144:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8145:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8146:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8147:                             &escape($title).':'.&escape($code).':'.
                   8148:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8149:                             $homeserver);
1.1248    raeburn  8150:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8151:             my @items = split(/&/,$response);
                   8152:             foreach my $item (@items) {
                   8153:                 my ($key,$value) = split('=',$item);
                   8154:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8155:             }
                   8156:         }
                   8157:     }
                   8158:     return \%crsreqresponse;
                   8159: }
                   8160: 
1.1287    raeburn  8161: sub check_instcode_cloning {
                   8162:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8163:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8164:         return;
                   8165:     }
                   8166:     my $canclone;
                   8167:     if (@{$code_order} > 0) {
                   8168:         my $instcoderegexp ='^';
                   8169:         my @clonecodes = split(/\&/,$cloner);
                   8170:         foreach my $item (@{$code_order}) {
                   8171:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8172:                 foreach my $pair (@clonecodes) {
                   8173:                     my ($key,$val) = split(/\=/,$pair,2);
                   8174:                     $val = &unescape($val);
                   8175:                     if ($key eq $item) {
                   8176:                         $instcoderegexp .= '('.$val.')';
                   8177:                         last;
                   8178:                     }
                   8179:                 }
                   8180:             } else {
                   8181:                 $instcoderegexp .= $codedefaults->{$item};
                   8182:             }
                   8183:         }
                   8184:         $instcoderegexp .= '$';
                   8185:         my (@from,@to);
                   8186:         eval {
                   8187:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8188:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8189:         };
                   8190:         if ((@from > 0) && (@to > 0)) {
                   8191:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8192:             if (!@diffs) {
                   8193:                 $canclone = 1;
                   8194:             }
                   8195:         }
                   8196:     }
                   8197:     return $canclone;
                   8198: }
                   8199: 
                   8200: sub default_instcode_cloning {
                   8201:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8202:     my (%codedefaults,@code_order,$canclone);
                   8203:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8204:         %codedefaults = %{$codedefaultsref};
                   8205:         @code_order = @{$codeorderref};
                   8206:     } elsif ($clonedom) {
                   8207:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8208:     }
                   8209:     if (($domdefclone) && (@code_order)) {
                   8210:         my @clonecodes = split(/\+/,$domdefclone);
                   8211:         my $instcoderegexp ='^';
                   8212:         foreach my $item (@code_order) {
                   8213:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8214:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8215:             } else {
                   8216:                 $instcoderegexp .= $codedefaults{$item};
                   8217:             }
                   8218:         }
                   8219:         $instcoderegexp .= '$';
                   8220:         my (@from,@to);
                   8221:         eval {
                   8222:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8223:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8224:         };
                   8225:         if ((@from > 0) && (@to > 0)) {
                   8226:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8227:             if (!@diffs) {
                   8228:                 $canclone = 1;
                   8229:             }
                   8230:         }
                   8231:     }
                   8232:     return $canclone;
                   8233: }
                   8234: 
1.679     raeburn  8235: # ------------------------------------------------------- Course Group routines
                   8236: 
                   8237: sub get_coursegroups {
1.809     raeburn  8238:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8239:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8240: }
                   8241: 
1.679     raeburn  8242: sub modify_coursegroup {
                   8243:     my ($cdom,$cnum,$groupsettings) = @_;
                   8244:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8245: }
                   8246: 
1.809     raeburn  8247: sub toggle_coursegroup_status {
                   8248:     my ($cdom,$cnum,$group,$action) = @_;
                   8249:     my ($from_namespace,$to_namespace);
                   8250:     if ($action eq 'delete') {
                   8251:         $from_namespace = 'coursegroups';
                   8252:         $to_namespace = 'deleted_groups';
                   8253:     } else {
                   8254:         $from_namespace = 'deleted_groups';
                   8255:         $to_namespace = 'coursegroups';
                   8256:     }
                   8257:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8258:     if (my $tmp = &error(%curr_group)) {
                   8259:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8260:         return ('read error',$tmp);
                   8261:     } else {
                   8262:         my %savedsettings = %curr_group; 
1.809     raeburn  8263:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8264:         my $deloutcome;
                   8265:         if ($result eq 'ok') {
1.809     raeburn  8266:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8267:         } else {
                   8268:             return ('write error',$result);
                   8269:         }
                   8270:         if ($deloutcome eq 'ok') {
                   8271:             return 'ok';
                   8272:         } else {
                   8273:             return ('delete error',$deloutcome);
                   8274:         }
                   8275:     }
                   8276: }
                   8277: 
1.679     raeburn  8278: sub modify_group_roles {
1.957     raeburn  8279:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8280:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8281:     my $role = 'gr/'.&escape($userprivs);
                   8282:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8283:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8284:     if ($result eq 'ok') {
                   8285:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8286:     }
1.679     raeburn  8287:     return $result;
                   8288: }
                   8289: 
                   8290: sub modify_coursegroup_membership {
                   8291:     my ($cdom,$cnum,$membership) = @_;
                   8292:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8293:     return $result;
                   8294: }
                   8295: 
1.682     raeburn  8296: sub get_active_groups {
                   8297:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8298:     my $now = time;
                   8299:     my %groups = ();
                   8300:     foreach my $key (keys(%env)) {
1.811     albertel 8301:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8302:             my ($start,$end) = split(/\./,$env{$key});
                   8303:             if (($end!=0) && ($end<$now)) { next; }
                   8304:             if (($start!=0) && ($start>$now)) { next; }
                   8305:             if ($1 eq $cdom && $2 eq $cnum) {
                   8306:                 $groups{$3} = $env{$key} ;
                   8307:             }
                   8308:         }
                   8309:     }
                   8310:     return %groups;
                   8311: }
                   8312: 
1.683     raeburn  8313: sub get_group_membership {
                   8314:     my ($cdom,$cnum,$group) = @_;
                   8315:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8316: }
                   8317: 
                   8318: sub get_users_groups {
                   8319:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8320:     my @usersgroups;
1.683     raeburn  8321:     my $cachetime=1800;
                   8322: 
                   8323:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8324:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8325:     if (defined($cached)) {
1.734     albertel 8326:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8327:     } else {  
                   8328:         $grouplist = '';
1.816     raeburn  8329:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8330:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8331:         my $access_end = $env{'course.'.$courseid.
                   8332:                               '.default_enrollment_end_date'};
                   8333:         my $now = time;
                   8334:         foreach my $key (keys(%roleshash)) {
                   8335:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8336:                 my $group = $1;
                   8337:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8338:                     my $start = $2;
                   8339:                     my $end = $1;
                   8340:                     if ($start == -1) { next; } # deleted from group
                   8341:                     if (($start!=0) && ($start>$now)) { next; }
                   8342:                     if (($end!=0) && ($end<$now)) {
                   8343:                         if ($access_end && $access_end < $now) {
                   8344:                             if ($access_end - $end < 86400) {
                   8345:                                 push(@usersgroups,$group);
1.733     raeburn  8346:                             }
                   8347:                         }
1.817     raeburn  8348:                         next;
1.733     raeburn  8349:                     }
1.817     raeburn  8350:                     push(@usersgroups,$group);
1.683     raeburn  8351:                 }
                   8352:             }
                   8353:         }
1.817     raeburn  8354:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8355:         $grouplist = join(':',@usersgroups);
                   8356:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8357:     }
1.733     raeburn  8358:     return @usersgroups;
1.683     raeburn  8359: }
                   8360: 
                   8361: sub devalidate_getgroups_cache {
                   8362:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8363:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8364: 
1.683     raeburn  8365:     my $hashid="$udom:$uname:$courseid";
                   8366:     &devalidate_cache_new('getgroups',$hashid);
                   8367: }
                   8368: 
1.12      www      8369: # ------------------------------------------------------------------ Plain Text
                   8370: 
                   8371: sub plaintext {
1.988     raeburn  8372:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8373:     if ($short =~ m{^cr/}) {
1.758     albertel 8374: 	return (split('/',$short))[-1];
                   8375:     }
1.742     raeburn  8376:     if (!defined($cid)) {
                   8377:         $cid = $env{'request.course.id'};
                   8378:     }
                   8379:     my %rolenames = (
1.1008    raeburn  8380:                       Course    => 'std',
                   8381:                       Community => 'alt1',
1.742     raeburn  8382:                     );
1.1037    raeburn  8383:     if ($cid ne '') {
                   8384:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8385:             unless ($forcedefault) {
                   8386:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8387:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8388:                 return &Apache::lonlocal::mt($roletext);
                   8389:             }
                   8390:         }
                   8391:     }
                   8392:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8393:         (defined($rolenames{$type})) && 
                   8394:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8395:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8396:     } elsif ($cid ne '') {
                   8397:         my $crstype = $env{'course.'.$cid.'.type'};
                   8398:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8399:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8400:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8401:         }
1.742     raeburn  8402:     }
1.1037    raeburn  8403:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8404: }
                   8405: 
                   8406: # ----------------------------------------------------------------- Assign Role
                   8407: 
                   8408: sub assignrole {
1.957     raeburn  8409:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8410:         $context)=@_;
1.21      www      8411:     my $mrole;
                   8412:     if ($role =~ /^cr\//) {
1.393     www      8413:         my $cwosec=$url;
1.811     albertel 8414:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8415: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8416:            my $refused = 1;
                   8417:            if ($context eq 'requestcourses') {
                   8418:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8419:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8420:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8421:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8422:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8423:                            if ($crsenv{'internal.courseowner'} eq
                   8424:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8425:                                $refused = '';
                   8426:                            }
                   8427:                        }
                   8428:                    }
                   8429:                }
                   8430:            }
                   8431:            if ($refused) {
                   8432:                &logthis('Refused custom assignrole: '.
                   8433:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8434:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8435:                return 'refused';
                   8436:            }
1.104     www      8437:         }
1.21      www      8438:         $mrole='cr';
1.678     raeburn  8439:     } elsif ($role =~ /^gr\//) {
                   8440:         my $cwogrp=$url;
1.811     albertel 8441:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8442:         unless (&allowed('mdg',$cwogrp)) {
                   8443:             &logthis('Refused group assignrole: '.
                   8444:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8445:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8446:             return 'refused';
                   8447:         }
                   8448:         $mrole='gr';
1.21      www      8449:     } else {
1.82      www      8450:         my $cwosec=$url;
1.811     albertel 8451:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8452:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8453:             my $refused;
                   8454:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8455:                 if (!(&allowed('c'.$role,$url))) {
                   8456:                     $refused = 1;
                   8457:                 }
                   8458:             } else {
                   8459:                 $refused = 1;
                   8460:             }
1.947     raeburn  8461:             if ($refused) {
1.1045    raeburn  8462:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8463:                 if (!$selfenroll && $context eq 'course') {
                   8464:                     my %crsenv;
                   8465:                     if ($role eq 'cc' || $role eq 'co') {
                   8466:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8467:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8468:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8469:                                 if ($crsenv{'internal.courseowner'} eq 
                   8470:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8471:                                     $refused = '';
                   8472:                                 }
                   8473:                             }
                   8474:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8475:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8476:                                 if ($crsenv{'internal.courseowner'} eq 
                   8477:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8478:                                     $refused = '';
                   8479:                                 }
                   8480:                             }
                   8481:                         }
                   8482:                     }
                   8483:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8484:                     $refused = '';
1.1017    raeburn  8485:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8486:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8487:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8488:                         my $wrongcc;
                   8489:                         if ($cnum =~ /^$match_community$/) {
                   8490:                             $wrongcc = 1 if ($role eq 'cc');
                   8491:                         } else {
                   8492:                             $wrongcc = 1 if ($role eq 'co');
                   8493:                         }
                   8494:                         unless ($wrongcc) {
                   8495:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8496:                             if ($crsenv{'internal.courseowner'} eq 
                   8497:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8498:                                 $refused = '';
                   8499:                             }
1.1017    raeburn  8500:                         }
                   8501:                     }
1.1183    raeburn  8502:                 } elsif ($context eq 'requestauthor') {
                   8503:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8504:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8505:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8506:                             $refused = '';
                   8507:                         } else {
                   8508:                             my %domdefaults = &get_domain_defaults($udom);
                   8509:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8510:                                 my $checkbystatus;
                   8511:                                 if ($env{'user.adv'}) { 
                   8512:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8513:                                     if ($disposition eq 'automatic') {
                   8514:                                         $refused = '';
                   8515:                                     } elsif ($disposition eq '') {
                   8516:                                         $checkbystatus = 1;
                   8517:                                     } 
                   8518:                                 } else {
                   8519:                                     $checkbystatus = 1;
                   8520:                                 }
                   8521:                                 if ($checkbystatus) {
                   8522:                                     if ($env{'environment.inststatus'}) {
                   8523:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8524:                                         foreach my $type (@inststatuses) {
                   8525:                                             if (($type ne '') &&
                   8526:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8527:                                                 $refused = '';
                   8528:                                             }
                   8529:                                         }
                   8530:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8531:                                         $refused = '';
                   8532:                                     }
                   8533:                                 }
                   8534:                             }
                   8535:                         }
                   8536:                     }
1.1017    raeburn  8537:                 }
                   8538:                 if ($refused) {
1.947     raeburn  8539:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8540:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8541: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8542:                     return 'refused';
                   8543:                 }
1.932     raeburn  8544:             }
1.1131    raeburn  8545:         } elsif ($role eq 'au') {
                   8546:             if ($url ne '/'.$udom.'/') {
                   8547:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8548:                          ' to assign author role for '.$uname.':'.$udom.
                   8549:                          ' in domain: '.$url.' refused (wrong domain).');
                   8550:                 return 'refused';
                   8551:             }
1.104     www      8552:         }
1.21      www      8553:         $mrole=$role;
                   8554:     }
1.620     albertel 8555:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8556:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8557:     if ($end) { $command.='_'.$end; }
1.21      www      8558:     if ($start) {
                   8559: 	if ($end) { 
1.81      www      8560:            $command.='_'.$start; 
1.21      www      8561:         } else {
1.81      www      8562:            $command.='_0_'.$start;
1.21      www      8563:         }
                   8564:     }
1.739     raeburn  8565:     my $origstart = $start;
                   8566:     my $origend = $end;
1.957     raeburn  8567:     my $delflag;
1.357     www      8568: # actually delete
                   8569:     if ($deleteflag) {
1.373     www      8570: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8571: # modify command to delete the role
1.620     albertel 8572:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8573:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8574: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8575: # set start and finish to negative values for userrolelog
                   8576:            $start=-1;
                   8577:            $end=-1;
1.957     raeburn  8578:            $delflag = 1;
1.357     www      8579:         }
                   8580:     }
                   8581: # send command
1.349     www      8582:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8583: # log new user role if status is ok
1.349     www      8584:     if ($answer eq 'ok') {
1.663     raeburn  8585: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8586:         if (($role eq 'cc') || ($role eq 'in') ||
                   8587:             ($role eq 'ep') || ($role eq 'ad') ||
                   8588:             ($role eq 'ta') || ($role eq 'st') ||
                   8589:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8590:             ($role eq 'co')) {
1.1200    raeburn  8591: # for course roles, perform group memberships changes triggered by role change.
                   8592:             unless ($role =~ /^gr/) {
                   8593:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8594:                                                  $origstart,$selfenroll,$context);
                   8595:             }
1.1184    raeburn  8596:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8597:                            $selfenroll,$context);
                   8598:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8599:                  ($role eq 'au') || ($role eq 'dc')) {
                   8600:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8601:                            $context);
                   8602:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8603:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8604:                              $context); 
                   8605:         }
1.1053    raeburn  8606:         if ($role eq 'cc') {
                   8607:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8608:         }
1.349     www      8609:     }
                   8610:     return $answer;
1.169     harris41 8611: }
                   8612: 
1.1053    raeburn  8613: sub autoupdate_coowners {
                   8614:     my ($url,$end,$start,$uname,$udom) = @_;
                   8615:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8616:     if (($cdom ne '') && ($cnum ne '')) {
                   8617:         my $now = time;
                   8618:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8619:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8620:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8621:             my $instcode = $coursehash{'internal.coursecode'};
                   8622:             if ($instcode ne '') {
1.1056    raeburn  8623:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8624:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8625:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8626:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8627:                         if ($result eq 'valid') {
                   8628:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8629:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8630:                                     push(@newcoowners,$coowner);
                   8631:                                 }
                   8632:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8633:                                     push(@newcoowners,$uname.':'.$udom);
                   8634:                                 }
                   8635:                                 @newcoowners = sort(@newcoowners);
                   8636:                             } else {
                   8637:                                 push(@newcoowners,$uname.':'.$udom);
                   8638:                             }
                   8639:                         } else {
                   8640:                             if ($coursehash{'internal.co-owners'}) {
                   8641:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8642:                                     unless ($coowner eq $uname.':'.$udom) {
                   8643:                                         push(@newcoowners,$coowner);
                   8644:                                     }
                   8645:                                 }
                   8646:                                 unless (@newcoowners > 0) {
                   8647:                                     $delcoowners = 1;
                   8648:                                     $coowners = '';
                   8649:                                 }
                   8650:                             }
                   8651:                         }
                   8652:                         if (@newcoowners || $delcoowners) {
                   8653:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8654:                                             $delcoowners,@newcoowners);
                   8655:                         }
                   8656:                     }
                   8657:                 }
                   8658:             }
                   8659:         }
                   8660:     }
                   8661: }
                   8662: 
                   8663: sub store_coowners {
                   8664:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8665:     my $cid = $cdom.'_'.$cnum;
                   8666:     my ($coowners,$delresult,$putresult);
                   8667:     if (@newcoowners) {
                   8668:         $coowners = join(',',@newcoowners);
                   8669:         my %coownershash = (
                   8670:                             'internal.co-owners' => $coowners,
                   8671:                            );
                   8672:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8673:         if ($putresult eq 'ok') {
                   8674:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8675:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8676:             }
                   8677:         }
                   8678:     }
                   8679:     if ($delcoowners) {
                   8680:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8681:         if ($delresult eq 'ok') {
                   8682:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8683:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8684:             }
                   8685:         }
                   8686:     }
                   8687:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8688:         my %crsinfo =
                   8689:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8690:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8691:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8692:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8693:         }
                   8694:     }
                   8695: }
                   8696: 
1.169     harris41 8697: # -------------------------------------------------- Modify user authentication
1.197     www      8698: # Overrides without validation
                   8699: 
1.169     harris41 8700: sub modifyuserauth {
                   8701:     my ($udom,$uname,$umode,$upass)=@_;
                   8702:     my $uhome=&homeserver($uname,$udom);
1.197     www      8703:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8704:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8705:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8706:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8707:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8708: 		     &escape($upass),$uhome);
1.620     albertel 8709:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8710:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8711:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8712:     &log($udom,,$uname,$uhome,
1.620     albertel 8713:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8714:                                      $env{'user.name'}.', '.$umode.
1.197     www      8715:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8716:     unless ($reply eq 'ok') {
1.197     www      8717:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8718: 	return 'error: '.$reply;
                   8719:     }   
1.170     harris41 8720:     return 'ok';
1.80      www      8721: }
                   8722: 
1.81      www      8723: # --------------------------------------------------------------- Modify a user
1.80      www      8724: 
1.81      www      8725: sub modifyuser {
1.206     matthew  8726:     my ($udom,    $uname, $uid,
                   8727:         $umode,   $upass, $first,
                   8728:         $middle,  $last,  $gene,
1.1058    raeburn  8729:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8730:     $udom= &LONCAPA::clean_domain($udom);
                   8731:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8732:     my $showcandelete = 'none';
                   8733:     if (ref($candelete) eq 'ARRAY') {
                   8734:         if (@{$candelete} > 0) {
                   8735:             $showcandelete = join(', ',@{$candelete});
                   8736:         }
                   8737:     }
1.81      www      8738:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8739:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8740: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8741:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8742:                                      ' desiredhome not specified'). 
1.620     albertel 8743:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8744:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8745:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8746:     my $newuser;
                   8747:     if ($uhome eq 'no_host') {
                   8748:         $newuser = 1;
                   8749:     }
1.80      www      8750: # ----------------------------------------------------------------- Create User
1.406     albertel 8751:     if (($uhome eq 'no_host') && 
                   8752: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8753:         my $unhome='';
1.844     albertel 8754:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8755:             $unhome = $desiredhome;
1.620     albertel 8756: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8757: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8758:         } else { # load balancing routine for determining $unhome
1.81      www      8759:             my $loadm=10000000;
1.841     albertel 8760: 	    my %servers = &get_servers($udom,'library');
                   8761: 	    foreach my $tryserver (keys(%servers)) {
                   8762: 		my $answer=reply('load',$tryserver);
                   8763: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8764: 		    $loadm=$answer;
                   8765: 		    $unhome=$tryserver;
                   8766: 		}
1.80      www      8767: 	    }
                   8768:         }
                   8769:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8770: 	    return 'error: unable to find a home server for '.$uname.
                   8771:                    ' in domain '.$udom;
1.80      www      8772:         }
                   8773:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8774:                          &escape($upass),$unhome);
                   8775: 	unless ($reply eq 'ok') {
                   8776:             return 'error: '.$reply;
                   8777:         }   
1.230     stredwic 8778:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8779:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8780: 	    return 'error: unable verify users home machine.';
1.80      www      8781:         }
1.209     matthew  8782:     }   # End of creation of new user
1.80      www      8783: # ---------------------------------------------------------------------- Add ID
                   8784:     if ($uid) {
                   8785:        $uid=~tr/A-Z/a-z/;
                   8786:        my %uidhash=&idrget($udom,$uname);
1.196     www      8787:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8788:          && (!$forceid)) {
1.80      www      8789: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8790: 	      return 'error: user id "'.$uid.'" does not match '.
                   8791:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8792:           }
                   8793:        } else {
                   8794: 	  &idput($udom,($uname => $uid));
                   8795:        }
                   8796:     }
                   8797: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8798:     my @tmp=&get('environment',
1.899     raeburn  8799: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8800:                     'permanentemail','inststatus'],
1.134     albertel 8801: 		   $udom,$uname);
1.1075    raeburn  8802:     my (%names,%oldnames);
1.313     matthew  8803:     if ($tmp[0] =~ m/^error:.*/) { 
                   8804:         %names=(); 
                   8805:     } else {
                   8806:         %names = @tmp;
1.1075    raeburn  8807:         %oldnames = %names;
1.313     matthew  8808:     }
1.388     www      8809: #
1.1058    raeburn  8810: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8811: # of users did not contain them), do not overwrite existing values
                   8812: # unless field is in $candelete array ref.  
                   8813: #
                   8814: 
                   8815:     my @fields = ('firstname','middlename','lastname','generation',
                   8816:                   'permanentemail','id');
                   8817:     my %newvalues;
                   8818:     if (ref($candelete) eq 'ARRAY') {
                   8819:         foreach my $field (@fields) {
                   8820:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8821:                 if ($field eq 'firstname') {
                   8822:                     $names{$field} = $first;
                   8823:                 } elsif ($field eq 'middlename') {
                   8824:                     $names{$field} = $middle;
                   8825:                 } elsif ($field eq 'lastname') {
                   8826:                     $names{$field} = $last;
                   8827:                 } elsif ($field eq 'generation') { 
                   8828:                     $names{$field} = $gene;
                   8829:                 } elsif ($field eq 'permanentemail') {
                   8830:                     $names{$field} = $email;
                   8831:                 } elsif ($field eq 'id') {
                   8832:                     $names{$field}  = $uid;
                   8833:                 }
                   8834:             }
                   8835:         }
                   8836:     }
1.388     www      8837:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8838:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8839:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8840:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8841:     if ($email) {
                   8842:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8843:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8844:     }
1.899     raeburn  8845:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8846:     if (defined($inststatus)) {
                   8847:         $names{'inststatus'} = '';
                   8848:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8849:         if (ref($usertypes) eq 'HASH') {
                   8850:             my @okstatuses; 
                   8851:             foreach my $item (split(/:/,$inststatus)) {
                   8852:                 if (defined($usertypes->{$item})) {
                   8853:                     push(@okstatuses,$item);  
                   8854:                 }
                   8855:             }
                   8856:             if (@okstatuses) {
                   8857:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8858:             }
                   8859:         }
                   8860:     }
1.1075    raeburn  8861:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8862:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8863:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8864:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8865:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8866:     } else {
                   8867:         $logmsg .= ' during self creation';
                   8868:     }
1.1075    raeburn  8869:     my $changed;
                   8870:     if ($newuser) {
                   8871:         $changed = 1;
                   8872:     } else {
                   8873:         foreach my $field (@fields) {
                   8874:             if ($names{$field} ne $oldnames{$field}) {
                   8875:                 $changed = 1;
                   8876:                 last;
                   8877:             }
                   8878:         }
                   8879:     }
                   8880:     unless ($changed) {
                   8881:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8882:         &logthis($logmsg);
                   8883:         return 'ok';
                   8884:     }
                   8885:     my $reply = &put('environment', \%names, $udom,$uname);
                   8886:     if ($reply ne 'ok') { 
                   8887:         return 'error: '.$reply;
                   8888:     }
1.1087    raeburn  8889:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8890:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8891:     }
1.1075    raeburn  8892:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8893:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8894:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8895:     &logthis($logmsg);
1.134     albertel 8896:     return 'ok';
1.80      www      8897: }
                   8898: 
1.81      www      8899: # -------------------------------------------------------------- Modify student
1.80      www      8900: 
1.81      www      8901: sub modifystudent {
                   8902:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8903:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216    raeburn  8904:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8905:     if (!$cid) {
1.620     albertel 8906: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8907: 	    return 'not_in_class';
                   8908: 	}
1.80      www      8909:     }
                   8910: # --------------------------------------------------------------- Make the user
1.81      www      8911:     my $reply=&modifyuser
1.209     matthew  8912: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8913:          $desiredhome,$email,$inststatus);
1.80      www      8914:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8915:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  8916:     # student's environment
1.297     matthew  8917:     $uid = undef if (!$forceid);
1.455     albertel 8918:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  8919:                                         $gene,$usec,$end,$start,$type,$locktype,
                   8920:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8921:     return $reply;
                   8922: }
                   8923: 
                   8924: sub modify_student_enrollment {
1.1216    raeburn  8925:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8926:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8927:     my ($cdom,$cnum,$chome);
                   8928:     if (!$cid) {
1.620     albertel 8929: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8930: 	    return 'not_in_class';
                   8931: 	}
1.620     albertel 8932: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8933: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8934:     } else {
                   8935: 	($cdom,$cnum)=split(/_/,$cid);
                   8936:     }
1.620     albertel 8937:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8938:     if (!$chome) {
1.457     raeburn  8939: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8940:     }
1.455     albertel 8941:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8942:     # Make sure the user exists
1.81      www      8943:     my $uhome=&homeserver($uname,$udom);
                   8944:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8945: 	return 'error: no such user';
                   8946:     }
1.297     matthew  8947:     # Get student data if we were not given enough information
                   8948:     if (!defined($first)  || $first  eq '' || 
                   8949:         !defined($last)   || $last   eq '' || 
                   8950:         !defined($uid)    || $uid    eq '' || 
                   8951:         !defined($middle) || $middle eq '' || 
                   8952:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8953:         # They did not supply us with enough data to enroll the student, so
                   8954:         # we need to pick up more information.
1.297     matthew  8955:         my %tmp = &get('environment',
1.294     matthew  8956:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8957:                        ,$udom,$uname);
                   8958: 
1.800     albertel 8959:         #foreach my $key (keys(%tmp)) {
                   8960:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8961:         #}
1.294     matthew  8962:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8963:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8964:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8965:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8966:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8967:     }
1.556     albertel 8968:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8969:     my $user = "$uname:$udom";
                   8970:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8971:     my $reply=cput('classlist',
1.1148    raeburn  8972: 		   {$user => 
1.1216    raeburn  8973: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8974: 		   $cdom,$cnum);
1.1148    raeburn  8975:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8976:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8977:     } else { 
1.81      www      8978: 	return 'error: '.$reply;
                   8979:     }
1.297     matthew  8980:     # Add student role to user
1.83      www      8981:     my $uurl='/'.$cid;
1.81      www      8982:     $uurl=~s/\_/\//g;
                   8983:     if ($usec) {
                   8984: 	$uurl.='/'.$usec;
                   8985:     }
1.1148    raeburn  8986:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8987:                              $selfenroll,$context);
                   8988:     if ($result ne 'ok') {
                   8989:         if ($old_entry{$user} ne '') {
                   8990:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8991:         } else {
                   8992:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8993:         }
                   8994:     }
                   8995:     return $result; 
1.21      www      8996: }
                   8997: 
1.556     albertel 8998: sub format_name {
                   8999:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9000:     my $name;
                   9001:     if ($first ne 'lastname') {
                   9002: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9003:     } else {
                   9004: 	if ($lastname=~/\S/) {
                   9005: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9006: 	    $name=~s/\s+,/,/;
                   9007: 	} else {
                   9008: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9009: 	}
                   9010:     }
                   9011:     $name=~s/^\s+//;
                   9012:     $name=~s/\s+$//;
                   9013:     $name=~s/\s+/ /g;
                   9014:     return $name;
                   9015: }
                   9016: 
1.84      www      9017: # ------------------------------------------------- Write to course preferences
                   9018: 
                   9019: sub writecoursepref {
                   9020:     my ($courseid,%prefs)=@_;
                   9021:     $courseid=~s/^\///;
                   9022:     $courseid=~s/\_/\//g;
                   9023:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9024:     my $chome=homeserver($cnum,$cdomain);
                   9025:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9026: 	return 'error: no such course';
                   9027:     }
                   9028:     my $cstring='';
1.800     albertel 9029:     foreach my $pref (keys(%prefs)) {
                   9030: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9031:     }
1.84      www      9032:     $cstring=~s/\&$//;
                   9033:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9034: }
                   9035: 
                   9036: # ---------------------------------------------------------- Make/modify course
                   9037: 
                   9038: sub createcourse {
1.741     raeburn  9039:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9040:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9041:     $url=&declutter($url);
                   9042:     my $cid='';
1.1028    raeburn  9043:     if ($context eq 'requestcourses') {
                   9044:         my $can_create = 0;
                   9045:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9046:         if ($udom eq $ownerdom) {
                   9047:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9048:                                   $context)) {
                   9049:                 $can_create = 1;
                   9050:             }
                   9051:         } else {
                   9052:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9053:                                            $category);
                   9054:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9055:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9056:                 if (@curr > 0) {
                   9057:                     my @options = qw(approval validate autolimit);
                   9058:                     my $optregex = join('|',@options);
                   9059:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9060:                         $can_create = 1;
                   9061:                     }
                   9062:                 }
                   9063:             }
                   9064:         }
                   9065:         if ($can_create) {
                   9066:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9067:                 unless (&allowed('ccc',$udom)) {
                   9068:                     return 'refused'; 
                   9069:                 }
1.1017    raeburn  9070:             }
                   9071:         } else {
                   9072:             return 'refused';
                   9073:         }
1.1028    raeburn  9074:     } elsif (!&allowed('ccc',$udom)) {
                   9075:         return 'refused';
1.84      www      9076:     }
1.1011    raeburn  9077: # --------------------------------------------------------------- Get Unique ID
                   9078:     my $uname;
                   9079:     if ($cnum =~ /^$match_courseid$/) {
                   9080:         my $chome=&homeserver($cnum,$udom,'true');
                   9081:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9082:             $uname = $cnum;
                   9083:         } else {
1.1038    raeburn  9084:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9085:         }
                   9086:     } else {
1.1038    raeburn  9087:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9088:     }
                   9089:     return $uname if ($uname =~ /^error/);
                   9090: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9091:     if (!defined($course_server)) {
                   9092:         if (defined(&domain($udom,'primary'))) {
                   9093:             $course_server = &domain($udom,'primary');
                   9094:         } else {
                   9095:             $course_server = $env{'user.home'}; 
                   9096:         }
                   9097:     }
                   9098:     my %host_servers =
                   9099:         &Apache::lonnet::get_servers($udom,'library');
                   9100:     unless ($host_servers{$course_server}) {
                   9101:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9102:     }
1.84      www      9103: # ------------------------------------------------------------- Make the course
                   9104:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9105:                       $course_server);
1.84      www      9106:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9107:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9108:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9109: 	return 'error: no such course';
                   9110:     }
1.271     www      9111: # ----------------------------------------------------------------- Course made
1.516     raeburn  9112: # log existence
1.1029    raeburn  9113:     my $now = time;
1.918     raeburn  9114:     my $newcourse = {
                   9115:                     $udom.'_'.$uname => {
1.921     raeburn  9116:                                      description => $description,
                   9117:                                      inst_code   => $inst_code,
                   9118:                                      owner       => $course_owner,
                   9119:                                      type        => $crstype,
1.1029    raeburn  9120:                                      creator     => $env{'user.name'}.':'.
                   9121:                                                     $env{'user.domain'},
                   9122:                                      created     => $now,
                   9123:                                      context     => $context,
1.918     raeburn  9124:                                                 },
                   9125:                     };
1.921     raeburn  9126:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9127: # set toplevel url
1.271     www      9128:     my $topurl=$url;
                   9129:     unless ($nonstandard) {
                   9130: # ------------------------------------------ For standard courses, make top url
                   9131:         my $mapurl=&clutter($url);
1.278     www      9132:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9133:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9134: <map>
                   9135: <resource id="1" type="start"></resource>
                   9136: <resource id="2" src="$mapurl"></resource>
                   9137: <resource id="3" type="finish"></resource>
                   9138: <link index="1" from="1" to="2"></link>
                   9139: <link index="2" from="2" to="3"></link>
                   9140: </map>
                   9141: ENDINITMAP
                   9142:         $topurl=&declutter(
1.638     albertel 9143:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9144:                           );
                   9145:     }
                   9146: # ----------------------------------------------------------- Write preferences
1.84      www      9147:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9148:                      ('description'              => $description,
                   9149:                       'url'                      => $topurl,
                   9150:                       'internal.creator'         => $env{'user.name'}.':'.
                   9151:                                                     $env{'user.domain'},
                   9152:                       'internal.created'         => $now,
                   9153:                       'internal.creationcontext' => $context)
                   9154:                     );
1.84      www      9155:     return '/'.$udom.'/'.$uname;
                   9156: }
                   9157: 
1.1011    raeburn  9158: # ------------------------------------------------------------------- Create ID
                   9159: sub generate_coursenum {
1.1038    raeburn  9160:     my ($udom,$crstype) = @_;
1.1011    raeburn  9161:     my $domdesc = &domain($udom);
                   9162:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9163:     my $first;
                   9164:     if ($crstype eq 'Community') {
                   9165:         $first = '0';
                   9166:     } else {
                   9167:         $first = int(1+rand(9)); 
                   9168:     } 
                   9169:     my $uname=$first.
1.1011    raeburn  9170:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9171:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9172:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9173: # ----------------------------------------------- Make sure that does not exist
                   9174:     my $uhome=&homeserver($uname,$udom,'true');
                   9175:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9176:         if ($crstype eq 'Community') {
                   9177:             $first = '0';
                   9178:         } else {
                   9179:             $first = int(1+rand(9));
                   9180:         }
                   9181:         $uname=$first.
1.1011    raeburn  9182:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9183:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9184:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9185:         $uhome=&homeserver($uname,$udom,'true');
                   9186:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9187:             return 'error: unable to generate unique course-ID';
                   9188:         }
                   9189:     }
                   9190:     return $uname;
                   9191: }
                   9192: 
1.813     albertel 9193: sub is_course {
1.1167    droeschl 9194:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9195:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9196: 
                   9197:     return unless $cdom and $cnum;
                   9198: 
                   9199:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9200:         '.');
                   9201: 
1.1219    raeburn  9202:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9203:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9204: }
                   9205: 
1.1015    raeburn  9206: sub store_userdata {
                   9207:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9208:     my $result;
1.1016    raeburn  9209:     if ($datakey ne '') {
1.1013    raeburn  9210:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9211:             if ($udom eq '' || $uname eq '') {
                   9212:                 $udom = $env{'user.domain'};
                   9213:                 $uname = $env{'user.name'};
                   9214:             }
                   9215:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9216:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9217:                 $result = 'error: no_host';
                   9218:             } else {
                   9219:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9220:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9221: 
                   9222:                 my $namevalue='';
                   9223:                 foreach my $key (keys(%{$storehash})) {
                   9224:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9225:                 }
                   9226:                 $namevalue=~s/\&$//;
1.1224    raeburn  9227:                 unless ($namespace eq 'courserequests') {
                   9228:                     $datakey = &escape($datakey);
                   9229:                 }
1.1105    raeburn  9230:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9231:                                   $namevalue,$uhome);
1.1013    raeburn  9232:             }
                   9233:         } else {
                   9234:             $result = 'error: data to store was not a hash reference'; 
                   9235:         }
                   9236:     } else {
                   9237:         $result= 'error: invalid requestkey'; 
                   9238:     }
                   9239:     return $result;
                   9240: }
                   9241: 
1.21      www      9242: # ---------------------------------------------------------- Assign Custom Role
                   9243: 
                   9244: sub assigncustomrole {
1.957     raeburn  9245:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9246:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9247:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9248: }
                   9249: 
                   9250: # ----------------------------------------------------------------- Revoke Role
                   9251: 
                   9252: sub revokerole {
1.957     raeburn  9253:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9254:     my $now=time;
1.965     raeburn  9255:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9256: }
                   9257: 
                   9258: # ---------------------------------------------------------- Revoke Custom Role
                   9259: 
                   9260: sub revokecustomrole {
1.957     raeburn  9261:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9262:     my $now=time;
1.357     www      9263:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9264:            $deleteflag,$selfenroll,$context);
1.17      www      9265: }
                   9266: 
1.533     banghart 9267: # ------------------------------------------------------------ Disk usage
1.535     albertel 9268: sub diskusage {
1.955     raeburn  9269:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9270:     $directorypath =~ s/\/$//;
                   9271:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9272:                        .&escape($getpropath).':'.&escape($uname).':'
                   9273:                        .&escape($udom),homeserver($uname,$udom));
                   9274:     if ($listing eq 'unknown_cmd') {
                   9275:         if ($getpropath) {
                   9276:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9277:         }
                   9278:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9279:     }
1.514     albertel 9280:     return $listing;
1.512     banghart 9281: }
                   9282: 
1.566     banghart 9283: sub is_locked {
1.1096    raeburn  9284:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9285:     my @check;
                   9286:     my $is_locked;
1.1093    raeburn  9287:     push (@check,$file_name);
1.613     albertel 9288:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9289: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9290:     my ($tmp)=keys(%locked);
                   9291:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9292:     
1.566     banghart 9293:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9294:         $is_locked = 'false';
                   9295:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9296:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9297:                $is_locked = 'true';
1.1096    raeburn  9298:                if (ref($which) eq 'ARRAY') {
                   9299:                    push(@{$which},$entry);
                   9300:                } else {
                   9301:                    last;
                   9302:                }
1.745     raeburn  9303:            }
                   9304:        }
1.566     banghart 9305:     } else {
                   9306:         $is_locked = 'false';
                   9307:     }
1.1093    raeburn  9308:     return $is_locked;
1.566     banghart 9309: }
                   9310: 
1.759     albertel 9311: sub declutter_portfile {
                   9312:     my ($file) = @_;
1.833     albertel 9313:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9314:     return $file;
                   9315: }
                   9316: 
1.559     banghart 9317: # ------------------------------------------------------------- Mark as Read Only
                   9318: 
                   9319: sub mark_as_readonly {
                   9320:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9321:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9322:     my ($tmp)=keys(%current_permissions);
                   9323:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9324:     foreach my $file (@{$files}) {
1.759     albertel 9325: 	$file = &declutter_portfile($file);
1.561     banghart 9326:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9327:     }
1.613     albertel 9328:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9329:     return;
                   9330: }
                   9331: 
1.572     banghart 9332: # ------------------------------------------------------------Save Selected Files
                   9333: 
                   9334: sub save_selected_files {
                   9335:     my ($user, $path, @files) = @_;
                   9336:     my $filename = $user."savedfiles";
1.573     banghart 9337:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9338:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9339:     foreach my $file (@files) {
1.620     albertel 9340:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9341:     }
                   9342:     foreach my $file (@other_files) {
1.574     banghart 9343:         print (OUT $file."\n");
1.572     banghart 9344:     }
1.574     banghart 9345:     close (OUT);
1.572     banghart 9346:     return 'ok';
                   9347: }
                   9348: 
1.574     banghart 9349: sub clear_selected_files {
                   9350:     my ($user) = @_;
                   9351:     my $filename = $user."savedfiles";
1.1117    foxr     9352:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9353:     print (OUT undef);
                   9354:     close (OUT);
                   9355:     return ("ok");    
                   9356: }
                   9357: 
1.572     banghart 9358: sub files_in_path {
                   9359:     my ($user, $path) = @_;
                   9360:     my $filename = $user."savedfiles";
                   9361:     my %return_files;
1.1117    foxr     9362:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9363:     while (my $line_in = <IN>) {
1.574     banghart 9364:         chomp ($line_in);
                   9365:         my @paths_and_file = split (m!/!, $line_in);
                   9366:         my $file_part = pop (@paths_and_file);
                   9367:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9368:         $path_part.='/';
                   9369:         my $path_and_file = $path_part.$file_part;
                   9370:         if ($path_part eq $path) {
                   9371:             $return_files{$file_part}= 'selected';
                   9372:         }
                   9373:     }
1.574     banghart 9374:     close (IN);
                   9375:     return (\%return_files);
1.572     banghart 9376: }
                   9377: 
                   9378: # called in portfolio select mode, to show files selected NOT in current directory
                   9379: sub files_not_in_path {
                   9380:     my ($user, $path) = @_;
                   9381:     my $filename = $user."savedfiles";
                   9382:     my @return_files;
                   9383:     my $path_part;
1.1117    foxr     9384:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9385:     while (my $line = <IN>) {
1.572     banghart 9386:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9387:         my @paths_and_file = split(m|/|, $line);
                   9388:         my $file_part = pop(@paths_and_file);
                   9389:         chomp($file_part);
                   9390:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9391:         $path_part .= '/';
                   9392:         my $path_and_file = $path_part.$file_part;
                   9393:         if ($path_part ne $path) {
1.800     albertel 9394:             push(@return_files, ($path_and_file));
1.572     banghart 9395:         }
                   9396:     }
1.800     albertel 9397:     close(OUT);
1.574     banghart 9398:     return (@return_files);
1.572     banghart 9399: }
                   9400: 
1.1273    raeburn  9401: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9402:  
                   9403: sub portfiles_versioning {
                   9404:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   9405:     my $portfolio_root = '/userfiles/portfolio';
                   9406:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   9407:     foreach my $file (@{$portfiles}) {
                   9408:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   9409:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   9410:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   9411:         my $getpropath = 1;
                   9412:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   9413:                                              $stu_name,$getpropath);
                   9414:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   9415:         my $new_answer = 
                   9416:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   9417:         if ($new_answer ne 'problem getting file') {
                   9418:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   9419:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   9420:                               [$symb,$env{'request.course.id'},'graded']);
                   9421:         }
                   9422:     }
                   9423: }
                   9424: 
                   9425: sub get_next_version {
                   9426:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   9427:     my $version;
                   9428:     if (ref($dir_list) eq 'ARRAY') {
                   9429:         foreach my $row (@{$dir_list}) {
                   9430:             my ($file) = split(/\&/,$row,2);
                   9431:             my ($file_name,$file_version,$file_ext) =
                   9432:                 &file_name_version_ext($file);
                   9433:             if (($file_name eq $answer_name) &&
                   9434:                 ($file_ext eq $answer_ext)) {
                   9435:                      # gets here if filename and extension match,
                   9436:                      # regardless of version
                   9437:                 if ($file_version ne '') {
                   9438:                     # a versioned file is found  so save it for later
                   9439:                     if ($file_version > $version) {
                   9440:                         $version = $file_version;
                   9441:                     }
                   9442:                 }
                   9443:             }
                   9444:         }
                   9445:     }
                   9446:     $version ++;
                   9447:     return($version);
                   9448: }
                   9449: 
                   9450: sub version_selected_portfile {
                   9451:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   9452:     my ($answer_name,$answer_ver,$answer_ext) =
                   9453:         &file_name_version_ext($file_name);
                   9454:     my $new_answer;
                   9455:     $env{'form.copy'} =
                   9456:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   9457:     if($env{'form.copy'} eq '-1') {
                   9458:         $new_answer = 'problem getting file';
                   9459:     } else {
                   9460:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   9461:         my $copy_result = 
                   9462:             &finishuserfileupload($stu_name,$domain,'copy',
                   9463:                                   '/portfolio'.$directory.$new_answer);
                   9464:     }
                   9465:     undef($env{'form.copy'});
                   9466:     return ($new_answer);
                   9467: }
                   9468: 
                   9469: sub file_name_version_ext {
                   9470:     my ($file)=@_;
                   9471:     my @file_parts = split(/\./, $file);
                   9472:     my ($name,$version,$ext);
                   9473:     if (@file_parts > 1) {
                   9474:         $ext=pop(@file_parts);
                   9475:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   9476:             $version=pop(@file_parts);
                   9477:         }
                   9478:         $name=join('.',@file_parts);
                   9479:     } else {
                   9480:         $name=join('.',@file_parts);
                   9481:     }
                   9482:     return($name,$version,$ext);
                   9483: }
                   9484: 
1.745     raeburn  9485: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9486: 
1.745     raeburn  9487: sub get_portfile_permissions {
                   9488:     my ($domain,$user) = @_;
1.613     albertel 9489:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9490:     my ($tmp)=keys(%current_permissions);
                   9491:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9492:     return \%current_permissions;
                   9493: }
                   9494: 
                   9495: #---------------------------------------------Get portfolio file access controls
                   9496: 
1.749     raeburn  9497: sub get_access_controls {
1.745     raeburn  9498:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9499:     my %access;
                   9500:     my $real_file = $file;
                   9501:     $file =~ s/\.meta$//;
1.745     raeburn  9502:     if (defined($file)) {
1.749     raeburn  9503:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9504:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9505:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9506:             }
                   9507:         }
1.745     raeburn  9508:     } else {
1.749     raeburn  9509:         foreach my $key (keys(%{$current_permissions})) {
                   9510:             if ($key =~ /\0accesscontrol$/) {
                   9511:                 if (defined($group)) {
                   9512:                     if ($key !~ m-^\Q$group\E/-) {
                   9513:                         next;
                   9514:                     }
                   9515:                 }
                   9516:                 my ($fullpath) = split(/\0/,$key);
                   9517:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9518:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9519:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9520:                     }
                   9521:                 }
                   9522:             }
                   9523:         }
                   9524:     }
                   9525:     return %access;
                   9526: }
                   9527: 
                   9528: sub modify_access_controls {
                   9529:     my ($file_name,$changes,$domain,$user)=@_;
                   9530:     my ($outcome,$deloutcome);
                   9531:     my %store_permissions;
                   9532:     my %new_values;
                   9533:     my %new_control;
                   9534:     my %translation;
                   9535:     my @deletions = ();
                   9536:     my $now = time;
                   9537:     if (exists($$changes{'activate'})) {
                   9538:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9539:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9540:             my $numnew = scalar(@newitems);
                   9541:             for (my $i=0; $i<$numnew; $i++) {
                   9542:                 my $newkey = $newitems[$i];
                   9543:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9544:                 if ($newkey =~ /^\d+:/) { 
                   9545:                     $newkey =~ s/^(\d+)/$newid/;
                   9546:                     $translation{$1} = $newid;
                   9547:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9548:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9549:                     $translation{$1} = $newid;
                   9550:                 }
1.749     raeburn  9551:                 $new_values{$file_name."\0".$newkey} = 
                   9552:                                           $$changes{'activate'}{$newitems[$i]};
                   9553:                 $new_control{$newkey} = $now;
                   9554:             }
                   9555:         }
                   9556:     }
                   9557:     my %todelete;
                   9558:     my %changed_items;
                   9559:     foreach my $action ('delete','update') {
                   9560:         if (exists($$changes{$action})) {
                   9561:             if (ref($$changes{$action}) eq 'HASH') {
                   9562:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9563:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9564:                     if ($action eq 'delete') { 
                   9565:                         $todelete{$itemnum} = 1;
                   9566:                     } else {
                   9567:                         $changed_items{$itemnum} = $key;
                   9568:                     }
                   9569:                 }
1.745     raeburn  9570:             }
                   9571:         }
1.749     raeburn  9572:     }
                   9573:     # get lock on access controls for file.
                   9574:     my $lockhash = {
                   9575:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9576:                                                        ':'.$env{'user.domain'},
                   9577:                    }; 
                   9578:     my $tries = 0;
                   9579:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9580:    
1.1288    damieng  9581:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  9582:         $tries ++;
1.1289    damieng  9583:         sleep(0.1);
1.749     raeburn  9584:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9585:     }
                   9586:     if ($gotlock eq 'ok') {
                   9587:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9588:         my ($tmp)=keys(%curr_permissions);
                   9589:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9590:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9591:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9592:             if (ref($curr_controls) eq 'HASH') {
                   9593:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9594:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9595:                     if (defined($todelete{$itemnum})) {
                   9596:                         push(@deletions,$file_name."\0".$control_item);
                   9597:                     } else {
                   9598:                         if (defined($changed_items{$itemnum})) {
                   9599:                             $new_control{$changed_items{$itemnum}} = $now;
                   9600:                             push(@deletions,$file_name."\0".$control_item);
                   9601:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9602:                         } else {
                   9603:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9604:                         }
                   9605:                     }
1.745     raeburn  9606:                 }
                   9607:             }
                   9608:         }
1.970     raeburn  9609:         my ($group);
                   9610:         if (&is_course($domain,$user)) {
                   9611:             ($group,my $file) = split(/\//,$file_name,2);
                   9612:         }
1.749     raeburn  9613:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9614:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9615:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9616:         #  remove lock
                   9617:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9618:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9619:         my $sqlresult =
1.970     raeburn  9620:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9621:                                     $group);
1.749     raeburn  9622:     } else {
                   9623:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9624:     }
1.749     raeburn  9625:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9626: }
                   9627: 
1.827     raeburn  9628: sub make_public_indefinitely {
1.1271    raeburn  9629:     my (@requrl) = @_;
                   9630:     return &automated_portfile_access('public',\@requrl);
                   9631: }
                   9632: 
                   9633: sub automated_portfile_access {
                   9634:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  9635:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   9636:         return 'invalid';
                   9637:     }
1.1271    raeburn  9638:     my %urls;
                   9639:     if (ref($addsref) eq 'ARRAY') {
                   9640:         foreach my $requrl (@{$addsref}) {
                   9641:             if (&is_portfolio_url($requrl)) {
                   9642:                 unless (exists($urls{$requrl})) {
                   9643:                     $urls{$requrl} = 'add';
                   9644:                 }
                   9645:             }
                   9646:         }
                   9647:     }
                   9648:     if (ref($delsref) eq 'ARRAY') {
                   9649:         foreach my $requrl (@{$delsref}) { 
                   9650:             if (&is_portfolio_url($requrl)) {
                   9651:                 unless (exists($urls{$requrl})) {
                   9652:                     $urls{$requrl} = 'delete'; 
                   9653:                 }
                   9654:             }
                   9655:         }
                   9656:     }
                   9657:     unless (keys(%urls)) {
                   9658:         return 'invalid';
                   9659:     }
                   9660:     my $ip;
                   9661:     if ($accesstype eq 'ip') {
                   9662:         if (ref($info) eq 'HASH') {
                   9663:             if ($info->{'ip'} ne '') {
                   9664:                 $ip = $info->{'ip'};
                   9665:             }
                   9666:         }
                   9667:         if ($ip eq '') {
                   9668:             return 'invalid';
                   9669:         }
                   9670:     }
                   9671:     my $errors;
1.827     raeburn  9672:     my $now = time;
1.1271    raeburn  9673:     my %current_perms;
                   9674:     foreach my $requrl (sort(keys(%urls))) {
                   9675:         my $action;
                   9676:         if ($urls{$requrl} eq 'add') {
                   9677:             $action = 'activate';
                   9678:         } else {
                   9679:             $action = 'none';
                   9680:         }
                   9681:         my $aclnum = 0;
1.827     raeburn  9682:         my (undef,$udom,$unum,$file_name,$group) =
                   9683:             &parse_portfolio_url($requrl);
1.1271    raeburn  9684:         unless (exists($current_perms{$unum.':'.$udom})) {
                   9685:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   9686:         }
                   9687:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  9688:                                                    $group,$file_name);
                   9689:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9690:             my ($num,$scope,$end,$start) = 
                   9691:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  9692:             if ($scope eq $accesstype) {
                   9693:                 if (($start <= $now) && ($end == 0)) {
                   9694:                     if ($accesstype eq 'ip') {
                   9695:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   9696:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   9697:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   9698:                                     if ($urls{$requrl} eq 'add') {
                   9699:                                         $action = 'none';
                   9700:                                         last;
                   9701:                                     } else {
                   9702:                                         $action = 'delete';
                   9703:                                         $aclnum = $num;
                   9704:                                         last;
                   9705:                                     }
                   9706:                                 }
                   9707:                             }
                   9708:                         }
                   9709:                     } elsif ($accesstype eq 'public') {
                   9710:                         if ($urls{$requrl} eq 'add') {
                   9711:                             $action = 'none';
                   9712:                             last;
                   9713:                         } else {
                   9714:                             $action = 'delete';
                   9715:                             $aclnum = $num;
                   9716:                             last;
                   9717:                         }
                   9718:                     }
                   9719:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  9720:                     $action = 'update';
                   9721:                     $aclnum = $num;
1.1271    raeburn  9722:                     last;
1.827     raeburn  9723:                 }
                   9724:             }
                   9725:         }
                   9726:         if ($action eq 'none') {
1.1271    raeburn  9727:             next;
1.827     raeburn  9728:         } else {
                   9729:             my %changes;
                   9730:             my $newend = 0;
                   9731:             my $newstart = $now;
1.1271    raeburn  9732:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  9733:             $changes{$action}{$newkey} = {
1.1271    raeburn  9734:                 type => $accesstype,
1.827     raeburn  9735:                 time => {
                   9736:                     start => $newstart,
                   9737:                     end   => $newend,
                   9738:                 },
                   9739:             };
1.1271    raeburn  9740:             if ($accesstype eq 'ip') {
                   9741:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   9742:             }
1.827     raeburn  9743:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9744:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  9745:             unless ($outcome eq 'ok') {
                   9746:                 $errors .= $outcome.' ';
                   9747:             }
1.827     raeburn  9748:         }
1.1271    raeburn  9749:     }
                   9750:     if ($errors) {
                   9751:         $errors =~ s/\s$//;
                   9752:         return $errors;
1.827     raeburn  9753:     } else {
1.1271    raeburn  9754:         return 'ok';
1.827     raeburn  9755:     }
                   9756: }
                   9757: 
1.745     raeburn  9758: #------------------------------------------------------Get Marked as Read Only
                   9759: 
                   9760: sub get_marked_as_readonly {
                   9761:     my ($domain,$user,$what,$group) = @_;
                   9762:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9763:     my @readonly_files;
1.629     banghart 9764:     my $cmp1=$what;
                   9765:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9766:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9767:         if (defined($group)) {
                   9768:             if ($file_name !~ m-^\Q$group\E/-) {
                   9769:                 next;
                   9770:             }
                   9771:         }
1.561     banghart 9772:         if (ref($value) eq "ARRAY"){
                   9773:             foreach my $stored_what (@{$value}) {
1.629     banghart 9774:                 my $cmp2=$stored_what;
1.759     albertel 9775:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9776:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9777:                 }
1.629     banghart 9778:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9779:                     push(@readonly_files, $file_name);
1.745     raeburn  9780:                     last;
1.563     banghart 9781:                 } elsif (!defined($what)) {
                   9782:                     push(@readonly_files, $file_name);
1.745     raeburn  9783:                     last;
1.561     banghart 9784:                 }
                   9785:             }
1.745     raeburn  9786:         }
1.561     banghart 9787:     }
                   9788:     return @readonly_files;
                   9789: }
1.577     banghart 9790: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9791: 
1.577     banghart 9792: sub get_marked_as_readonly_hash {
1.745     raeburn  9793:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9794:     my %readonly_files;
1.745     raeburn  9795:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9796:         if (defined($group)) {
                   9797:             if ($file_name !~ m-^\Q$group\E/-) {
                   9798:                 next;
                   9799:             }
                   9800:         }
1.577     banghart 9801:         if (ref($value) eq "ARRAY"){
                   9802:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9803:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9804:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9805:                         if ($lock_descriptor eq 'graded') {
                   9806:                             $readonly_files{$file_name} = 'graded';
                   9807:                         } elsif ($lock_descriptor eq 'handback') {
                   9808:                             $readonly_files{$file_name} = 'handback';
                   9809:                         } else {
                   9810:                             if (!exists($readonly_files{$file_name})) {
                   9811:                                 $readonly_files{$file_name} = 'locked';
                   9812:                             }
                   9813:                         }
1.745     raeburn  9814:                     }
1.750     banghart 9815:                 } 
1.577     banghart 9816:             }
                   9817:         } 
                   9818:     }
                   9819:     return %readonly_files;
                   9820: }
1.559     banghart 9821: # ------------------------------------------------------------ Unmark as Read Only
                   9822: 
                   9823: sub unmark_as_readonly {
1.629     banghart 9824:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9825:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9826:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9827:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9828:     my $symb_crs = $what;
                   9829:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9830:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9831:     my ($tmp)=keys(%current_permissions);
                   9832:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9833:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9834:     foreach my $file (@readonly_files) {
1.759     albertel 9835: 	my $clean_file = &declutter_portfile($file);
                   9836: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9837: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9838:         my @new_locks;
                   9839:         my @del_keys;
                   9840:         if (ref($current_locks) eq "ARRAY"){
                   9841:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9842:                 my $compare=$locker;
1.749     raeburn  9843:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9844:                     $compare=join('',@{$locker});
1.746     raeburn  9845:                     if ($compare ne $symb_crs) {
                   9846:                         push(@new_locks, $locker);
                   9847:                     }
1.563     banghart 9848:                 }
                   9849:             }
1.650     albertel 9850:             if (scalar(@new_locks) > 0) {
1.563     banghart 9851:                 $current_permissions{$file} = \@new_locks;
                   9852:             } else {
                   9853:                 push(@del_keys, $file);
1.613     albertel 9854:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9855:                 delete($current_permissions{$file});
1.563     banghart 9856:             }
                   9857:         }
1.561     banghart 9858:     }
1.613     albertel 9859:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9860:     return;
                   9861: }
1.512     banghart 9862: 
1.17      www      9863: # ------------------------------------------------------------ Directory lister
                   9864: 
                   9865: sub dirlist {
1.955     raeburn  9866:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9867:     $uri=~s/^\///;
                   9868:     $uri=~s/\/$//;
1.253     stredwic 9869:     my ($udom, $uname);
1.955     raeburn  9870:     if ($getuserdir) {
1.253     stredwic 9871:         $udom = $userdomain;
                   9872:         $uname = $username;
1.955     raeburn  9873:     } else {
                   9874:         (undef,$udom,$uname)=split(/\//,$uri);
                   9875:         if(defined($userdomain)) {
                   9876:             $udom = $userdomain;
                   9877:         }
                   9878:         if(defined($username)) {
                   9879:             $uname = $username;
                   9880:         }
1.253     stredwic 9881:     }
1.955     raeburn  9882:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9883: 
1.955     raeburn  9884:     $dirRoot = $perlvar{'lonDocRoot'};
                   9885:     if (defined($getpropath)) {
                   9886:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9887:         $dirRoot =~ s/\/$//;
1.955     raeburn  9888:     } elsif (defined($getuserdir)) {
                   9889:         my $subdir=$uname.'__';
                   9890:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9891:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9892:                    ."/$udom/$subdir/$uname";
                   9893:     } elsif (defined($alternateRoot)) {
                   9894:         $dirRoot = $alternateRoot;
1.751     banghart 9895:     }
1.253     stredwic 9896: 
                   9897:     if($udom) {
                   9898:         if($uname) {
1.1135    raeburn  9899:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9900:             if ($uhome eq 'no_host') {
                   9901:                 return ([],'no_host');
                   9902:             }
1.955     raeburn  9903:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9904:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9905:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9906:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9907:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9908:             } else {
                   9909:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9910:             }
1.605     matthew  9911:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9912:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9913:                 @listing_results = split(/:/,$listing);
                   9914:             } else {
                   9915:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9916:             }
1.1135    raeburn  9917:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9918:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9919:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9920:                 return ([],$listing);
                   9921:             } else {
                   9922:                 return (\@listing_results);
1.1135    raeburn  9923:             }
1.955     raeburn  9924:         } elsif(!$alternateRoot) {
1.1136    raeburn  9925:             my (%allusers,%listerror);
1.841     albertel 9926: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9927:  	    foreach my $tryserver (keys(%servers)) {
                   9928:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9929:                                   &escape($udom),$tryserver);
                   9930:                 if ($listing eq 'unknown_cmd') {
                   9931: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9932: 				      $udom, $tryserver);
                   9933:                 } else {
                   9934:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9935:                 }
1.841     albertel 9936: 		if ($listing eq 'unknown_cmd') {
                   9937: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9938: 				      $udom, $tryserver);
                   9939: 		    @listing_results = split(/:/,$listing);
                   9940: 		} else {
                   9941: 		    @listing_results =
                   9942: 			map { &unescape($_); } split(/:/,$listing);
                   9943: 		}
1.1136    raeburn  9944:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9945:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9946:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9947:                     $listerror{$tryserver} = $listing;
                   9948:                 } else {
1.841     albertel 9949: 		    foreach my $line (@listing_results) {
                   9950: 			my ($entry) = split(/&/,$line,2);
                   9951: 			$allusers{$entry} = 1;
                   9952: 		    }
                   9953: 		}
1.253     stredwic 9954:             }
1.1136    raeburn  9955:             my @alluserslist=();
1.800     albertel 9956:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9957:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9958:             }
1.1136    raeburn  9959:             return (\@alluserslist);
1.253     stredwic 9960:         } else {
1.1136    raeburn  9961:             return ([],'missing username');
1.253     stredwic 9962:         }
1.955     raeburn  9963:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9964:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9965:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9966:         return (\@all_domains);
1.955     raeburn  9967:     } else {
1.1136    raeburn  9968:         return ([],'missing domain');
1.275     stredwic 9969:     }
                   9970: }
                   9971: 
                   9972: # --------------------------------------------- GetFileTimestamp
                   9973: # This function utilizes dirlist and returns the date stamp for
                   9974: # when it was last modified.  It will also return an error of -1
                   9975: # if an error occurs
                   9976: 
                   9977: sub GetFileTimestamp {
1.955     raeburn  9978:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9979:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9980:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9981:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9982:                                     undef,$getuserdir);
                   9983:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9984:         return -1;
                   9985:     }
                   9986:     if (ref($fileref) eq 'ARRAY') {
                   9987:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9988:         # @stats contains first the filename, then the stat output
                   9989:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9990:     } else {
                   9991:         return -1;
1.253     stredwic 9992:     }
1.26      www      9993: }
                   9994: 
1.712     albertel 9995: sub stat_file {
                   9996:     my ($uri) = @_;
1.787     albertel 9997:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9998: 
1.955     raeburn  9999:     my ($udom,$uname,$file);
1.712     albertel 10000:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10001: 	($udom,$uname,$file) =
1.811     albertel 10002: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10003: 	$file = 'userfiles/'.$file;
                   10004:     }
                   10005:     if ($uri =~ m-^/res/-) {
                   10006: 	($udom,$uname) = 
1.807     albertel 10007: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10008: 	$file = $uri;
                   10009:     }
                   10010: 
                   10011:     if (!$udom || !$uname || !$file) {
                   10012: 	# unable to handle the uri
                   10013: 	return ();
                   10014:     }
1.956     raeburn  10015:     my $getpropath;
                   10016:     if ($file =~ /^userfiles\//) {
                   10017:         $getpropath = 1;
                   10018:     }
1.1136    raeburn  10019:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10020:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10021:         return ();
                   10022:     } else {
                   10023:         if (ref($listref) eq 'ARRAY') {
                   10024:             my @stats = split('&',$listref->[0]);
                   10025: 	    shift(@stats); #filename is first
                   10026: 	    return @stats;
                   10027:         }
1.712     albertel 10028:     }
                   10029:     return ();
                   10030: }
                   10031: 
1.26      www      10032: # -------------------------------------------------------- Value of a Condition
                   10033: 
1.713     albertel 10034: # gets the value of a specific preevaluated condition
                   10035: #    stored in the string  $env{user.state.<cid>}
                   10036: # or looks up a condition reference in the bighash and if if hasn't
                   10037: # already been evaluated recurses into docondval to get the value of
                   10038: # the condition, then memoizing it to 
                   10039: #   $env{user.state.<cid>.<condition>}
1.40      www      10040: sub directcondval {
                   10041:     my $number=shift;
1.620     albertel 10042:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10043: 	&Apache::lonuserstate::evalstate();
                   10044:     }
1.713     albertel 10045:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10046: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10047:     } elsif ($number =~ /^_/) {
                   10048: 	my $sub_condition;
                   10049: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10050: 		&GDBM_READER(),0640)) {
                   10051: 	    $sub_condition=$bighash{'conditions'.$number};
                   10052: 	    untie(%bighash);
                   10053: 	}
                   10054: 	my $value = &docondval($sub_condition);
1.949     raeburn  10055: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10056: 	return $value;
                   10057:     }
1.620     albertel 10058:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10059:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10060:     } else {
                   10061:        return 2;
                   10062:     }
                   10063: }
                   10064: 
1.713     albertel 10065: # get the collection of conditions for this resource
1.26      www      10066: sub condval {
                   10067:     my $condidx=shift;
1.54      www      10068:     my $allpathcond='';
1.713     albertel 10069:     foreach my $cond (split(/\|/,$condidx)) {
                   10070: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10071: 	    $allpathcond.=
                   10072: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10073: 	}
1.191     harris41 10074:     }
1.54      www      10075:     $allpathcond=~s/\|$//;
1.713     albertel 10076:     return &docondval($allpathcond);
                   10077: }
                   10078: 
                   10079: #evaluates an expression of conditions
                   10080: sub docondval {
                   10081:     my ($allpathcond) = @_;
                   10082:     my $result=0;
                   10083:     if ($env{'request.course.id'}
                   10084: 	&& defined($allpathcond)) {
                   10085: 	my $operand='|';
                   10086: 	my @stack;
                   10087: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10088: 	    if ($chunk eq '(') {
                   10089: 		push @stack,($operand,$result);
                   10090: 	    } elsif ($chunk eq ')') {
                   10091: 		my $before=pop @stack;
                   10092: 		if (pop @stack eq '&') {
                   10093: 		    $result=$result>$before?$before:$result;
                   10094: 		} else {
                   10095: 		    $result=$result>$before?$result:$before;
                   10096: 		}
                   10097: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10098: 		$operand=$chunk;
                   10099: 	    } else {
                   10100: 		my $new=directcondval($chunk);
                   10101: 		if ($operand eq '&') {
                   10102: 		    $result=$result>$new?$new:$result;
                   10103: 		} else {
                   10104: 		    $result=$result>$new?$result:$new;
                   10105: 		}
                   10106: 	    }
                   10107: 	}
1.26      www      10108:     }
                   10109:     return $result;
1.421     albertel 10110: }
                   10111: 
                   10112: # ---------------------------------------------------- Devalidate courseresdata
                   10113: 
                   10114: sub devalidatecourseresdata {
                   10115:     my ($coursenum,$coursedomain)=@_;
                   10116:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10117:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10118: }
                   10119: 
1.763     www      10120: 
1.200     www      10121: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10122: #
                   10123: #  Parameters:
                   10124: #      $coursenum    - Number of the course.
                   10125: #      $coursedomain - Domain at which the course was created.
                   10126: #  Returns:
                   10127: #     A hash of the course parameters along (I think) with timestamps
                   10128: #     and version info.
1.877     foxr     10129: 
1.624     albertel 10130: sub get_courseresdata {
                   10131:     my ($coursenum,$coursedomain)=@_;
1.200     www      10132:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10133:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10134:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10135:     my %dumpreply;
1.417     albertel 10136:     unless (defined($cached)) {
1.624     albertel 10137: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10138: 	$result=\%dumpreply;
1.251     albertel 10139: 	my ($tmp) = keys(%dumpreply);
                   10140: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10141: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10142: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10143: 	    return $tmp;
1.416     albertel 10144: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10145: 	    $result=undef;
1.599     albertel 10146: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10147: 	}
                   10148:     }
1.624     albertel 10149:     return $result;
                   10150: }
                   10151: 
1.633     albertel 10152: sub devalidateuserresdata {
                   10153:     my ($uname,$udom)=@_;
                   10154:     my $hashid="$udom:$uname";
                   10155:     &devalidate_cache_new('userres',$hashid);
                   10156: }
                   10157: 
1.624     albertel 10158: sub get_userresdata {
                   10159:     my ($uname,$udom)=@_;
                   10160:     #most student don\'t have any data set, check if there is some data
                   10161:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10162: 
                   10163:     my $hashid="$udom:$uname";
                   10164:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10165:     if (!defined($cached)) {
                   10166: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10167: 	$result=\%resourcedata;
                   10168: 	&do_cache_new('userres',$hashid,$result,600);
                   10169:     }
                   10170:     my ($tmp)=keys(%$result);
                   10171:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10172: 	return $result;
                   10173:     }
                   10174:     #error 2 occurs when the .db doesn't exist
                   10175:     if ($tmp!~/error: 2 /) {
1.672     albertel 10176: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 10177: 		 " Trying to get resource data for ".
                   10178: 		 $uname." at ".$udom.": ".
                   10179: 		 $tmp."</font>");
                   10180:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10181: 	#&EXT_cache_set($udom,$uname);
                   10182: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10183: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10184:     }
                   10185:     return $tmp;
                   10186: }
1.879     foxr     10187: #----------------------------------------------- resdata - return resource data
                   10188: #  Purpose:
                   10189: #    Return resource data for either users or for a course.
                   10190: #  Parameters:
                   10191: #     $name      - Course/user name.
                   10192: #     $domain    - Name of the domain the user/course is registered on.
                   10193: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   10194: #     @which     - Array of names of resources desired.
                   10195: #  Returns:
                   10196: #     The value of the first reasource in @which that is found in the
                   10197: #     resource hash.
                   10198: #  Exceptional Conditions:
                   10199: #     If the $type passed in is not valid (not the string 'course' or 
                   10200: #     'user', an undefined  reference is returned.
                   10201: #     If none of the resources are found, an undef is returned
1.624     albertel 10202: sub resdata {
                   10203:     my ($name,$domain,$type,@which)=@_;
                   10204:     my $result;
                   10205:     if ($type eq 'course') {
                   10206: 	$result=&get_courseresdata($name,$domain);
                   10207:     } elsif ($type eq 'user') {
                   10208: 	$result=&get_userresdata($name,$domain);
                   10209:     }
                   10210:     if (!ref($result)) { return $result; }    
1.251     albertel 10211:     foreach my $item (@which) {
1.927     albertel 10212: 	if (defined($result->{$item->[0]})) {
                   10213: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10214: 	}
1.250     albertel 10215:     }
1.291     albertel 10216:     return undef;
1.200     www      10217: }
                   10218: 
1.1236    raeburn  10219: sub get_numsuppfiles {
                   10220:     my ($cnum,$cdom,$ignorecache)=@_;
                   10221:     my $hashid=$cnum.':'.$cdom;
                   10222:     my ($suppcount,$cached);
                   10223:     unless ($ignorecache) {
                   10224:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10225:     }
                   10226:     unless (defined($cached)) {
                   10227:         my $chome=&homeserver($cnum,$cdom);
                   10228:         unless ($chome eq 'no_host') {
                   10229:             ($suppcount,my $errors) = (0,0);
                   10230:             my $suppmap = 'supplemental.sequence';
                   10231:             ($suppcount,$errors) = 
                   10232:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10233:         }
                   10234:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10235:     }
                   10236:     return $suppcount;
                   10237: }
                   10238: 
1.379     matthew  10239: #
                   10240: # EXT resource caching routines
                   10241: #
                   10242: 
                   10243: sub clear_EXT_cache_status {
1.383     albertel 10244:     &delenv('cache.EXT.');
1.379     matthew  10245: }
                   10246: 
                   10247: sub EXT_cache_status {
                   10248:     my ($target_domain,$target_user) = @_;
1.383     albertel 10249:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10250:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10251:         # We know already the user has no data
                   10252:         return 1;
                   10253:     } else {
                   10254:         return 0;
                   10255:     }
                   10256: }
                   10257: 
                   10258: sub EXT_cache_set {
                   10259:     my ($target_domain,$target_user) = @_;
1.383     albertel 10260:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10261:     #&appenv({$cachename => time});
1.379     matthew  10262: }
                   10263: 
1.28      www      10264: # --------------------------------------------------------- Value of a Variable
1.58      www      10265: sub EXT {
1.715     albertel 10266: 
1.1228    raeburn  10267:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10268:     unless ($varname) { return ''; }
1.218     albertel 10269:     #get real user name/domain, courseid and symb
                   10270:     my $courseid;
1.359     albertel 10271:     my $publicuser;
1.427     www      10272:     if ($symbparm) {
                   10273: 	$symbparm=&get_symb_from_alias($symbparm);
                   10274:     }
1.218     albertel 10275:     if (!($uname && $udom)) {
1.790     albertel 10276:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10277:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10278:     } else {
1.620     albertel 10279: 	$courseid=$env{'request.course.id'};
1.218     albertel 10280:     }
1.48      www      10281:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10282:     my $rest;
1.320     albertel 10283:     if (defined($therest[0])) {
1.48      www      10284:        $rest=join('.',@therest);
                   10285:     } else {
                   10286:        $rest='';
                   10287:     }
1.320     albertel 10288: 
1.57      www      10289:     my $qualifierrest=$qualifier;
                   10290:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10291:     my $spacequalifierrest=$space;
                   10292:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10293:     if ($realm eq 'user') {
1.48      www      10294: # --------------------------------------------------------------- user.resource
                   10295: 	if ($space eq 'resource') {
1.651     albertel 10296: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10297: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10298: 		 &&
1.744     albertel 10299: 		 ($symbparm eq &symbread()) ) {	
                   10300: 		# if we are in the middle of processing the resource the
                   10301: 		# get the value we are planning on committing
                   10302:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10303:                     return $Apache::lonhomework::results{$qualifierrest};
                   10304:                 } else {
                   10305:                     return $Apache::lonhomework::history{$qualifierrest};
                   10306:                 }
1.335     albertel 10307: 	    } else {
1.359     albertel 10308: 		my %restored;
1.620     albertel 10309: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10310: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10311: 		} else {
                   10312: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10313: 		}
1.335     albertel 10314: 		return $restored{$qualifierrest};
                   10315: 	    }
1.48      www      10316: # ----------------------------------------------------------------- user.access
                   10317:         } elsif ($space eq 'access') {
1.218     albertel 10318: 	    # FIXME - not supporting calls for a specific user
1.48      www      10319:             return &allowed($qualifier,$rest);
                   10320: # ------------------------------------------ user.preferences, user.environment
                   10321:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10322: 	    if (($uname eq $env{'user.name'}) &&
                   10323: 		($udom eq $env{'user.domain'})) {
                   10324: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10325: 	    } else {
1.359     albertel 10326: 		my %returnhash;
                   10327: 		if (!$publicuser) {
                   10328: 		    %returnhash=&userenvironment($udom,$uname,
                   10329: 						 $qualifierrest);
                   10330: 		}
1.218     albertel 10331: 		return $returnhash{$qualifierrest};
                   10332: 	    }
1.48      www      10333: # ----------------------------------------------------------------- user.course
                   10334:         } elsif ($space eq 'course') {
1.218     albertel 10335: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10336:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10337: # ------------------------------------------------------------------- user.role
                   10338:         } elsif ($space eq 'role') {
1.218     albertel 10339: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10340:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10341:             if ($qualifier eq 'value') {
                   10342: 		return $role;
                   10343:             } elsif ($qualifier eq 'extent') {
                   10344:                 return $where;
                   10345:             }
                   10346: # ----------------------------------------------------------------- user.domain
                   10347:         } elsif ($space eq 'domain') {
1.218     albertel 10348:             return $udom;
1.48      www      10349: # ------------------------------------------------------------------- user.name
                   10350:         } elsif ($space eq 'name') {
1.218     albertel 10351:             return $uname;
1.48      www      10352: # ---------------------------------------------------- Any other user namespace
1.29      www      10353:         } else {
1.359     albertel 10354: 	    my %reply;
                   10355: 	    if (!$publicuser) {
                   10356: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10357: 	    }
                   10358: 	    return $reply{$qualifierrest};
1.48      www      10359:         }
1.236     www      10360:     } elsif ($realm eq 'query') {
                   10361: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10362:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10363: 						[$spacequalifierrest]);
1.620     albertel 10364: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10365:    } elsif ($realm eq 'request') {
1.48      www      10366: # ------------------------------------------------------------- request.browser
                   10367:         if ($space eq 'browser') {
1.1145    bisitz   10368:             return $env{'browser.'.$qualifier};
1.57      www      10369: # ------------------------------------------------------------ request.filename
                   10370:         } else {
1.620     albertel 10371:             return $env{'request.'.$spacequalifierrest};
1.29      www      10372:         }
1.28      www      10373:     } elsif ($realm eq 'course') {
1.48      www      10374: # ---------------------------------------------------------- course.description
1.620     albertel 10375:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10376:     } elsif ($realm eq 'resource') {
1.165     www      10377: 
1.620     albertel 10378: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10379: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10380: 	}
1.693     albertel 10381: 
1.1232    raeburn  10382:         if ($qualifier eq '') {
                   10383: 	    if ($space eq 'title') {
                   10384: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10385: 	        return &gettitle($symbparm);
                   10386: 	    }
1.693     albertel 10387: 	
1.1232    raeburn  10388: 	    if ($space eq 'map') {
                   10389: 	        my ($map) = &decode_symb($symbparm);
                   10390: 	        return &symbread($map);
                   10391: 	    }
                   10392:             if ($space eq 'maptitle') {
                   10393:                 my ($map) = &decode_symb($symbparm);
                   10394:                 return &gettitle($map);
                   10395:             }
                   10396: 	    if ($space eq 'filename') {
                   10397: 	        if ($symbparm) {
                   10398: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10399: 	        }
                   10400: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10401: 	    }
1.1232    raeburn  10402: 
1.1233    raeburn  10403:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10404:                 if ($space eq 'visibleparts') {
                   10405:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10406:                     my $item;
                   10407:                     if (ref($navmap)) {
                   10408:                         my $res = $navmap->getBySymb($symbparm);
                   10409:                         my $parts = $res->parts();
                   10410:                         if (ref($parts) eq 'ARRAY') {
                   10411:                             $item = join(',',@{$parts});
                   10412:                         }
                   10413:                         undef($navmap);
1.1232    raeburn  10414:                     }
1.1233    raeburn  10415:                     return $item;
1.1232    raeburn  10416:                 }
                   10417:             }
                   10418:         }
1.693     albertel 10419: 
                   10420: 	my ($section, $group, @groups);
1.593     albertel 10421: 	my ($courselevelm,$courselevel);
1.1228    raeburn  10422:         if (($courseid eq '') && ($cid)) {
                   10423:             $courseid = $cid;
                   10424:         }
                   10425: 	if (($symbparm && $courseid) && 
                   10426: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      10427: 
1.218     albertel 10428: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10429: 
1.60      www      10430: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10431: 	    my $symbp=$symbparm;
1.735     albertel 10432: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10433: 
                   10434: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10435: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10436: 
1.620     albertel 10437: 	    if (($env{'user.name'} eq $uname) &&
                   10438: 		($env{'user.domain'} eq $udom)) {
                   10439: 		$section=$env{'request.course.sec'};
1.733     raeburn  10440:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10441:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10442: 	    } else {
1.539     albertel 10443: 		if (! defined($usection)) {
1.551     albertel 10444: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10445: 		} else {
                   10446: 		    $section = $usection;
                   10447: 		}
1.733     raeburn  10448:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10449: 	    }
                   10450: 
                   10451: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10452: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10453: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10454: 
1.593     albertel 10455: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10456: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10457: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10458: 
1.60      www      10459: # ----------------------------------------------------------- first, check user
1.624     albertel 10460: 
                   10461: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10462: 				       ([$courselevelr,'resource'],
                   10463: 					[$courselevelm,'map'     ],
                   10464: 					[$courselevel, 'course'  ]));
1.931     albertel 10465: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10466: 
1.594     albertel 10467: # ------------------------------------------------ second, check some of course
1.684     raeburn  10468:             my $coursereply;
1.691     raeburn  10469:             if (@groups > 0) {
                   10470:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10471:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10472:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10473:             }
1.96      www      10474: 
1.684     raeburn  10475: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10476: 				  $env{'course.'.$courseid.'.domain'},
                   10477: 				  'course',
                   10478: 				  ([$seclevelr,   'resource'],
                   10479: 				   [$seclevelm,   'map'     ],
                   10480: 				   [$seclevel,    'course'  ],
                   10481: 				   [$courselevelr,'resource']));
                   10482: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10483: 
1.60      www      10484: # ------------------------------------------------------ third, check map parms
1.218     albertel 10485: 	    my %parmhash=();
                   10486: 	    my $thisparm='';
                   10487: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10488: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10489: 		    &GDBM_READER(),0640)) {
1.218     albertel 10490: 		$thisparm=$parmhash{$symbparm};
                   10491: 		untie(%parmhash);
                   10492: 	    }
1.927     albertel 10493: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10494: 	}
1.594     albertel 10495: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10496: 
1.218     albertel 10497: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10498: 	my $filename;
                   10499: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10500: 	if ($symbparm) {
1.409     www      10501: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10502: 	} else {
1.620     albertel 10503: 	    $filename=$env{'request.filename'};
1.282     albertel 10504: 	}
                   10505: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10506: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10507: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10508: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10509: 
1.927     albertel 10510: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10511: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10512: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10513: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10514: 				     $env{'course.'.$courseid.'.domain'},
                   10515: 				     'course',
1.927     albertel 10516: 				     ([$courselevelm,'map'   ],
                   10517: 				      [$courselevel, 'course']));
                   10518: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10519: 	}
1.145     www      10520: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10521: 	unless ($space eq '0') {
1.336     albertel 10522: 	    my @parts=split(/_/,$space);
                   10523: 	    my $id=pop(@parts);
                   10524: 	    my $part=join('_',@parts);
                   10525: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10526: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10527: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10528: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10529: 	}
1.395     albertel 10530: 	if ($recurse) { return undef; }
                   10531: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10532: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10533: # ---------------------------------------------------- Any other user namespace
                   10534:     } elsif ($realm eq 'environment') {
                   10535: # ----------------------------------------------------------------- environment
1.620     albertel 10536: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10537: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10538: 	} else {
1.770     albertel 10539: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10540: 		return '';
                   10541: 	    }
1.219     albertel 10542: 	    my %returnhash=&userenvironment($udom,$uname,
                   10543: 					    $spacequalifierrest);
                   10544: 	    return $returnhash{$spacequalifierrest};
                   10545: 	}
1.28      www      10546:     } elsif ($realm eq 'system') {
1.48      www      10547: # ----------------------------------------------------------------- system.time
                   10548: 	if ($space eq 'time') {
                   10549: 	    return time;
                   10550:         }
1.696     albertel 10551:     } elsif ($realm eq 'server') {
                   10552: # ----------------------------------------------------------------- system.time
                   10553: 	if ($space eq 'name') {
                   10554: 	    return $ENV{'SERVER_NAME'};
                   10555:         }
1.28      www      10556:     }
1.48      www      10557:     return '';
1.61      www      10558: }
                   10559: 
1.927     albertel 10560: sub get_reply {
                   10561:     my ($reply_value) = @_;
1.940     raeburn  10562:     if (ref($reply_value) eq 'ARRAY') {
                   10563:         if (wantarray) {
                   10564: 	    return @$reply_value;
                   10565:         }
                   10566:         return $reply_value->[0];
                   10567:     } else {
                   10568:         return $reply_value;
1.927     albertel 10569:     }
                   10570: }
                   10571: 
1.691     raeburn  10572: sub check_group_parms {
                   10573:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10574:     my @groupitems = ();
                   10575:     my $resultitem;
1.927     albertel 10576:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10577:     foreach my $group (@{$groups}) {
                   10578:         foreach my $level (@levels) {
1.927     albertel 10579:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10580:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10581:         }
                   10582:     }
                   10583:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10584:                             $env{'course.'.$courseid.'.domain'},
                   10585:                                      'course',@groupitems);
                   10586:     return $coursereply;
                   10587: }
                   10588: 
                   10589: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10590:     my ($courseid,@groups) = @_;
                   10591:     @groups = sort(@groups);
1.691     raeburn  10592:     return @groups;
                   10593: }
                   10594: 
1.395     albertel 10595: sub packages_tab_default {
                   10596:     my ($uri,$varname)=@_;
                   10597:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10598: 
                   10599:     my (@extension,@specifics,$do_default);
                   10600:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10601: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10602: 	if ($pack_type eq 'default') {
                   10603: 	    $do_default=1;
                   10604: 	} elsif ($pack_type eq 'extension') {
                   10605: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10606: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10607: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10608: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10609: 	}
                   10610:     }
                   10611:     # first look for a package that matches the requested part id
                   10612:     foreach my $package (@specifics) {
                   10613: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10614: 	next if ($pack_part ne $part);
                   10615: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10616: 	    return $packagetab{"$pack_type&$name&default"};
                   10617: 	}
                   10618:     }
                   10619:     # look for any possible matching non extension_ package
                   10620:     foreach my $package (@specifics) {
                   10621: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10622: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10623: 	    return $packagetab{"$pack_type&$name&default"};
                   10624: 	}
1.585     albertel 10625: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10626: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10627: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10628: 	}
                   10629:     }
1.738     albertel 10630:     # look for any posible extension_ match
                   10631:     foreach my $package (@extension) {
                   10632: 	my ($package,$pack_type)=@{$package};
                   10633: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10634: 	    return $packagetab{"$pack_type&$name&default"};
                   10635: 	}
                   10636: 	if (defined($packagetab{$package."&$name&default"})) {
                   10637: 	    return $packagetab{$package."&$name&default"};
                   10638: 	}
                   10639:     }
                   10640:     # look for a global default setting
                   10641:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10642: 	return $packagetab{"default&$name&default"};
                   10643:     }
1.395     albertel 10644:     return undef;
                   10645: }
                   10646: 
1.334     albertel 10647: sub add_prefix_and_part {
                   10648:     my ($prefix,$part)=@_;
                   10649:     my $keyroot;
                   10650:     if (defined($prefix) && $prefix !~ /^__/) {
                   10651: 	# prefix that has a part already
                   10652: 	$keyroot=$prefix;
                   10653:     } elsif (defined($prefix)) {
                   10654: 	# prefix that is missing a part
                   10655: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10656:     } else {
                   10657: 	# no prefix at all
                   10658: 	if (defined($part)) { $keyroot='_'.$part; }
                   10659:     }
                   10660:     return $keyroot;
                   10661: }
                   10662: 
1.71      www      10663: # ---------------------------------------------------------------- Get metadata
                   10664: 
1.599     albertel 10665: my %metaentry;
1.1070    www      10666: my %importedpartids;
1.71      www      10667: sub metadata {
1.176     www      10668:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10669:     $uri=&declutter($uri);
1.288     albertel 10670:     # if it is a non metadata possible uri return quickly
1.529     albertel 10671:     if (($uri eq '') || 
                   10672: 	(($uri =~ m|^/*adm/|) && 
1.1217    raeburn  10673: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10674:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10675: 	return undef;
                   10676:     }
1.1261    raeburn  10677:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10678: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10679: 	return undef;
1.288     albertel 10680:     }
1.73      www      10681:     my $filename=$uri;
                   10682:     $uri=~s/\.meta$//;
1.172     www      10683: #
                   10684: # Is the metadata already cached?
1.177     www      10685: # Look at timestamp of caching
1.172     www      10686: # Everything is cached by the main uri, libraries are never directly cached
                   10687: #
1.428     albertel 10688:     if (!defined($liburi)) {
1.599     albertel 10689: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10690: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10691:     }
                   10692:     {
1.1069    www      10693: # Imported parts would go here
1.1070    www      10694:         my %importedids=();
                   10695:         my @origfileimportpartids=();
1.1069    www      10696:         my $importedparts=0;
1.172     www      10697: #
                   10698: # Is this a recursive call for a library?
                   10699: #
1.599     albertel 10700: #	if (! exists($metacache{$uri})) {
                   10701: #	    $metacache{$uri}={};
                   10702: #	}
1.924     albertel 10703: 	my $cachetime = 60*60;
1.171     www      10704:         if ($liburi) {
                   10705: 	    $liburi=&declutter($liburi);
                   10706:             $filename=$liburi;
1.401     bowersj2 10707:         } else {
1.599     albertel 10708: 	    &devalidate_cache_new('meta',$uri);
                   10709: 	    undef(%metaentry);
1.401     bowersj2 10710: 	}
1.140     www      10711:         my %metathesekeys=();
1.73      www      10712:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10713: 	my $metastring;
1.1140    www      10714: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10715: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10716: 	    $metastring = 
1.929     albertel 10717: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10718: 					  ('grade_target' => 'meta'));
                   10719: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10720: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10721:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10722: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10723: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10724: 	    $metastring=&getfile($file);
1.489     albertel 10725: 	}
1.208     albertel 10726:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10727:         my $token;
1.140     www      10728:         undef %metathesekeys;
1.71      www      10729:         while ($token=$parser->get_token) {
1.339     albertel 10730: 	    if ($token->[0] eq 'S') {
                   10731: 		if (defined($token->[2]->{'package'})) {
1.172     www      10732: #
                   10733: # This is a package - get package info
                   10734: #
1.339     albertel 10735: 		    my $package=$token->[2]->{'package'};
                   10736: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10737: 		    if (defined($token->[2]->{'id'})) { 
                   10738: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10739: 		    }
1.599     albertel 10740: 		    if ($metaentry{':packages'}) {
                   10741: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10742: 		    } else {
1.599     albertel 10743: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10744: 		    }
1.736     albertel 10745: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10746: 			my $part=$keyroot;
                   10747: 			$part=~s/^\_//;
1.736     albertel 10748: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10749: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10750: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10751: 			    # ignore package.tab specified default values
                   10752:                             # here &package_tab_default() will fetch those
                   10753: 			    if ($subp eq 'default') { next; }
1.736     albertel 10754: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10755: 			    my $unikey;
                   10756: 			    if ($pack =~ /_0$/) {
                   10757: 				$unikey='parameter_0_'.$name;
                   10758: 				$part=0;
                   10759: 			    } else {
                   10760: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10761: 			    }
1.339     albertel 10762: 			    if ($subp eq 'display') {
                   10763: 				$value.=' [Part: '.$part.']';
                   10764: 			    }
1.599     albertel 10765: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10766: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10767: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10768: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10769: 			    }
1.599     albertel 10770: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10771: 				$metaentry{':'.$unikey}=
                   10772: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10773: 			    }
1.339     albertel 10774: 			}
                   10775: 		    }
                   10776: 		} else {
1.172     www      10777: #
                   10778: # This is not a package - some other kind of start tag
1.339     albertel 10779: #
                   10780: 		    my $entry=$token->[1];
1.1068    www      10781: 		    my $unikey='';
1.175     www      10782: 
1.339     albertel 10783: 		    if ($entry eq 'import') {
1.175     www      10784: #
                   10785: # Importing a library here
1.339     albertel 10786: #
1.1067    www      10787:                         my $location=$parser->get_text('/import');
                   10788:                         my $dir=$filename;
                   10789:                         $dir=~s|[^/]*$||;
                   10790:                         $location=&filelocation($dir,$location);
1.1069    www      10791:                        
1.1068    www      10792:                         my $importmode=$token->[2]->{'importmode'};
                   10793:                         if ($importmode eq 'problem') {
1.1069    www      10794: # Import as problem/response
1.1068    www      10795:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10796:                         } elsif ($importmode eq 'part') {
                   10797: # Import as part(s)
1.1069    www      10798:                            $importedparts=1;
                   10799: # We need to get the original file and the imported file to get the part order correct
                   10800: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10801: # Load and inspect original file
1.1070    www      10802:                            if ($#origfileimportpartids<0) {
                   10803:                               undef(%importedpartids);
                   10804:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10805:                               my $origfile=&getfile($origfilelocation);
                   10806:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10807:                            }
                   10808: 
1.1069    www      10809: # Load and inspect imported file
                   10810:                            my $impfile=&getfile($location);
                   10811:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10812:                            if ($#impfilepartids>=0) {
                   10813: # This problem had parts
1.1070    www      10814:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10815:                            } else {
                   10816: # Importing by turning a single problem into a problem part
                   10817: # It gets the import-tags ID as part-ID
                   10818:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10819:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10820:                            }
1.1068    www      10821:                         } else {
                   10822: # Normal import
                   10823:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10824:                            if (defined($token->[2]->{'id'})) {
                   10825:                               $unikey.='_'.$token->[2]->{'id'};
                   10826:                            }
1.1067    www      10827:                         }
                   10828: 
1.339     albertel 10829: 			if ($depthcount<20) {
1.736     albertel 10830: 			    my $metadata = 
                   10831: 				&metadata($uri,'keys', $location,$unikey,
                   10832: 					  $depthcount+1);
                   10833: 			    foreach my $meta (split(',',$metadata)) {
                   10834: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10835: 				$metathesekeys{$meta}=1;
1.339     albertel 10836: 			    }
1.1068    www      10837: 			
                   10838:                         }
1.1067    www      10839: 		    } else {
                   10840: #
                   10841: # Not importing, some other kind of non-package, non-library start tag
                   10842: # 
                   10843:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10844:                         if (defined($token->[2]->{'id'})) {
                   10845:                             $unikey.='_'.$token->[2]->{'id'};
                   10846:                         }
1.339     albertel 10847: 			if (defined($token->[2]->{'name'})) { 
                   10848: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10849: 			}
                   10850: 			$metathesekeys{$unikey}=1;
1.736     albertel 10851: 			foreach my $param (@{$token->[3]}) {
                   10852: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10853: 				$token->[2]->{$param};
1.339     albertel 10854: 			}
                   10855: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10856: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10857: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10858: 		 # only ws inside the tag, and not in default, so use default
                   10859: 		 # as value
1.599     albertel 10860: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10861: 			} elsif ( $internaltext =~ /\S/ ) {
                   10862: 		  # something interesting inside the tag
                   10863: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10864: 			} else {
1.908     albertel 10865: 		  # no interesting values, don't set a default
1.339     albertel 10866: 			}
1.172     www      10867: # end of not-a-package not-a-library import
1.339     albertel 10868: 		    }
1.172     www      10869: # end of not-a-package start tag
1.339     albertel 10870: 		}
1.172     www      10871: # the next is the end of "start tag"
1.339     albertel 10872: 	    }
                   10873: 	}
1.483     albertel 10874: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10875: 	$extension = lc($extension);
                   10876: 	if ($extension eq 'htm') { $extension='html'; }
                   10877: 
1.737     albertel 10878: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10879: 	    #no specific packages #how's our extension
                   10880: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10881: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10882: 					 \%metathesekeys);
                   10883: 	}
1.883     albertel 10884: 
                   10885: 	if (!exists($metaentry{':packages'})
                   10886: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10887: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10888: 		#no specific packages well let's get default then
                   10889: 		if ($key!~/^default&/) { next; }
1.488     albertel 10890: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10891: 					     \%metathesekeys);
                   10892: 	    }
                   10893: 	}
1.338     www      10894: # are there custom rights to evaluate
1.599     albertel 10895: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10896: 
1.338     www      10897:     #
                   10898:     # Importing a rights file here
1.339     albertel 10899:     #
                   10900: 	    unless ($depthcount) {
1.599     albertel 10901: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10902: 		my $dir=$filename;
                   10903: 		$dir=~s|[^/]*$||;
                   10904: 		$location=&filelocation($dir,$location);
1.736     albertel 10905: 		my $rights_metadata =
                   10906: 		    &metadata($uri,'keys',$location,'_rights',
                   10907: 			      $depthcount+1);
                   10908: 		foreach my $rights (split(',',$rights_metadata)) {
                   10909: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10910: 		    $metathesekeys{$rights}=1;
1.339     albertel 10911: 		}
                   10912: 	    }
                   10913: 	}
1.737     albertel 10914: 	# uniqifiy package listing
                   10915: 	my %seen;
                   10916: 	my @uniq_packages =
                   10917: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10918: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10919: 
1.1070    www      10920:         if ($importedparts) {
                   10921: # We had imported parts and need to rebuild partorder
                   10922:            $metaentry{':partorder'}='';
                   10923:            $metathesekeys{'partorder'}=1;
                   10924:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10925:                if ($origfileimportpartids[$index] eq 'part') {
                   10926: # original part, part of the problem
                   10927:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10928:                } else {
                   10929: # we have imported parts at this position
                   10930:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10931:                }
                   10932:            }
                   10933:            $metaentry{':partorder'}=~s/^\,//;
                   10934:         }
                   10935: 
1.737     albertel 10936: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10937: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  10938: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 10939: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10940: # this is the end of "was not already recently cached
1.71      www      10941:     }
1.599     albertel 10942:     return $metaentry{':'.$what};
1.261     albertel 10943: }
                   10944: 
1.488     albertel 10945: sub metadata_create_package_def {
1.483     albertel 10946:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10947:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10948:     if ($subp eq 'default') { next; }
                   10949:     
1.599     albertel 10950:     if (defined($metaentry{':packages'})) {
                   10951: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10952:     } else {
1.599     albertel 10953: 	$metaentry{':packages'}=$package;
1.483     albertel 10954:     }
                   10955:     my $value=$packagetab{$key};
                   10956:     my $unikey;
                   10957:     $unikey='parameter_0_'.$name;
1.599     albertel 10958:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10959:     $$metathesekeys{$unikey}=1;
1.599     albertel 10960:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10961: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10962:     }
1.599     albertel 10963:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10964: 	$metaentry{':'.$unikey}=
                   10965: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10966:     }
                   10967: }
                   10968: 
1.261     albertel 10969: sub metadata_generate_part0 {
                   10970:     my ($metadata,$metacache,$uri) = @_;
                   10971:     my %allnames;
1.737     albertel 10972:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10973: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10974: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10975: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10976: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10977: 	    $allnames{$name}=$part;
                   10978: 	  }
                   10979: 	}
                   10980:     }
                   10981:     foreach my $name (keys(%allnames)) {
                   10982:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10983:       my $key=":parameter_0_$name";
1.261     albertel 10984:       $$metacache{"$key.part"}='0';
                   10985:       $$metacache{"$key.name"}=$name;
1.428     albertel 10986:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10987: 					   $allnames{$name}.'_'.$name.
                   10988: 					   '.type'};
1.428     albertel 10989:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10990: 			     '.display'};
1.644     www      10991:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10992:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10993:       $$metacache{"$key.display"}=$olddis;
                   10994:     }
1.71      www      10995: }
                   10996: 
1.764     albertel 10997: # ------------------------------------------------------ Devalidate title cache
                   10998: 
                   10999: sub devalidate_title_cache {
                   11000:     my ($url)=@_;
                   11001:     if (!$env{'request.course.id'}) { return; }
                   11002:     my $symb=&symbread($url);
                   11003:     if (!$symb) { return; }
                   11004:     my $key=$env{'request.course.id'}."\0".$symb;
                   11005:     &devalidate_cache_new('title',$key);
                   11006: }
                   11007: 
1.1014    droeschl 11008: # ------------------------------------------------- Get the title of a course
                   11009: 
                   11010: sub current_course_title {
                   11011:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11012: }
1.301     www      11013: # ------------------------------------------------- Get the title of a resource
                   11014: 
                   11015: sub gettitle {
                   11016:     my $urlsymb=shift;
                   11017:     my $symb=&symbread($urlsymb);
1.534     albertel 11018:     if ($symb) {
1.620     albertel 11019: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11020: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11021: 	if (defined($cached)) { 
                   11022: 	    return $result;
                   11023: 	}
1.534     albertel 11024: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11025: 	my $title='';
1.907     albertel 11026: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11027: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11028: 	} else {
                   11029: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11030: 		    &GDBM_READER(),0640)) {
                   11031: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11032: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11033: 		untie(%bighash);
                   11034: 	    }
1.534     albertel 11035: 	}
                   11036: 	$title=~s/\&colon\;/\:/gs;
                   11037: 	if ($title) {
1.1159    www      11038: # Remember both $symb and $title for dynamic metadata
                   11039:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11040:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11041: # Cache this title and then return it
1.599     albertel 11042: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11043: 	}
                   11044: 	$urlsymb=$url;
                   11045:     }
                   11046:     my $title=&metadata($urlsymb,'title');
                   11047:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11048:     return $title;
1.301     www      11049: }
1.613     albertel 11050: 
1.614     albertel 11051: sub get_slot {
                   11052:     my ($which,$cnum,$cdom)=@_;
                   11053:     if (!$cnum || !$cdom) {
1.790     albertel 11054: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11055: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11056: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11057:     }
1.703     albertel 11058:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11059:     my %slotinfo;
                   11060:     if (exists($remembered{$key})) {
                   11061: 	$slotinfo{$which} = $remembered{$key};
                   11062:     } else {
                   11063: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11064: 	&Apache::lonhomework::showhash(%slotinfo);
                   11065: 	my ($tmp)=keys(%slotinfo);
                   11066: 	if ($tmp=~/^error:/) { return (); }
                   11067: 	$remembered{$key} = $slotinfo{$which};
                   11068:     }
1.616     albertel 11069:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11070: 	return %{$slotinfo{$which}};
                   11071:     }
                   11072:     return $slotinfo{$which};
1.614     albertel 11073: }
1.1150    raeburn  11074: 
                   11075: sub get_reservable_slots {
                   11076:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11077:     my $now = time;
                   11078:     my $reservable_info;
                   11079:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11080:     if (exists($remembered{$key})) {
                   11081:         $reservable_info = $remembered{$key};
                   11082:     } else {
                   11083:         my %resv;
                   11084:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11085:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11086:         $reservable_info = \%resv;
                   11087:         $remembered{$key} = $reservable_info;
                   11088:     }
                   11089:     return $reservable_info;
                   11090: }
                   11091: 
                   11092: sub get_course_slots {
                   11093:     my ($cnum,$cdom) = @_;
                   11094:     my $hashid=$cnum.':'.$cdom;
                   11095:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11096:     if (defined($cached)) {
                   11097:         if (ref($result) eq 'HASH') {
                   11098:             return %{$result};
                   11099:         }
                   11100:     } else {
                   11101:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11102:         my ($tmp) = keys(%slots);
                   11103:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  11104:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11105:             return %slots;
                   11106:         }
                   11107:     }
                   11108:     return;
                   11109: }
                   11110: 
                   11111: sub devalidate_slots_cache {
                   11112:     my ($cnum,$cdom)=@_;
                   11113:     my $hashid=$cnum.':'.$cdom;
                   11114:     &devalidate_cache_new('allslots',$hashid);
                   11115: }
                   11116: 
1.1181    raeburn  11117: sub get_coursechange {
                   11118:     my ($cdom,$cnum) = @_;
                   11119:     if ($cdom eq '' || $cnum eq '') {
                   11120:         return unless ($env{'request.course.id'});
                   11121:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11122:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11123:     }
                   11124:     my $hashid=$cdom.'_'.$cnum;
                   11125:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11126:     if ((defined($cached)) && ($change ne '')) {
                   11127:         return $change;
                   11128:     } else {
                   11129:         my %crshash;
                   11130:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11131:         if ($crshash{'internal.contentchange'} eq '') {
                   11132:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11133:             if ($change eq '') {
                   11134:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11135:                 $change = $crshash{'internal.created'};
                   11136:             }
                   11137:         } else {
                   11138:             $change = $crshash{'internal.contentchange'};
                   11139:         }
                   11140:         my $cachetime = 600;
                   11141:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11142:     }
                   11143:     return $change;
                   11144: }
                   11145: 
                   11146: sub devalidate_coursechange_cache {
                   11147:     my ($cnum,$cdom)=@_;
                   11148:     my $hashid=$cnum.':'.$cdom;
                   11149:     &devalidate_cache_new('crschange',$hashid);
                   11150: }
                   11151: 
1.31      www      11152: # ------------------------------------------------- Update symbolic store links
                   11153: 
                   11154: sub symblist {
                   11155:     my ($mapname,%newhash)=@_;
1.438     www      11156:     $mapname=&deversion(&declutter($mapname));
1.31      www      11157:     my %hash;
1.620     albertel 11158:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11159:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11160:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11161: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11162: 		next if ($url eq 'last_known'
                   11163: 			 && $env{'form.no_update_last_known'});
                   11164: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11165: 						    $newhash{$url}->[1],
                   11166: 						    $newhash{$url}->[0]);
1.191     harris41 11167:             }
1.31      www      11168:             if (untie(%hash)) {
                   11169: 		return 'ok';
                   11170:             }
                   11171:         }
                   11172:     }
                   11173:     return 'error';
1.212     www      11174: }
                   11175: 
                   11176: # --------------------------------------------------------------- Verify a symb
                   11177: 
                   11178: sub symbverify {
1.1190    raeburn  11179:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11180:     my $thisfn=$thisurl;
1.439     www      11181:     $thisfn=&declutter($thisfn);
1.215     www      11182: # direct jump to resource in page or to a sequence - will construct own symbs
                   11183:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11184: # check URL part
1.409     www      11185:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11186: 
1.431     www      11187:     unless ($url eq $thisfn) { return 0; }
1.213     www      11188: 
1.216     www      11189:     $symb=&symbclean($symb);
1.510     www      11190:     $thisurl=&deversion($thisurl);
1.439     www      11191:     $thisfn=&deversion($thisfn);
1.213     www      11192: 
                   11193:     my %bighash;
                   11194:     my $okay=0;
1.431     www      11195: 
1.620     albertel 11196:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11197:                             &GDBM_READER(),0640)) {
1.1204    raeburn  11198:         my $noclutter;
1.1032    raeburn  11199:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11200:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  11201:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11202:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11203:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11204:                 $noclutter = 1;
                   11205:             }
                   11206:         }
                   11207:         my $ids;
                   11208:         if ($noclutter) {
                   11209:             $ids=$bighash{'ids_'.$thisurl};
                   11210:         } else {
                   11211:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11212:         }
1.1102    raeburn  11213:         unless ($ids) {
                   11214:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   11215:             $ids=$bighash{$idkey};
1.216     www      11216:         }
                   11217:         if ($ids) {
                   11218: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  11219:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  11220:                 $symb =~ s/\?.+$//;
1.1202    raeburn  11221:             }
1.800     albertel 11222: 	    foreach my $id (split(/\,/,$ids)) {
                   11223: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11224:                if (
                   11225:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  11226:    eq $symb) {
                   11227:                    if (ref($encstate)) {
                   11228:                        $$encstate = $bighash{'encrypted_'.$id};
                   11229:                    }
1.620     albertel 11230: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  11231: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   11232:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  11233: 		       $okay=1;
1.1202    raeburn  11234:                        last;
1.582     albertel 11235: 		   }
                   11236: 	       }
1.216     www      11237: 	   }
                   11238:         }
1.213     www      11239: 	untie(%bighash);
                   11240:     }
                   11241:     return $okay;
1.31      www      11242: }
                   11243: 
1.210     www      11244: # --------------------------------------------------------------- Clean-up symb
                   11245: 
                   11246: sub symbclean {
                   11247:     my $symb=shift;
1.568     albertel 11248:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11249: # remove version from map
                   11250:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11251: 
1.210     www      11252: # remove version from URL
                   11253:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11254: 
1.507     www      11255: # remove wrapper
                   11256: 
1.510     www      11257:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11258:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11259:     return $symb;
1.409     www      11260: }
                   11261: 
                   11262: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11263: 
                   11264: sub encode_symb {
                   11265:     my ($map,$resid,$url)=@_;
                   11266:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11267: }
1.409     www      11268: 
                   11269: sub decode_symb {
1.568     albertel 11270:     my $symb=shift;
                   11271:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11272:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11273:     return (&fixversion($map),$resid,&fixversion($url));
                   11274: }
                   11275: 
                   11276: sub fixversion {
                   11277:     my $fn=shift;
1.609     banghart 11278:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11279:     my %bighash;
                   11280:     my $uri=&clutter($fn);
1.620     albertel 11281:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11282: # is this cached?
1.599     albertel 11283:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11284:     if (defined($cached)) { return $result; }
                   11285: # unfortunately not cached, or expired
1.620     albertel 11286:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11287: 	    &GDBM_READER(),0640)) {
                   11288:  	if ($bighash{'version_'.$uri}) {
                   11289:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11290:  	    unless (($version eq 'mostrecent') || 
                   11291: 		    ($version==&getversion($uri))) {
1.440     www      11292:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11293:  	    }
                   11294:  	}
                   11295:  	untie %bighash;
1.413     www      11296:     }
1.599     albertel 11297:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11298: }
                   11299: 
                   11300: sub deversion {
                   11301:     my $url=shift;
                   11302:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11303:     return $url;
1.210     www      11304: }
                   11305: 
1.31      www      11306: # ------------------------------------------------------ Return symb list entry
                   11307: 
                   11308: sub symbread {
1.1282    raeburn  11309:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  11310:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  11311:     if (defined($env{$cache_str})) {
                   11312:         if ($ignorecachednull) {
                   11313:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11314:         } else {
                   11315:             return $env{$cache_str};
                   11316:         }
                   11317:     }
1.242     www      11318: # no filename provided? try from environment
1.1265    raeburn  11319:     unless ($thisfn) {
1.620     albertel 11320:         if ($env{'request.symb'}) {
                   11321: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 11322: 	}
1.620     albertel 11323: 	$thisfn=$env{'request.filename'};
1.44      www      11324:     }
1.569     albertel 11325:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11326: # is that filename actually a symb? Verify, clean, and return
                   11327:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11328: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11329: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11330: 	}
1.242     www      11331:     }
1.44      www      11332:     $thisfn=declutter($thisfn);
1.31      www      11333:     my %hash;
1.37      www      11334:     my %bighash;
                   11335:     my $syval='';
1.620     albertel 11336:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11337:         my $targetfn = $thisfn;
1.609     banghart 11338:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11339:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11340:         }
1.687     albertel 11341: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11342: 	    $targetfn=$1;
                   11343: 	}
1.620     albertel 11344:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11345:                       &GDBM_READER(),0640)) {
1.481     raeburn  11346: 	    $syval=$hash{$targetfn};
1.37      www      11347:             untie(%hash);
                   11348:         }
                   11349: # ---------------------------------------------------------- There was an entry
                   11350:         if ($syval) {
1.601     albertel 11351: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11352: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11353: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11354: 		    #return $env{$cache_str}='';
1.601     albertel 11355: 		#}    
                   11356: 		#$syval.=$1;
                   11357: 	    #}
1.37      www      11358:         } else {
                   11359: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11360:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11361:                             &GDBM_READER(),0640)) {
1.37      www      11362: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11363:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11364:               unless ($ids) { 
                   11365:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11366:               }
                   11367:               unless ($ids) {
                   11368: # alias?
                   11369: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11370:               }
1.37      www      11371:               if ($ids) {
                   11372: # ------------------------------------------------------------------- Has ID(s)
                   11373:                  my @possibilities=split(/\,/,$ids);
1.39      www      11374:                  if ($#possibilities==0) {
                   11375: # ----------------------------------------------- There is only one possibility
1.37      www      11376: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11377: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11378: 						    $resid,$thisfn);
1.1282    raeburn  11379:                      if (ref($possibles) eq 'HASH') {
                   11380:                          $possibles->{$syval} = 1;    
                   11381:                      }
                   11382:                      if ($checkforblock) {
                   11383:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11384:                          if (@blockers) {
                   11385:                              $syval = '';
                   11386:                              return;
                   11387:                          }
                   11388:                      }
                   11389:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      11390: # ------------------------------------------ There is more than one possibility
                   11391:                      my $realpossible=0;
1.800     albertel 11392:                      foreach my $id (@possibilities) {
                   11393: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  11394:                          my $canaccess;
                   11395:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11396:                              $canaccess = 1;
                   11397:                          } else { 
                   11398:                              $canaccess = &allowed('bre',$file);
                   11399:                          }
                   11400:                          if ($canaccess) {
                   11401:          		     my ($mapid,$resid)=split(/\./,$id);
                   11402:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11403:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11404: 						             $resid,$thisfn);
                   11405:                                  if (ref($possibles) eq 'HASH') {
                   11406:                                      $possibles->{$syval} = 1;
                   11407:                                  }
                   11408:                                  if ($checkforblock) {
                   11409:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11410:                                      unless (@blockers > 0) {
                   11411:                                          $syval = $poss_syval;
                   11412:                                          $realpossible++;
                   11413:                                      }
                   11414:                                  } else {
                   11415:                                      $syval = $poss_syval;
                   11416:                                      $realpossible++;
                   11417:                                  }
                   11418:                              }
1.39      www      11419: 			 }
1.191     harris41 11420:                      }
1.39      www      11421: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11422:                  } else {
                   11423:                      $syval='';
1.37      www      11424:                  }
                   11425: 	      }
1.1282    raeburn  11426:               untie(%bighash);
1.481     raeburn  11427:            }
1.31      www      11428:         }
1.62      www      11429:         if ($syval) {
1.620     albertel 11430: 	    return $env{$cache_str}=$syval;
1.62      www      11431:         }
1.31      www      11432:     }
1.949     raeburn  11433:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11434:     return $env{$cache_str}='';
1.31      www      11435: }
                   11436: 
                   11437: # ---------------------------------------------------------- Return random seed
                   11438: 
1.32      www      11439: sub numval {
                   11440:     my $txt=shift;
                   11441:     $txt=~tr/A-J/0-9/;
                   11442:     $txt=~tr/a-j/0-9/;
                   11443:     $txt=~tr/K-T/0-9/;
                   11444:     $txt=~tr/k-t/0-9/;
                   11445:     $txt=~tr/U-Z/0-5/;
                   11446:     $txt=~tr/u-z/0-5/;
                   11447:     $txt=~s/\D//g;
1.564     albertel 11448:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11449:     return int($txt);
1.368     albertel 11450: }
                   11451: 
1.484     albertel 11452: sub numval2 {
                   11453:     my $txt=shift;
                   11454:     $txt=~tr/A-J/0-9/;
                   11455:     $txt=~tr/a-j/0-9/;
                   11456:     $txt=~tr/K-T/0-9/;
                   11457:     $txt=~tr/k-t/0-9/;
                   11458:     $txt=~tr/U-Z/0-5/;
                   11459:     $txt=~tr/u-z/0-5/;
                   11460:     $txt=~s/\D//g;
                   11461:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11462:     my $total;
                   11463:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11464:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11465:     return int($total);
                   11466: }
                   11467: 
1.575     albertel 11468: sub numval3 {
                   11469:     use integer;
                   11470:     my $txt=shift;
                   11471:     $txt=~tr/A-J/0-9/;
                   11472:     $txt=~tr/a-j/0-9/;
                   11473:     $txt=~tr/K-T/0-9/;
                   11474:     $txt=~tr/k-t/0-9/;
                   11475:     $txt=~tr/U-Z/0-5/;
                   11476:     $txt=~tr/u-z/0-5/;
                   11477:     $txt=~s/\D//g;
                   11478:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11479:     my $total;
                   11480:     foreach my $val (@txts) { $total+=$val; }
                   11481:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11482:     return $total;
                   11483: }
                   11484: 
1.675     albertel 11485: sub digest {
                   11486:     my ($data)=@_;
                   11487:     my $digest=&Digest::MD5::md5($data);
                   11488:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11489:     my ($e,$f);
                   11490:     {
                   11491:         use integer;
                   11492:         $e=($a+$b);
                   11493:         $f=($c+$d);
                   11494:         if ($_64bit) {
                   11495:             $e=(($e<<32)>>32);
                   11496:             $f=(($f<<32)>>32);
                   11497:         }
                   11498:     }
                   11499:     if (wantarray) {
                   11500: 	return ($e,$f);
                   11501:     } else {
                   11502: 	my $g;
                   11503: 	{
                   11504: 	    use integer;
                   11505: 	    $g=($e+$f);
                   11506: 	    if ($_64bit) {
                   11507: 		$g=(($g<<32)>>32);
                   11508: 	    }
                   11509: 	}
                   11510: 	return $g;
                   11511:     }
                   11512: }
                   11513: 
1.368     albertel 11514: sub latest_rnd_algorithm_id {
1.675     albertel 11515:     return '64bit5';
1.366     albertel 11516: }
1.32      www      11517: 
1.503     albertel 11518: sub get_rand_alg {
                   11519:     my ($courseid)=@_;
1.790     albertel 11520:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11521:     if ($courseid) {
1.620     albertel 11522: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11523:     }
                   11524:     return &latest_rnd_algorithm_id();
                   11525: }
                   11526: 
1.562     albertel 11527: sub validCODE {
                   11528:     my ($CODE)=@_;
                   11529:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11530:     return 0;
                   11531: }
                   11532: 
1.491     albertel 11533: sub getCODE {
1.620     albertel 11534:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11535:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11536: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11537: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11538: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11539:     }
                   11540:     return undef;
                   11541: }
1.1133    foxr     11542: #
                   11543: #  Determines the random seed for a specific context:
                   11544: #
                   11545: # parameters:
                   11546: #   symb      - in course context the symb for the seed.
                   11547: #   course_id - The course id of the form domain_coursenum.
                   11548: #   domain    - Domain for the user.
                   11549: #   course    - Course for the user.
                   11550: #   cenv      - environment of the course.
                   11551: #
                   11552: # NOTE:
                   11553: #   All parameters are picked out of the environment if missing
                   11554: #   or not defined.
                   11555: #   If a symb cannot be determined the current time is used instead.
                   11556: #
                   11557: #  For a given well defined symb, courside, domain, username,
                   11558: #  and course environment, the seed is reproducible.
                   11559: #
1.31      www      11560: sub rndseed {
1.1133    foxr     11561:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11562:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11563:     if (!defined($symb)) {
1.366     albertel 11564: 	unless ($symb=$wsymb) { return time; }
                   11565:     }
1.1146    foxr     11566:     if (!defined $courseid) { 
                   11567: 	$courseid=$wcourseid; 
                   11568:     }
                   11569:     if (!defined $domain) { $domain=$wdomain; }
                   11570:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11571: 
                   11572:     my $which;
                   11573:     if (defined($cenv->{'rndseed'})) {
                   11574: 	$which = $cenv->{'rndseed'};
                   11575:     } else {
                   11576: 	$which =&get_rand_alg($courseid);
                   11577:     }
1.491     albertel 11578:     if (defined(&getCODE())) {
1.1133    foxr     11579: 
1.675     albertel 11580: 	if ($which eq '64bit5') {
                   11581: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11582: 	} elsif ($which eq '64bit4') {
1.575     albertel 11583: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11584: 	} else {
                   11585: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11586: 	}
1.675     albertel 11587:     } elsif ($which eq '64bit5') {
                   11588: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11589:     } elsif ($which eq '64bit4') {
                   11590: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11591:     } elsif ($which eq '64bit3') {
                   11592: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11593:     } elsif ($which eq '64bit2') {
                   11594: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11595:     } elsif ($which eq '64bit') {
                   11596: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11597:     }
                   11598:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11599: }
                   11600: 
                   11601: sub rndseed_32bit {
                   11602:     my ($symb,$courseid,$domain,$username)=@_;
                   11603:     {
                   11604: 	use integer;
                   11605: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11606: 	my $symbseed=numval($symb) << 22;
                   11607: 	my $namechck=unpack("%32C*",$username) << 17;
                   11608: 	my $nameseed=numval($username) << 12;
                   11609: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11610: 	my $courseseed=unpack("%32C*",$courseid);
                   11611: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11612: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11613: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11614: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11615: 	return $num;
                   11616:     }
                   11617: }
                   11618: 
                   11619: sub rndseed_64bit {
                   11620:     my ($symb,$courseid,$domain,$username)=@_;
                   11621:     {
                   11622: 	use integer;
                   11623: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11624: 	my $symbseed=numval($symb) << 10;
                   11625: 	my $namechck=unpack("%32S*",$username);
                   11626: 	
                   11627: 	my $nameseed=numval($username) << 21;
                   11628: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11629: 	my $courseseed=unpack("%32S*",$courseid);
                   11630: 	
                   11631: 	my $num1=$symbchck+$symbseed+$namechck;
                   11632: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11633: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11634: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11635: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11636: 	return "$num1,$num2";
1.155     albertel 11637:     }
1.366     albertel 11638: }
                   11639: 
1.443     albertel 11640: sub rndseed_64bit2 {
                   11641:     my ($symb,$courseid,$domain,$username)=@_;
                   11642:     {
                   11643: 	use integer;
                   11644: 	# strings need to be an even # of cahracters long, it it is odd the
                   11645:         # last characters gets thrown away
                   11646: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11647: 	my $symbseed=numval($symb) << 10;
                   11648: 	my $namechck=unpack("%32S*",$username.' ');
                   11649: 	
                   11650: 	my $nameseed=numval($username) << 21;
1.501     albertel 11651: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11652: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11653: 	
                   11654: 	my $num1=$symbchck+$symbseed+$namechck;
                   11655: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11656: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11657: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11658: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11659: 	return "$num1,$num2";
                   11660:     }
                   11661: }
                   11662: 
                   11663: sub rndseed_64bit3 {
                   11664:     my ($symb,$courseid,$domain,$username)=@_;
                   11665:     {
                   11666: 	use integer;
                   11667: 	# strings need to be an even # of cahracters long, it it is odd the
                   11668:         # last characters gets thrown away
                   11669: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11670: 	my $symbseed=numval2($symb) << 10;
                   11671: 	my $namechck=unpack("%32S*",$username.' ');
                   11672: 	
                   11673: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11674: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11675: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11676: 	
                   11677: 	my $num1=$symbchck+$symbseed+$namechck;
                   11678: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11679: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11680: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11681: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11682: 	
1.503     albertel 11683: 	return "$num1:$num2";
1.443     albertel 11684:     }
                   11685: }
                   11686: 
1.575     albertel 11687: sub rndseed_64bit4 {
                   11688:     my ($symb,$courseid,$domain,$username)=@_;
                   11689:     {
                   11690: 	use integer;
                   11691: 	# strings need to be an even # of cahracters long, it it is odd the
                   11692:         # last characters gets thrown away
                   11693: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11694: 	my $symbseed=numval3($symb) << 10;
                   11695: 	my $namechck=unpack("%32S*",$username.' ');
                   11696: 	
                   11697: 	my $nameseed=numval3($username) << 21;
                   11698: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11699: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11700: 	
                   11701: 	my $num1=$symbchck+$symbseed+$namechck;
                   11702: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11703: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11704: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11705: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11706: 	
1.575     albertel 11707: 	return "$num1:$num2";
                   11708:     }
                   11709: }
                   11710: 
1.675     albertel 11711: sub rndseed_64bit5 {
                   11712:     my ($symb,$courseid,$domain,$username)=@_;
                   11713:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11714:     return "$num1:$num2";
                   11715: }
                   11716: 
1.366     albertel 11717: sub rndseed_CODE_64bit {
                   11718:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11719:     {
1.366     albertel 11720: 	use integer;
1.443     albertel 11721: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11722: 	my $symbseed=numval2($symb);
1.491     albertel 11723: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11724: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11725: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11726: 	my $num1=$symbseed+$CODEchck;
                   11727: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11728: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11729: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11730: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11731: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11732: 	return "$num1:$num2";
1.366     albertel 11733:     }
                   11734: }
                   11735: 
1.575     albertel 11736: sub rndseed_CODE_64bit4 {
                   11737:     my ($symb,$courseid,$domain,$username)=@_;
                   11738:     {
                   11739: 	use integer;
                   11740: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11741: 	my $symbseed=numval3($symb);
                   11742: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11743: 	my $CODEseed=numval3(&getCODE());
                   11744: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11745: 	my $num1=$symbseed+$CODEchck;
                   11746: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11747: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11748: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11749: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11750: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11751: 	return "$num1:$num2";
                   11752:     }
                   11753: }
                   11754: 
1.675     albertel 11755: sub rndseed_CODE_64bit5 {
                   11756:     my ($symb,$courseid,$domain,$username)=@_;
                   11757:     my $code = &getCODE();
                   11758:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11759:     return "$num1:$num2";
                   11760: }
                   11761: 
1.366     albertel 11762: sub setup_random_from_rndseed {
                   11763:     my ($rndseed)=@_;
1.503     albertel 11764:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  11765:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   11766:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   11767:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   11768:         } else {
                   11769:             &Math::Random::random_set_seed($num1,$num2);
                   11770:         }
1.366     albertel 11771:     } else {
                   11772: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11773:     }
1.36      albertel 11774: }
                   11775: 
1.474     albertel 11776: sub latest_receipt_algorithm_id {
1.835     albertel 11777:     return 'receipt3';
1.474     albertel 11778: }
                   11779: 
1.480     www      11780: sub recunique {
                   11781:     my $fucourseid=shift;
                   11782:     my $unique;
1.835     albertel 11783:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11784: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11785: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11786:     } else {
                   11787: 	$unique=$perlvar{'lonReceipt'};
                   11788:     }
                   11789:     return unpack("%32C*",$unique);
                   11790: }
                   11791: 
                   11792: sub recprefix {
                   11793:     my $fucourseid=shift;
                   11794:     my $prefix;
1.835     albertel 11795:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11796: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11797: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11798:     } else {
                   11799: 	$prefix=$perlvar{'lonHostID'};
                   11800:     }
                   11801:     return unpack("%32C*",$prefix);
                   11802: }
                   11803: 
1.76      www      11804: sub ireceipt {
1.474     albertel 11805:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11806: 
                   11807:     my $return =&recprefix($fucourseid).'-';
                   11808: 
                   11809:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11810: 	$env{'request.state'} eq 'construct') {
                   11811: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11812: 	return $return;
                   11813:     }
                   11814: 
1.76      www      11815:     my $cuname=unpack("%32C*",$funame);
                   11816:     my $cudom=unpack("%32C*",$fudom);
                   11817:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11818:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11819:     my $cunique=&recunique($fucourseid);
1.474     albertel 11820:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11821:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11822: 
1.790     albertel 11823: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11824: 			       
                   11825: 	$return.= ($cunique%$cuname+
                   11826: 		   $cunique%$cudom+
                   11827: 		   $cusymb%$cuname+
                   11828: 		   $cusymb%$cudom+
                   11829: 		   $cucourseid%$cuname+
                   11830: 		   $cucourseid%$cudom+
                   11831: 		   $cpart%$cuname+
                   11832: 		   $cpart%$cudom);
                   11833:     } else {
                   11834: 	$return.= ($cunique%$cuname+
                   11835: 		   $cunique%$cudom+
                   11836: 		   $cusymb%$cuname+
                   11837: 		   $cusymb%$cudom+
                   11838: 		   $cucourseid%$cuname+
                   11839: 		   $cucourseid%$cudom);
                   11840:     }
                   11841:     return $return;
1.76      www      11842: }
                   11843: 
                   11844: sub receipt {
1.474     albertel 11845:     my ($part)=@_;
1.790     albertel 11846:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11847:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11848: }
1.260     ng       11849: 
1.790     albertel 11850: sub whichuser {
                   11851:     my ($passedsymb)=@_;
                   11852:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11853:     if (defined($env{'form.grade_symb'})) {
                   11854: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11855: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11856: 	if (!$allowed &&
                   11857: 	    exists($env{'request.course.sec'}) &&
                   11858: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11859: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11860: 			      '/'.$env{'request.course.sec'});
                   11861: 	}
                   11862: 	if ($allowed) {
                   11863: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11864: 	    $courseid=$tmp_courseid;
                   11865: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11866: 	    ($name)=&get_env_multiple('form.grade_username');
                   11867: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11868: 	}
                   11869:     }
                   11870:     if (!$passedsymb) {
                   11871: 	$symb=&symbread();
                   11872:     } else {
                   11873: 	$symb=$passedsymb;
                   11874:     }
                   11875:     $courseid=$env{'request.course.id'};
                   11876:     $domain=$env{'user.domain'};
                   11877:     $name=$env{'user.name'};
                   11878:     if ($name eq 'public' && $domain eq 'public') {
                   11879: 	if (!defined($env{'form.username'})) {
                   11880: 	    $env{'form.username'}.=time.rand(10000000);
                   11881: 	}
                   11882: 	$name.=$env{'form.username'};
                   11883:     }
                   11884:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11885: 
                   11886: }
                   11887: 
1.36      albertel 11888: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11889: # returns either the contents of the file or 
                   11890: # -1 if the file doesn't exist
1.481     raeburn  11891: #
                   11892: # if the target is a file that was uploaded via DOCS, 
                   11893: # a check will be made to see if a current copy exists on the local server,
                   11894: # if it does this will be served, otherwise a copy will be retrieved from
                   11895: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11896: # the local server.   
1.472     albertel 11897: 
1.36      albertel 11898: sub getfile {
1.538     albertel 11899:     my ($file) = @_;
1.609     banghart 11900:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11901:     &repcopy($file);
                   11902:     return &readfile($file);
                   11903: }
                   11904: 
                   11905: sub repcopy_userfile {
                   11906:     my ($file)=@_;
1.1142    raeburn  11907:     my $londocroot = $perlvar{'lonDocRoot'};
                   11908:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11909:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11910:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11911: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11912:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11913:     if (-e "$file") {
1.828     www      11914: # we already have a local copy, check it out
1.538     albertel 11915: 	my @fileinfo = stat($file);
1.828     www      11916: 	my $rtncode;
                   11917: 	my $info;
1.538     albertel 11918: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11919: 	if ($lwpresp ne 'ok') {
1.828     www      11920: # there is no such file anymore, even though we had a local copy
1.482     albertel 11921: 	    if ($rtncode eq '404') {
1.538     albertel 11922: 		unlink($file);
1.482     albertel 11923: 	    }
                   11924: 	    return -1;
                   11925: 	}
                   11926: 	if ($info < $fileinfo[9]) {
1.828     www      11927: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11928: 	    return 'ok';
1.828     www      11929: 	} else {
                   11930: # the file is outdated, get rid of it
                   11931: 	    unlink($file);
1.482     albertel 11932: 	}
1.828     www      11933:     }
                   11934: # one way or the other, at this point, we don't have the file
                   11935: # construct the correct path for the file
                   11936:     my @parts = ($cdom,$cnum); 
                   11937:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11938: 	push @parts, split(/\//,$1);
                   11939:     }
                   11940:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11941:     foreach my $part (@parts) {
                   11942: 	$path .= '/'.$part;
                   11943: 	if (!-e $path) {
                   11944: 	    mkdir($path,0770);
1.482     albertel 11945: 	}
                   11946:     }
1.828     www      11947: # now the path exists for sure
                   11948: # get a user agent
                   11949:     my $ua=new LWP::UserAgent;
                   11950:     my $transferfile=$file.'.in.transfer';
                   11951: # FIXME: this should flock
                   11952:     if (-e $transferfile) { return 'ok'; }
                   11953:     my $request;
                   11954:     $uri=~s/^\///;
1.980     raeburn  11955:     my $homeserver = &homeserver($cnum,$cdom);
                   11956:     my $protocol = $protocol{$homeserver};
                   11957:     $protocol = 'http' if ($protocol ne 'https');
                   11958:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11959:     my $response=$ua->request($request,$transferfile);
                   11960: # did it work?
                   11961:     if ($response->is_error()) {
                   11962: 	unlink($transferfile);
                   11963: 	&logthis("Userfile repcopy failed for $uri");
                   11964: 	return -1;
                   11965:     }
                   11966: # worked, rename the transfer file
                   11967:     rename($transferfile,$file);
1.607     raeburn  11968:     return 'ok';
1.481     raeburn  11969: }
                   11970: 
1.517     albertel 11971: sub tokenwrapper {
                   11972:     my $uri=shift;
1.980     raeburn  11973:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11974:     $uri=~s|^/||;
1.620     albertel 11975:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11976:     my $token=$1;
1.552     albertel 11977:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11978:     if ($udom && $uname && $file) {
                   11979: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11980:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11981:         my $homeserver = &homeserver($uname,$udom);
                   11982:         my $protocol = $protocol{$homeserver};
                   11983:         $protocol = 'http' if ($protocol ne 'https');
                   11984:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11985:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11986:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11987:     } else {
                   11988:         return '/adm/notfound.html';
                   11989:     }
                   11990: }
                   11991: 
1.828     www      11992: # call with reqtype HEAD: get last modification time
                   11993: # call with reqtype GET: get the file contents
                   11994: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11995: #
1.481     raeburn  11996: sub getuploaded {
                   11997:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11998:     $uri=~s/^\///;
1.980     raeburn  11999:     my $homeserver = &homeserver($cnum,$cdom);
                   12000:     my $protocol = $protocol{$homeserver};
                   12001:     $protocol = 'http' if ($protocol ne 'https');
                   12002:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12003:     my $ua=new LWP::UserAgent;
                   12004:     my $request=new HTTP::Request($reqtype,$uri);
                   12005:     my $response=$ua->request($request);
                   12006:     $$rtncode = $response->code;
1.482     albertel 12007:     if (! $response->is_success()) {
                   12008: 	return 'failed';
                   12009:     }      
                   12010:     if ($reqtype eq 'HEAD') {
1.486     www      12011: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12012:     } elsif ($reqtype eq 'GET') {
                   12013: 	$$info = $response->content;
1.472     albertel 12014:     }
1.482     albertel 12015:     return 'ok';
1.36      albertel 12016: }
                   12017: 
1.481     raeburn  12018: sub readfile {
                   12019:     my $file = shift;
                   12020:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12021:     my $fh;
                   12022:     open($fh,"<$file");
                   12023:     my $a='';
1.800     albertel 12024:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12025:     return $a;
                   12026: }
                   12027: 
1.36      albertel 12028: sub filelocation {
1.590     banghart 12029:     my ($dir,$file) = @_;
                   12030:     my $location;
                   12031:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12032: 
                   12033:     if ($file =~ m-^/adm/-) {
                   12034: 	$file=~s-^/adm/wrapper/-/-;
                   12035: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12036:     }
1.882     albertel 12037: 
1.1139    www      12038:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12039:         $location = $file;
1.609     banghart 12040:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12041:         my ($udom,$uname,$filename)=
1.811     albertel 12042:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12043:         my $home=&homeserver($uname,$udom);
                   12044:         my $is_me=0;
                   12045:         my @ids=&current_machine_ids();
                   12046:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12047:         if ($is_me) {
1.1117    foxr     12048:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12049:         } else {
                   12050:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12051:   	      $udom.'/'.$uname.'/'.$filename;
                   12052:         }
1.882     albertel 12053:     } elsif ($file =~ m-^/adm/-) {
                   12054: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12055:     } else {
                   12056:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12057:         $file=~s:^/(res|priv)/:/:;
                   12058:         my $space=$1;
1.590     banghart 12059:         if ( !( $file =~ m:^/:) ) {
                   12060:             $location = $dir. '/'.$file;
                   12061:         } else {
1.1142    raeburn  12062:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12063:         }
1.59      albertel 12064:     }
1.590     banghart 12065:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12066:     while ($location=~m{/\.\./}) {
                   12067: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12068: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12069: 	} else {
                   12070: 	    $location=~ s{/\.\./}{/}g;
                   12071: 	}
                   12072:     } #remove dir/..
1.590     banghart 12073:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12074:     return $location;
1.46      www      12075: }
1.36      albertel 12076: 
1.46      www      12077: sub hreflocation {
                   12078:     my ($dir,$file)=@_;
1.980     raeburn  12079:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12080: 	$file=filelocation($dir,$file);
1.700     albertel 12081:     } elsif ($file=~m-^/adm/-) {
                   12082: 	$file=~s-^/adm/wrapper/-/-;
                   12083: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12084:     }
                   12085:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12086: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12087:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12088: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12089: 	        {/uploaded/$1/$2/}x;
1.46      www      12090:     }
1.913     albertel 12091:     if ($file=~ m{^/userfiles/}) {
                   12092: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12093:     }
1.462     albertel 12094:     return $file;
1.465     albertel 12095: }
                   12096: 
1.1139    www      12097: 
                   12098: 
                   12099: 
                   12100: 
1.465     albertel 12101: sub current_machine_domains {
1.853     albertel 12102:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12103: }
                   12104: 
                   12105: sub machine_domains {
                   12106:     my ($hostname) = @_;
1.465     albertel 12107:     my @domains;
1.838     albertel 12108:     my %hostname = &all_hostnames();
1.465     albertel 12109:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12110: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12111: 	if ($hostname eq $name) {
1.844     albertel 12112: 	    push(@domains,&host_domain($id));
1.465     albertel 12113: 	}
                   12114:     }
                   12115:     return @domains;
                   12116: }
                   12117: 
                   12118: sub current_machine_ids {
1.853     albertel 12119:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12120: }
                   12121: 
                   12122: sub machine_ids {
                   12123:     my ($hostname) = @_;
                   12124:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12125:     my @ids;
1.888     albertel 12126:     my %name_to_host = &all_names();
1.889     albertel 12127:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12128: 	return @{ $name_to_host{$hostname} };
                   12129:     }
                   12130:     return;
1.31      www      12131: }
                   12132: 
1.824     raeburn  12133: sub additional_machine_domains {
                   12134:     my @domains;
                   12135:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12136:     while( my $line = <$fh>) {
                   12137:         $line =~ s/\s//g;
                   12138:         push(@domains,$line);
                   12139:     }
                   12140:     return @domains;
                   12141: }
                   12142: 
                   12143: sub default_login_domain {
                   12144:     my $domain = $perlvar{'lonDefDomain'};
                   12145:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12146:     foreach my $posdom (&current_machine_domains(),
                   12147:                         &additional_machine_domains()) {
                   12148:         if (lc($posdom) eq lc($testdomain)) {
                   12149:             $domain=$posdom;
                   12150:             last;
                   12151:         }
                   12152:     }
                   12153:     return $domain;
                   12154: }
                   12155: 
1.31      www      12156: # ------------------------------------------------------------- Declutters URLs
                   12157: 
                   12158: sub declutter {
                   12159:     my $thisfn=shift;
1.569     albertel 12160:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  12161:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12162:         $thisfn=~s{^/home/httpd/html}{};
                   12163:     }
1.31      www      12164:     $thisfn=~s/^\///;
1.697     albertel 12165:     $thisfn=~s|^adm/wrapper/||;
                   12166:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12167:     $thisfn=~s/^res\///;
1.1172    bisitz   12168:     $thisfn=~s/^priv\///;
1.1032    raeburn  12169:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12170:         $thisfn=~s/\?.+$//;
                   12171:     }
1.268     www      12172:     return $thisfn;
                   12173: }
                   12174: 
                   12175: # ------------------------------------------------------------- Clutter up URLs
                   12176: 
                   12177: sub clutter {
                   12178:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12179:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12180: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12181:        $thisfn='/res'.$thisfn; 
                   12182:     }
1.1031    raeburn  12183:     if ($thisfn !~m|^/adm|) {
                   12184: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12185: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12186: 	} else {
                   12187: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12188: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12189: 	    if ($embstyle eq 'ssi'
                   12190: 		|| ($embstyle eq 'hdn')
                   12191: 		|| ($embstyle eq 'rat')
                   12192: 		|| ($embstyle eq 'prv')
                   12193: 		|| ($embstyle eq 'ign')) {
                   12194: 		#do nothing with these
                   12195: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12196: 		|| ($embstyle eq 'emb')
                   12197: 		|| ($embstyle eq 'wrp')) {
                   12198: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12199: 	    } elsif ($embstyle eq 'unk'
                   12200: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12201: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12202: 	    } else {
1.718     www      12203: #		&logthis("Got a blank emb style");
1.695     albertel 12204: 	    }
1.694     albertel 12205: 	}
                   12206:     }
1.31      www      12207:     return $thisfn;
1.12      www      12208: }
                   12209: 
1.787     albertel 12210: sub clutter_with_no_wrapper {
                   12211:     my $uri = &clutter(shift);
                   12212:     if ($uri =~ m-^/adm/-) {
                   12213: 	$uri =~ s-^/adm/wrapper/-/-;
                   12214: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12215:     }
                   12216:     return $uri;
                   12217: }
                   12218: 
1.557     albertel 12219: sub freeze_escape {
                   12220:     my ($value)=@_;
                   12221:     if (ref($value)) {
                   12222: 	$value=&nfreeze($value);
                   12223: 	return '__FROZEN__'.&escape($value);
                   12224:     }
                   12225:     return &escape($value);
                   12226: }
                   12227: 
1.11      www      12228: 
1.557     albertel 12229: sub thaw_unescape {
                   12230:     my ($value)=@_;
                   12231:     if ($value =~ /^__FROZEN__/) {
                   12232: 	substr($value,0,10,undef);
                   12233: 	$value=&unescape($value);
                   12234: 	return &thaw($value);
                   12235:     }
                   12236:     return &unescape($value);
                   12237: }
                   12238: 
1.436     albertel 12239: sub correct_line_ends {
                   12240:     my ($result)=@_;
                   12241:     $$result =~s/\r\n/\n/mg;
                   12242:     $$result =~s/\r/\n/mg;
1.415     albertel 12243: }
1.1       albertel 12244: # ================================================================ Main Program
                   12245: 
1.184     www      12246: sub goodbye {
1.204     albertel 12247:    &logthis("Starting Shut down");
1.443     albertel 12248: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12249:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12250: #converted
1.599     albertel 12251: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12252:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12253: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12254: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12255: #1.1 only
1.870     albertel 12256: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12257: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12258: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12259: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12260:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12261:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12262:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12263:    &flushcourselogs();
                   12264:    &logthis("Shutting down");
                   12265: }
                   12266: 
1.852     albertel 12267: sub get_dns {
1.1210    raeburn  12268:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12269:     if (!$ignore_cache) {
                   12270: 	my ($content,$cached)=
                   12271: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12272: 	if ($cached) {
1.1210    raeburn  12273: 	    &$func($content,$hashref);
1.869     albertel 12274: 	    return;
                   12275: 	}
                   12276:     }
                   12277: 
                   12278:     my %alldns;
1.852     albertel 12279:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12280:     foreach my $dns (<$config>) {
                   12281: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12282:         my $line = $1;
                   12283:         my ($host,$protocol) = split(/:/,$line);
                   12284:         if ($protocol ne 'https') {
                   12285:             $protocol = 'http';
                   12286:         }
                   12287: 	$alldns{$host} = $protocol;
1.869     albertel 12288:     }
                   12289:     while (%alldns) {
1.1263    raeburn  12290: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12291: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12292:         $ua->timeout(30);
1.979     raeburn  12293: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12294: 	my $response=$ua->request($request);
1.979     raeburn  12295:         delete($alldns{$dns});
1.852     albertel 12296: 	next if ($response->is_error());
                   12297: 	my @content = split("\n",$response->content);
1.1210    raeburn  12298: 	unless ($nocache) {
1.1219    raeburn  12299: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  12300: 	}
                   12301: 	&$func(\@content,$hashref);
1.869     albertel 12302: 	return;
1.852     albertel 12303:     }
                   12304:     close($config);
1.871     albertel 12305:     my $which = (split('/',$url))[3];
                   12306:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12307:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12308:     my @content = <$config>;
1.1210    raeburn  12309:     &$func(\@content,$hashref);
                   12310:     return;
                   12311: }
                   12312: 
                   12313: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  12314: sub parse_dns_checksums_tab {
1.1210    raeburn  12315:     my ($lines,$hashref) = @_;
1.1264    raeburn  12316:     my $lonhost = $perlvar{'lonHostID'};
                   12317:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  12318:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  12319:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12320:     my $webconfdir = '/etc/httpd/conf';
                   12321:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12322:         $webconfdir = '/etc/apache2';
                   12323:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12324:         if ($1 >= 10) {
                   12325:             $webconfdir = '/etc/apache2';
                   12326:         }
                   12327:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12328:         if ($1 >= 10.0) {
                   12329:             $webconfdir = '/etc/apache2';
                   12330:         }
                   12331:     }
1.1210    raeburn  12332:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12333:     my (%chksum,%revnum);
                   12334:     if (ref($lines) eq 'ARRAY') {
                   12335:         chomp(@{$lines});
1.1238    raeburn  12336:         my $version = shift(@{$lines});
                   12337:         if ($version eq $release) {  
1.1210    raeburn  12338:             foreach my $line (@{$lines}) {
1.1238    raeburn  12339:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  12340:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12341:                     if ($webconfdir eq '/etc/apache2') {
                   12342:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12343:                     }
                   12344:                 }
1.1238    raeburn  12345:                 $chksum{$file} = $shasum;
                   12346:                 $revnum{$file} = $version;
1.1210    raeburn  12347:             }
                   12348:             if (ref($hashref) eq 'HASH') {
                   12349:                 %{$hashref} = (
                   12350:                                 sums     => \%chksum,
                   12351:                                 versions => \%revnum,
                   12352:                               );
                   12353:             }
                   12354:         }
                   12355:     }
1.869     albertel 12356:     return;
1.852     albertel 12357: }
1.1210    raeburn  12358: 
                   12359: sub fetch_dns_checksums {
1.1238    raeburn  12360:     my %checksums;
                   12361:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  12362:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  12363:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12364:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  12365:              \%checksums);
1.1210    raeburn  12366:     return \%checksums;
                   12367: }
                   12368: 
1.327     albertel 12369: # ------------------------------------------------------------ Read domain file
                   12370: {
1.852     albertel 12371:     my $loaded;
1.846     albertel 12372:     my %domain;
                   12373: 
1.852     albertel 12374:     sub parse_domain_tab {
                   12375: 	my ($lines) = @_;
                   12376: 	foreach my $line (@$lines) {
                   12377: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12378: 
1.846     albertel 12379: 	    chomp($line);
1.852     albertel 12380: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12381: 	    my %this_domain;
                   12382: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12383: 			       'lang_def', 'city', 'longi', 'lati',
                   12384: 			       'primary') {
                   12385: 		$this_domain{$field} = shift(@elements);
                   12386: 	    }
                   12387: 	    $domain{$name} = \%this_domain;
1.852     albertel 12388: 	}
                   12389:     }
1.864     albertel 12390: 
                   12391:     sub reset_domain_info {
                   12392: 	undef($loaded);
                   12393: 	undef(%domain);
                   12394:     }
                   12395: 
1.852     albertel 12396:     sub load_domain_tab {
1.869     albertel 12397: 	my ($ignore_cache) = @_;
                   12398: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 12399: 	my $fh;
                   12400: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12401: 	    my @lines = <$fh>;
                   12402: 	    &parse_domain_tab(\@lines);
1.448     albertel 12403: 	}
1.852     albertel 12404: 	close($fh);
                   12405: 	$loaded = 1;
1.327     albertel 12406:     }
1.846     albertel 12407: 
                   12408:     sub domain {
1.852     albertel 12409: 	&load_domain_tab() if (!$loaded);
                   12410: 
1.846     albertel 12411: 	my ($name,$what) = @_;
                   12412: 	return if ( !exists($domain{$name}) );
                   12413: 
                   12414: 	if (!$what) {
                   12415: 	    return $domain{$name}{'description'};
                   12416: 	}
                   12417: 	return $domain{$name}{$what};
                   12418:     }
1.974     raeburn  12419: 
                   12420:     sub domain_info {
                   12421:         &load_domain_tab() if (!$loaded);
                   12422:         return %domain;
                   12423:     }
                   12424: 
1.327     albertel 12425: }
                   12426: 
                   12427: 
1.1       albertel 12428: # ------------------------------------------------------------- Read hosts file
                   12429: {
1.838     albertel 12430:     my %hostname;
1.844     albertel 12431:     my %hostdom;
1.845     albertel 12432:     my %libserv;
1.852     albertel 12433:     my $loaded;
1.888     albertel 12434:     my %name_to_host;
1.1074    raeburn  12435:     my %internetdom;
1.1107    raeburn  12436:     my %LC_dns_serv;
1.852     albertel 12437: 
                   12438:     sub parse_hosts_tab {
                   12439: 	my ($file) = @_;
                   12440: 	foreach my $configline (@$file) {
                   12441: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12442:             chomp($configline);
                   12443: 	    if ($configline =~ /^\^/) {
                   12444:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12445:                     $LC_dns_serv{$1} = 1;
                   12446:                 }
                   12447:                 next;
                   12448:             }
1.1074    raeburn  12449: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12450: 	    $name=~s/\s//g;
                   12451: 	    if ($id && $domain && $role && $name) {
                   12452: 		$hostname{$id}=$name;
1.888     albertel 12453: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12454: 		$hostdom{$id}=$domain;
                   12455: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12456:                 if (defined($protocol)) {
                   12457:                     if ($protocol eq 'https') {
                   12458:                         $protocol{$id} = $protocol;
                   12459:                     } else {
                   12460:                         $protocol{$id} = 'http'; 
                   12461:                     }
1.968     raeburn  12462:                 } else {
1.969     raeburn  12463:                     $protocol{$id} = 'http';
1.968     raeburn  12464:                 }
1.1074    raeburn  12465:                 if (defined($intdom)) {
                   12466:                     $internetdom{$id} = $intdom;
                   12467:                 }
1.852     albertel 12468: 	    }
                   12469: 	}
                   12470:     }
1.864     albertel 12471:     
                   12472:     sub reset_hosts_info {
1.897     albertel 12473: 	&purge_remembered();
1.864     albertel 12474: 	&reset_domain_info();
                   12475: 	&reset_hosts_ip_info();
1.892     albertel 12476: 	undef(%name_to_host);
1.864     albertel 12477: 	undef(%hostname);
                   12478: 	undef(%hostdom);
                   12479: 	undef(%libserv);
                   12480: 	undef($loaded);
                   12481:     }
1.1       albertel 12482: 
1.852     albertel 12483:     sub load_hosts_tab {
1.869     albertel 12484: 	my ($ignore_cache) = @_;
                   12485: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 12486: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12487: 	my @config = <$config>;
                   12488: 	&parse_hosts_tab(\@config);
                   12489: 	close($config);
                   12490: 	$loaded=1;
1.1       albertel 12491:     }
1.852     albertel 12492: 
1.838     albertel 12493:     sub hostname {
1.852     albertel 12494: 	&load_hosts_tab() if (!$loaded);
                   12495: 
1.838     albertel 12496: 	my ($lonid) = @_;
                   12497: 	return $hostname{$lonid};
                   12498:     }
1.845     albertel 12499: 
1.838     albertel 12500:     sub all_hostnames {
1.852     albertel 12501: 	&load_hosts_tab() if (!$loaded);
                   12502: 
1.838     albertel 12503: 	return %hostname;
                   12504:     }
1.845     albertel 12505: 
1.888     albertel 12506:     sub all_names {
                   12507: 	&load_hosts_tab() if (!$loaded);
                   12508: 
                   12509: 	return %name_to_host;
                   12510:     }
                   12511: 
1.974     raeburn  12512:     sub all_host_domain {
                   12513:         &load_hosts_tab() if (!$loaded);
                   12514:         return %hostdom;
                   12515:     }
                   12516: 
1.845     albertel 12517:     sub is_library {
1.852     albertel 12518: 	&load_hosts_tab() if (!$loaded);
                   12519: 
1.845     albertel 12520: 	return exists($libserv{$_[0]});
                   12521:     }
                   12522: 
                   12523:     sub all_library {
1.852     albertel 12524: 	&load_hosts_tab() if (!$loaded);
                   12525: 
1.845     albertel 12526: 	return %libserv;
                   12527:     }
                   12528: 
1.1062    droeschl 12529:     sub unique_library {
                   12530: 	#2x reverse removes all hostnames that appear more than once
                   12531:         my %unique = reverse &all_library();
                   12532:         return reverse %unique;
                   12533:     }
                   12534: 
1.841     albertel 12535:     sub get_servers {
1.852     albertel 12536: 	&load_hosts_tab() if (!$loaded);
                   12537: 
1.841     albertel 12538: 	my ($domain,$type) = @_;
                   12539: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12540: 	                                          : %hostname;
                   12541: 	my %result;
1.842     albertel 12542: 	if (ref($domain) eq 'ARRAY') {
                   12543: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12544: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12545: 		    $result{$host} = $hostname;
                   12546: 		}
                   12547: 	    }
                   12548: 	} else {
                   12549: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12550: 		if ($hostdom{$host} eq $domain) {
                   12551: 		    $result{$host} = $hostname;
                   12552: 		}
1.841     albertel 12553: 	    }
                   12554: 	}
                   12555: 	return %result;
                   12556:     }
1.845     albertel 12557: 
1.1062    droeschl 12558:     sub get_unique_servers {
                   12559:         my %unique = reverse &get_servers(@_);
                   12560: 	return reverse %unique;
                   12561:     }
                   12562: 
1.844     albertel 12563:     sub host_domain {
1.852     albertel 12564: 	&load_hosts_tab() if (!$loaded);
                   12565: 
1.844     albertel 12566: 	my ($lonid) = @_;
                   12567: 	return $hostdom{$lonid};
                   12568:     }
                   12569: 
1.841     albertel 12570:     sub all_domains {
1.852     albertel 12571: 	&load_hosts_tab() if (!$loaded);
                   12572: 
1.841     albertel 12573: 	my %seen;
                   12574: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12575: 	return @uniq;
                   12576:     }
1.1074    raeburn  12577: 
                   12578:     sub internet_dom {
                   12579:         &load_hosts_tab() if (!$loaded);
                   12580: 
                   12581:         my ($lonid) = @_;
                   12582:         return $internetdom{$lonid};
                   12583:     }
1.1107    raeburn  12584: 
                   12585:     sub is_LC_dns {
                   12586:         &load_hosts_tab() if (!$loaded);
                   12587: 
                   12588:         my ($hostname) = @_;
                   12589:         return exists($LC_dns_serv{$hostname});
                   12590:     }
                   12591: 
1.1       albertel 12592: }
                   12593: 
1.847     albertel 12594: { 
                   12595:     my %iphost;
1.856     albertel 12596:     my %name_to_ip;
                   12597:     my %lonid_to_ip;
1.869     albertel 12598: 
1.847     albertel 12599:     sub get_hosts_from_ip {
                   12600: 	my ($ip) = @_;
                   12601: 	my %iphosts = &get_iphost();
                   12602: 	if (ref($iphosts{$ip})) {
                   12603: 	    return @{$iphosts{$ip}};
                   12604: 	}
                   12605: 	return;
1.839     albertel 12606:     }
1.864     albertel 12607:     
                   12608:     sub reset_hosts_ip_info {
                   12609: 	undef(%iphost);
                   12610: 	undef(%name_to_ip);
                   12611: 	undef(%lonid_to_ip);
                   12612:     }
1.856     albertel 12613: 
                   12614:     sub get_host_ip {
                   12615: 	my ($lonid) = @_;
                   12616: 	if (exists($lonid_to_ip{$lonid})) {
                   12617: 	    return $lonid_to_ip{$lonid};
                   12618: 	}
                   12619: 	my $name=&hostname($lonid);
                   12620:    	my $ip = gethostbyname($name);
                   12621: 	return if (!$ip || length($ip) ne 4);
                   12622: 	$ip=inet_ntoa($ip);
                   12623: 	$name_to_ip{$name}   = $ip;
                   12624: 	$lonid_to_ip{$lonid} = $ip;
                   12625: 	return $ip;
                   12626:     }
1.847     albertel 12627:     
                   12628:     sub get_iphost {
1.869     albertel 12629: 	my ($ignore_cache) = @_;
1.894     albertel 12630: 
1.869     albertel 12631: 	if (!$ignore_cache) {
                   12632: 	    if (%iphost) {
                   12633: 		return %iphost;
                   12634: 	    }
                   12635: 	    my ($ip_info,$cached)=
                   12636: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12637: 	    if ($cached) {
                   12638: 		%iphost      = %{$ip_info->[0]};
                   12639: 		%name_to_ip  = %{$ip_info->[1]};
                   12640: 		%lonid_to_ip = %{$ip_info->[2]};
                   12641: 		return %iphost;
                   12642: 	    }
                   12643: 	}
1.894     albertel 12644: 
                   12645: 	# get yesterday's info for fallback
                   12646: 	my %old_name_to_ip;
                   12647: 	my ($ip_info,$cached)=
                   12648: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12649: 	if ($cached) {
                   12650: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12651: 	}
                   12652: 
1.888     albertel 12653: 	my %name_to_host = &all_names();
                   12654: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12655: 	    my $ip;
                   12656: 	    if (!exists($name_to_ip{$name})) {
                   12657: 		$ip = gethostbyname($name);
                   12658: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12659: 		    if (defined($old_name_to_ip{$name})) {
                   12660: 			$ip = $old_name_to_ip{$name};
                   12661: 			&logthis("Can't find $name defaulting to old $ip");
                   12662: 		    } else {
                   12663: 			&logthis("Name $name no IP found");
                   12664: 			next;
                   12665: 		    }
                   12666: 		} else {
                   12667: 		    $ip=inet_ntoa($ip);
1.847     albertel 12668: 		}
                   12669: 		$name_to_ip{$name} = $ip;
                   12670: 	    } else {
                   12671: 		$ip = $name_to_ip{$name};
1.653     albertel 12672: 	    }
1.888     albertel 12673: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12674: 		$lonid_to_ip{$id} = $ip;
                   12675: 	    }
                   12676: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12677: 	}
1.1219    raeburn  12678: 	&do_cache_new('iphost','iphost',
                   12679: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12680: 		      48*60*60);
1.869     albertel 12681: 
1.847     albertel 12682: 	return %iphost;
1.598     albertel 12683:     }
                   12684: 
1.992     raeburn  12685:     #
                   12686:     #  Given a DNS returns the loncapa host name for that DNS 
                   12687:     # 
                   12688:     sub host_from_dns {
                   12689:         my ($dns) = @_;
                   12690:         my @hosts;
                   12691:         my $ip;
                   12692: 
1.993     raeburn  12693:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12694:             $ip = $name_to_ip{$dns};
                   12695:         }
                   12696:         if (!$ip) {
                   12697:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12698:             if (length($ip) == 4) { 
                   12699: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12700:             }
                   12701:         }
                   12702:         if ($ip) {
                   12703: 	    @hosts = get_hosts_from_ip($ip);
                   12704: 	    return $hosts[0];
                   12705:         }
                   12706:         return undef;
1.986     foxr     12707:     }
1.992     raeburn  12708: 
1.1074    raeburn  12709:     sub get_internet_names {
                   12710:         my ($lonid) = @_;
                   12711:         return if ($lonid eq '');
                   12712:         my ($idnref,$cached)=
                   12713:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12714:         if ($cached) {
                   12715:             return $idnref;
                   12716:         }
                   12717:         my $ip = &get_host_ip($lonid);
                   12718:         my @hosts = &get_hosts_from_ip($ip);
                   12719:         my %iphost = &get_iphost();
                   12720:         my (@idns,%seen);
                   12721:         foreach my $id (@hosts) {
                   12722:             my $dom = &host_domain($id);
                   12723:             my $prim_id = &domain($dom,'primary');
                   12724:             my $prim_ip = &get_host_ip($prim_id);
                   12725:             next if ($seen{$prim_ip});
                   12726:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12727:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12728:                     my $intdom = &internet_dom($id);
                   12729:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12730:                         push(@idns,$intdom);
                   12731:                     }
                   12732:                 }
                   12733:             }
                   12734:             $seen{$prim_ip} = 1;
                   12735:         }
1.1219    raeburn  12736:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12737:     }
                   12738: 
1.986     foxr     12739: }
                   12740: 
1.1079    raeburn  12741: sub all_loncaparevs {
1.1249    raeburn  12742:     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  12743: }
                   12744: 
1.1227    raeburn  12745: # ---------------------------------------------------------- Read loncaparev table
                   12746: {
                   12747:     sub load_loncaparevs { 
                   12748:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12749:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12750:                 while (my $configline=<$config>) {
                   12751:                     chomp($configline);
                   12752:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12753:                     $loncaparevs{$hostid}=$loncaparev;
                   12754:                 }
                   12755:                 close($config);
                   12756:             }
                   12757:         }
                   12758:     }
                   12759: }
                   12760: 
                   12761: # ---------------------------------------------------------- Read serverhostID table
                   12762: {
                   12763:     sub load_serverhomeIDs {
                   12764:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12765:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12766:                 while (my $configline=<$config>) {
                   12767:                     chomp($configline);
                   12768:                     my ($name,$id)=split(/:/,$configline);
                   12769:                     $serverhomeIDs{$name}=$id;
                   12770:                 }
                   12771:                 close($config);
                   12772:             }
                   12773:         }
                   12774:     }
                   12775: }
                   12776: 
                   12777: 
1.862     albertel 12778: BEGIN {
                   12779: 
                   12780: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12781:     unless ($readit) {
                   12782: {
                   12783:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12784:     %perlvar = (%perlvar,%{$configvars});
                   12785: }
                   12786: 
                   12787: 
1.1       albertel 12788: # ------------------------------------------------------ Read spare server file
                   12789: {
1.448     albertel 12790:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12791: 
                   12792:     while (my $configline=<$config>) {
                   12793:        chomp($configline);
1.284     matthew  12794:        if ($configline) {
1.784     albertel 12795: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12796: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12797: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12798:        }
                   12799:     }
1.448     albertel 12800:     close($config);
1.1       albertel 12801: }
1.11      www      12802: # ------------------------------------------------------------ Read permissions
                   12803: {
1.448     albertel 12804:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12805: 
                   12806:     while (my $configline=<$config>) {
1.448     albertel 12807: 	chomp($configline);
                   12808: 	if ($configline) {
                   12809: 	    my ($role,$perm)=split(/ /,$configline);
                   12810: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12811: 	}
1.11      www      12812:     }
1.448     albertel 12813:     close($config);
1.11      www      12814: }
                   12815: 
                   12816: # -------------------------------------------- Read plain texts for permissions
                   12817: {
1.448     albertel 12818:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12819: 
                   12820:     while (my $configline=<$config>) {
1.448     albertel 12821: 	chomp($configline);
                   12822: 	if ($configline) {
1.742     raeburn  12823: 	    my ($short,@plain)=split(/:/,$configline);
                   12824:             %{$prp{$short}} = ();
                   12825: 	    if (@plain > 0) {
                   12826:                 $prp{$short}{'std'} = $plain[0];
                   12827:                 for (my $i=1; $i<@plain; $i++) {
                   12828:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12829:                 }
                   12830:             }
1.448     albertel 12831: 	}
1.135     www      12832:     }
1.448     albertel 12833:     close($config);
1.135     www      12834: }
                   12835: 
                   12836: # ---------------------------------------------------------- Read package table
                   12837: {
1.448     albertel 12838:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12839: 
                   12840:     while (my $configline=<$config>) {
1.483     albertel 12841: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12842: 	chomp($configline);
                   12843: 	my ($short,$plain)=split(/:/,$configline);
                   12844: 	my ($pack,$name)=split(/\&/,$short);
                   12845: 	if ($plain ne '') {
                   12846: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12847: 	    $packagetab{$short}=$plain; 
                   12848: 	}
1.11      www      12849:     }
1.448     albertel 12850:     close($config);
1.329     matthew  12851: }
                   12852: 
1.1073    raeburn  12853: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  12854: 
                   12855: &load_loncaparevs();
1.1073    raeburn  12856: 
1.1074    raeburn  12857: # ---------------------------------------------------------- Read serverhostID table
                   12858: 
1.1227    raeburn  12859: &load_serverhomeIDs();
                   12860: 
                   12861: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12862: {
                   12863:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12864:     if (-e $file) {
                   12865:         my $parser = HTML::LCParser->new($file);
                   12866:         while (my $token = $parser->get_token()) {
                   12867:             if ($token->[0] eq 'S') {
                   12868:                 my $item = $token->[1];
                   12869:                 my $name = $token->[2]{'name'};
                   12870:                 my $value = $token->[2]{'value'};
1.1285    raeburn  12871:                 my $valuematch = $token->[2]{'valuematch'};
                   12872:                 if ($item ne '' && $name ne '' && ($value ne '' || $valuematch ne '')) {
1.1079    raeburn  12873:                     my $release = $parser->get_text();
                   12874:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1285    raeburn  12875:                     $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch} = $release;
1.1079    raeburn  12876:                 }
                   12877:             }
                   12878:         }
                   12879:     }
1.1073    raeburn  12880: }
                   12881: 
1.1138    raeburn  12882: # ---------------------------------------------------------- Read managers table
                   12883: {
                   12884:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12885:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12886:             while (my $configline=<$config>) {
                   12887:                 chomp($configline);
                   12888:                 next if ($configline =~ /^\#/);
                   12889:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12890:                     $managerstab{$configline} = 1;
                   12891:                 }
                   12892:             }
                   12893:             close($config);
                   12894:         }
                   12895:     }
                   12896: }
                   12897: 
1.329     matthew  12898: # ------------- set up temporary directory
                   12899: {
1.1117    foxr     12900:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12901: 
1.11      www      12902: }
                   12903: 
1.794     albertel 12904: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12905: 				'compress_threshold'=> 20_000,
                   12906:  			        });
1.185     www      12907: 
1.281     www      12908: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12909: $dumpcount=0;
1.958     www      12910: $locknum=0;
1.22      www      12911: 
1.163     harris41 12912: &logtouch();
1.672     albertel 12913: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12914: $readit=1;
1.564     albertel 12915:     {
                   12916: 	use integer;
                   12917: 	my $test=(2**32)+1;
1.568     albertel 12918: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12919: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12920:     }
1.195     www      12921: }
1.1       albertel 12922: }
1.179     www      12923: 
1.1       albertel 12924: 1;
1.191     harris41 12925: __END__
                   12926: 
1.243     albertel 12927: =pod
                   12928: 
1.191     harris41 12929: =head1 NAME
                   12930: 
1.243     albertel 12931: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12932: 
                   12933: =head1 SYNOPSIS
                   12934: 
1.243     albertel 12935: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12936: 
                   12937:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12938: 
1.243     albertel 12939: Common parameters:
                   12940: 
                   12941: =over 4
                   12942: 
                   12943: =item *
                   12944: 
                   12945: $uname : an internal username (if $cname expecting a course Id specifically)
                   12946: 
                   12947: =item *
                   12948: 
                   12949: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12950: 
                   12951: =item *
                   12952: 
                   12953: $symb : a resource instance identifier
                   12954: 
                   12955: =item *
                   12956: 
                   12957: $namespace : the name of a .db file that contains the data needed or
                   12958: being set.
                   12959: 
                   12960: =back
                   12961: 
1.394     bowersj2 12962: =head1 OVERVIEW
1.191     harris41 12963: 
1.394     bowersj2 12964: lonnet provides subroutines which interact with the
                   12965: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12966: about classes, users, and resources.
1.243     albertel 12967: 
                   12968: For many of these objects you can also use this to store data about
                   12969: them or modify them in various ways.
1.191     harris41 12970: 
1.394     bowersj2 12971: =head2 Symbs
1.191     harris41 12972: 
1.394     bowersj2 12973: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12974: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12975: map, the resource number of the resource in the map, and the URL of
                   12976: the resource itself. The latter is somewhat redundant, but might help
                   12977: if maps change.
                   12978: 
                   12979: An example is
                   12980: 
                   12981:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12982: 
                   12983: The respective map entry is
                   12984: 
                   12985:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12986:   title="Problem 2">
                   12987:  </resource>
                   12988: 
                   12989: Symbs are used by the random number generator, as well as to store and
                   12990: restore data specific to a certain instance of for example a problem.
                   12991: 
                   12992: =head2 Storing And Retrieving Data
                   12993: 
                   12994: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12995: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12996: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12997: is is the non-critical message twin of cstore. These functions are for
                   12998: handlers to store a perl hash to a user's permanent data space in an
                   12999: easy manner, and to retrieve it again on another call. It is expected
                   13000: that a handler would use this once at the beginning to retrieve data,
                   13001: and then again once at the end to send only the new data back.
                   13002: 
                   13003: The data is stored in the user's data directory on the user's
                   13004: homeserver under the ID of the course.
                   13005: 
                   13006: The hash that is returned by restore will have all of the previous
                   13007: value for all of the elements of the hash.
                   13008: 
                   13009: Example:
                   13010: 
                   13011:  #creating a hash
                   13012:  my %hash;
                   13013:  $hash{'foo'}='bar';
                   13014: 
                   13015:  #storing it
                   13016:  &Apache::lonnet::cstore(\%hash);
                   13017: 
                   13018:  #changing a value
                   13019:  $hash{'foo'}='notbar';
                   13020: 
                   13021:  #adding a new value
                   13022:  $hash{'bar'}='foo';
                   13023:  &Apache::lonnet::cstore(\%hash);
                   13024: 
                   13025:  #retrieving the hash
                   13026:  my %history=&Apache::lonnet::restore();
                   13027: 
                   13028:  #print the hash
                   13029:  foreach my $key (sort(keys(%history))) {
                   13030:    print("\%history{$key} = $history{$key}");
                   13031:  }
                   13032: 
                   13033: Will print out:
1.191     harris41 13034: 
1.394     bowersj2 13035:  %history{1:foo} = bar
                   13036:  %history{1:keys} = foo:timestamp
                   13037:  %history{1:timestamp} = 990455579
                   13038:  %history{2:bar} = foo
                   13039:  %history{2:foo} = notbar
                   13040:  %history{2:keys} = foo:bar:timestamp
                   13041:  %history{2:timestamp} = 990455580
                   13042:  %history{bar} = foo
                   13043:  %history{foo} = notbar
                   13044:  %history{timestamp} = 990455580
                   13045:  %history{version} = 2
                   13046: 
                   13047: Note that the special hash entries C<keys>, C<version> and
                   13048: C<timestamp> were added to the hash. C<version> will be equal to the
                   13049: total number of versions of the data that have been stored. The
                   13050: C<timestamp> attribute will be the UNIX time the hash was
                   13051: stored. C<keys> is available in every historical section to list which
                   13052: keys were added or changed at a specific historical revision of a
                   13053: hash.
                   13054: 
                   13055: B<Warning>: do not store the hash that restore returns directly. This
                   13056: will cause a mess since it will restore the historical keys as if the
                   13057: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13058: 
1.394     bowersj2 13059: Calling convention:
1.191     harris41 13060: 
1.1225    raeburn  13061:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  13062:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13063: 
1.394     bowersj2 13064: For more detailed information, see lonnet specific documentation.
1.191     harris41 13065: 
1.394     bowersj2 13066: =head1 RETURN MESSAGES
1.191     harris41 13067: 
1.394     bowersj2 13068: =over 4
1.191     harris41 13069: 
1.394     bowersj2 13070: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13071: 
1.394     bowersj2 13072: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13073: when the connection is brought back up
1.191     harris41 13074: 
1.394     bowersj2 13075: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13076: for later delivery
1.191     harris41 13077: 
1.967     bisitz   13078: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13079: 
1.394     bowersj2 13080: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13081: that was requested
1.191     harris41 13082: 
1.243     albertel 13083: =back
1.191     harris41 13084: 
1.243     albertel 13085: =head1 PUBLIC SUBROUTINES
1.191     harris41 13086: 
1.243     albertel 13087: =head2 Session Environment Functions
1.191     harris41 13088: 
1.243     albertel 13089: =over 4
1.191     harris41 13090: 
1.394     bowersj2 13091: =item * 
                   13092: X<appenv()>
1.949     raeburn  13093: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13094: the user envirnoment file, and will be restored for each access this
1.620     albertel 13095: user makes during this session, also modifies the %env for the current
1.949     raeburn  13096: process. Optional rolesarrayref - if defined contains a reference to an array
                   13097: of roles which are exempt from the restriction on modifying user.role entries 
                   13098: in the user's environment.db and in %env.    
1.191     harris41 13099: 
                   13100: =item *
1.394     bowersj2 13101: X<delenv()>
1.987     raeburn  13102: B<delenv($delthis,$regexp)>: removes all items from the session
                   13103: environment file that begin with $delthis. If the 
                   13104: optional second arg - $regexp - is true, $delthis is treated as a 
                   13105: regular expression, otherwise \Q$delthis\E is used. 
                   13106: The values are also deleted from the current processes %env.
1.191     harris41 13107: 
1.795     albertel 13108: =item * get_env_multiple($name) 
                   13109: 
                   13110: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13111: values may be defined and end up as an array ref.
                   13112: 
                   13113: returns an array of values
                   13114: 
1.243     albertel 13115: =back
                   13116: 
                   13117: =head2 User Information
1.191     harris41 13118: 
1.243     albertel 13119: =over 4
1.191     harris41 13120: 
                   13121: =item *
1.394     bowersj2 13122: X<queryauthenticate()>
                   13123: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13124: authentication scheme
                   13125: 
                   13126: =item *
1.394     bowersj2 13127: X<authenticate()>
1.1073    raeburn  13128: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13129: authenticate user from domain's lib servers (first use the current
                   13130: one). C<$upass> should be the users password.
1.1073    raeburn  13131: $checkdefauth is optional (value is 1 if a check should be made to
                   13132:    authenticate user using default authentication method, and allow
                   13133:    account creation if username does not have account in the domain).
                   13134: $clientcancheckhost is optional (value is 1 if checking whether the
                   13135:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13136: 
                   13137: =item *
1.394     bowersj2 13138: X<homeserver()>
                   13139: B<homeserver($uname,$udom)>: find the server which has
                   13140: the user's directory and files (there must be only one), this caches
                   13141: the answer, and also caches if there is a borken connection.
1.191     harris41 13142: 
                   13143: =item *
1.394     bowersj2 13144: X<idget()>
                   13145: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   13146: (IDs are a unique resource in a domain, there must be only 1 ID per
                   13147: username, and only 1 username per ID in a specific domain) (returns
                   13148: hash: id=>name,id=>name)
1.191     harris41 13149: 
                   13150: =item *
1.394     bowersj2 13151: X<idrget()>
                   13152: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13153: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13154: 
                   13155: =item *
1.394     bowersj2 13156: X<idput()>
                   13157: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 13158: 
                   13159: =item *
1.394     bowersj2 13160: X<rolesinit()>
1.1169    droeschl 13161: B<rolesinit($udom,$username)>: get user privileges.
                   13162: returns user role, first access and timer interval hashes
1.243     albertel 13163: 
                   13164: =item *
1.1171    droeschl 13165: X<privileged()>
                   13166: B<privileged($username,$domain)>: returns a true if user has a
                   13167: privileged and active role (i.e. su or dc), false otherwise.
                   13168: 
                   13169: =item *
1.551     albertel 13170: X<getsection()>
                   13171: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13172: course $cname, return section name/number or '' for "not in course"
                   13173: and '-1' for "no section"
                   13174: 
                   13175: =item *
1.394     bowersj2 13176: X<userenvironment()>
                   13177: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13178: passed in @what from the requested user's environment, returns a hash
                   13179: 
1.858     raeburn  13180: =item * 
                   13181: X<userlog_query()>
1.859     albertel 13182: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13183: activity.log file. %filters defines filters applied when parsing the
                   13184: log file. These can be start or end timestamps, or the type of action
                   13185: - log to look for Login or Logout events, check for Checkin or
                   13186: Checkout, role for role selection. The response is in the form
                   13187: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13188: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13189: 
1.243     albertel 13190: =back
                   13191: 
                   13192: =head2 User Roles
                   13193: 
                   13194: =over 4
                   13195: 
                   13196: =item *
                   13197: 
1.1284    raeburn  13198: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13199: returns codes for allowed actions.
                   13200: 
                   13201: The first argument is required, all others are optional.
                   13202: 
                   13203: $priv is the privilege being checked.
                   13204: $uri contains additional information about what is being checked for access (e.g.,
                   13205: URL, course ID etc.). 
                   13206: $symb is the unique resource instance identifier in a course; if needed,
                   13207: but not provided, it will be retrieved via a call to &symbread(). 
                   13208: $role is the role for which a priv is being checked (only used if priv is evb). 
                   13209: $clientip is the user's IP address (only used when checking for access to portfolio 
                   13210: files).
                   13211: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   13212: prevents recursive calls to &allowed.
                   13213: 
1.243     albertel 13214:  F: full access
                   13215:  U,I,K: authentication modes (cxx only)
                   13216:  '': forbidden
                   13217:  1: user needs to choose course
                   13218:  2: browse allowed
1.766     albertel 13219:  A: passphrase authentication needed
1.1284    raeburn  13220:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13221: 
                   13222: =item *
                   13223: 
1.1192    raeburn  13224: constructaccess($url,$setpriv) : check for access to construction space URL
                   13225: 
                   13226: See if the owner domain and name in the URL match those in the
                   13227: expected environment.  If so, return three element list
                   13228: ($ownername,$ownerdomain,$ownerhome).
                   13229: 
                   13230: Otherwise return the null string.
                   13231: 
                   13232: If second argument 'setpriv' is true, it assigns the privileges,
                   13233: and returns the same three element list, unless the owner has
                   13234: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13235: in which case the null string is returned.
                   13236: 
                   13237: =item *
                   13238: 
1.243     albertel 13239: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   13240: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   13241: and course level
                   13242: 
                   13243: =item *
                   13244: 
1.988     raeburn  13245: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13246: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13247: $type is Course (default) or Community.
1.988     raeburn  13248: If $forcedefault evaluates to true, text returned will be default 
                   13249: text for $type. Otherwise, if this is a course, the text returned 
                   13250: will be a custom name for the role (if defined in the course's 
                   13251: environment).  If no custom name is defined the default is returned.
                   13252:    
1.832     raeburn  13253: =item *
                   13254: 
1.1219    raeburn  13255: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13256: All arguments are optional. Returns a hash of a roles, either for
                   13257: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13258: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13259: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13260: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13261: For each key, value is set to colon-separated start and end times for
                   13262: the role.  If no username and domain are specified, will default to
1.934     raeburn  13263: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13264: of role statuses (active, future or previous), roles 
                   13265: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13266: to restrict the list of roles reported. If no array ref is 
                   13267: provided for types, will default to return only active roles.
1.834     albertel 13268: 
1.1195    raeburn  13269: =item *
                   13270: 
                   13271: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  13272: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   13273: 
                   13274: Additional optional arguments are: $type (if role checking is to be restricted 
                   13275: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  13276: available roles) or future (roles available in the future), and
                   13277: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  13278: have active Domain Coordinator role in course's domain or in additional
                   13279: domains (specified in 'Domains to check for privileged users' in course
                   13280: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13281: 
                   13282: =item *
                   13283: 
                   13284: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13285: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13286: $possdomains and $possroles are optional array refs -- to domains to check and
                   13287: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13288: users' roles.db to check for a dc or su role in any domain. This can be
                   13289: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13290: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13291: this then allows &privileged_by_domain() to be used, which caches the identity
                   13292: of privileged users, eliminating the need for repeated calls to &dump().
                   13293: 
                   13294: =item *
                   13295: 
                   13296: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13297: where the outer hash keys are domains specified in the $possdomains array ref,
                   13298: next inner hash keys are privileged roles specified in the $roles array ref,
                   13299: and the innermost hash contains key = value pairs for username:domain = end:start
                   13300: for active or future "privileged" users with that role in that domain. To avoid
                   13301: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13302: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  13303: 
1.243     albertel 13304: =back
                   13305: 
                   13306: =head2 User Modification
                   13307: 
                   13308: =over 4
                   13309: 
                   13310: =item *
                   13311: 
1.957     raeburn  13312: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13313: user for the level given by URL.  Optional start and end dates (leave empty
                   13314: string or zero for "no date")
1.191     harris41 13315: 
                   13316: =item *
                   13317: 
1.243     albertel 13318: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13319: change a users, password, possible return values are: ok,
                   13320: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13321: refused
1.191     harris41 13322: 
                   13323: =item *
                   13324: 
1.243     albertel 13325: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13326: 
                   13327: =item *
                   13328: 
1.1058    raeburn  13329: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13330:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13331: 
                   13332: will update user information (firstname,middlename,lastname,generation,
                   13333: permanentemail), and if forceid is true, student/employee ID also.
                   13334: A user's institutional affiliation(s) can also be updated.
                   13335: User information fields will not be overwritten with empty entries 
                   13336: unless the field is included in the $candelete array reference.
                   13337: This array is included when a single user is modified via "Manage Users",
                   13338: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13339: 
                   13340: =item *
                   13341: 
1.286     matthew  13342: modifystudent
                   13343: 
1.957     raeburn  13344: modify a student's enrollment and identification information.
1.1235    raeburn  13345: The course id is resolved based on the current user's environment.  
                   13346: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13347: associated with a course.
                   13348: 
1.297     matthew  13349: This call is essentially a wrapper for lonnet::modifyuser and
                   13350: lonnet::modify_student_enrollment
1.286     matthew  13351: 
                   13352: Inputs: 
                   13353: 
                   13354: =over 4
                   13355: 
1.957     raeburn  13356: =item B<$udom> Student's loncapa domain
1.286     matthew  13357: 
1.957     raeburn  13358: =item B<$uname> Student's loncapa login name
1.286     matthew  13359: 
1.964     bisitz   13360: =item B<$uid> Student/Employee ID
1.286     matthew  13361: 
1.957     raeburn  13362: =item B<$umode> Student's authentication mode
1.286     matthew  13363: 
1.957     raeburn  13364: =item B<$upass> Student's password
1.286     matthew  13365: 
1.957     raeburn  13366: =item B<$first> Student's first name
1.286     matthew  13367: 
1.957     raeburn  13368: =item B<$middle> Student's middle name
1.286     matthew  13369: 
1.957     raeburn  13370: =item B<$last> Student's last name
1.286     matthew  13371: 
1.957     raeburn  13372: =item B<$gene> Student's generation
1.286     matthew  13373: 
1.957     raeburn  13374: =item B<$usec> Student's section in course
1.286     matthew  13375: 
                   13376: =item B<$end> Unix time of the roles expiration
                   13377: 
                   13378: =item B<$start> Unix time of the roles start date
                   13379: 
                   13380: =item B<$forceid> If defined, allow $uid to be changed
                   13381: 
                   13382: =item B<$desiredhome> server to use as home server for student
                   13383: 
1.957     raeburn  13384: =item B<$email> Student's permanent e-mail address
                   13385: 
                   13386: =item B<$type> Type of enrollment (auto or manual)
                   13387: 
1.963     raeburn  13388: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13389: 
                   13390: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13391: 
1.963     raeburn  13392: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13393: 
1.963     raeburn  13394: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13395: 
1.1216    raeburn  13396: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13397: 
                   13398: =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  13399: 
1.286     matthew  13400: =back
1.297     matthew  13401: 
                   13402: =item *
                   13403: 
                   13404: modify_student_enrollment
                   13405: 
1.1235    raeburn  13406: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13407: 'role.request.course' must be defined for this function to proceed.
                   13408: 
                   13409: Inputs:
                   13410: 
                   13411: =over 4
                   13412: 
1.1235    raeburn  13413: =item $udom, student's domain
1.297     matthew  13414: 
1.1235    raeburn  13415: =item $uname, student's name
1.297     matthew  13416: 
1.1235    raeburn  13417: =item $uid, student's user id
1.297     matthew  13418: 
1.1235    raeburn  13419: =item $first, student's first name
1.297     matthew  13420: 
                   13421: =item $middle
                   13422: 
                   13423: =item $last
                   13424: 
                   13425: =item $gene
                   13426: 
                   13427: =item $usec
                   13428: 
                   13429: =item $end
                   13430: 
                   13431: =item $start
                   13432: 
1.957     raeburn  13433: =item $type
                   13434: 
                   13435: =item $locktype
                   13436: 
                   13437: =item $cid
                   13438: 
                   13439: =item $selfenroll
                   13440: 
                   13441: =item $context
                   13442: 
1.1216    raeburn  13443: =item $credits, number of credits student will earn from this class
                   13444: 
1.297     matthew  13445: =back
                   13446: 
1.191     harris41 13447: 
                   13448: =item *
                   13449: 
1.243     albertel 13450: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13451: custom role; give a custom role to a user for the level given by URL.  Specify
                   13452: name and domain of role author, and role name
1.191     harris41 13453: 
                   13454: =item *
                   13455: 
1.243     albertel 13456: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13457: 
                   13458: =item *
                   13459: 
1.243     albertel 13460: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13461: 
                   13462: =back
                   13463: 
                   13464: =head2 Course Infomation
                   13465: 
                   13466: =over 4
1.191     harris41 13467: 
                   13468: =item *
                   13469: 
1.1118    foxr     13470: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13471: specified course id, including all environment settings for the
                   13472: course, the description of the course will be in the hash under the
                   13473: key 'description'
1.191     harris41 13474: 
1.1118    foxr     13475: $options is an optional parameter that if supplied is a hash reference that controls
                   13476: what how this function works.  It has the following key/values:
                   13477: 
                   13478: =over 4
                   13479: 
                   13480: =item freshen_cache
                   13481: 
                   13482: If defined, and the environment cache for the course is valid, it is 
                   13483: returned in the returned hash.
                   13484: 
                   13485: =item one_time
                   13486: 
                   13487: If defined, the last cache time is set to _now_
                   13488: 
                   13489: =item user
                   13490: 
                   13491: If defined, the supplied username is used instead of the current user.
                   13492: 
                   13493: 
                   13494: =back
                   13495: 
1.191     harris41 13496: =item *
                   13497: 
1.624     albertel 13498: resdata($name,$domain,$type,@which) : request for current parameter
                   13499: setting for a specific $type, where $type is either 'course' or 'user',
                   13500: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  13501: answers for 10 minutes.
1.243     albertel 13502: 
1.877     foxr     13503: =item *
                   13504: 
                   13505: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13506: data base, returning a hash that is keyed by the resource name and has
                   13507: values that are the resource value.  I believe that the timestamps and
                   13508: versions are also returned.
                   13509: 
1.1236    raeburn  13510: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13511: supplemental content area. This routine caches the number of files for 
                   13512: 10 minutes.
                   13513: 
1.243     albertel 13514: =back
                   13515: 
                   13516: =head2 Course Modification
                   13517: 
                   13518: =over 4
1.191     harris41 13519: 
                   13520: =item *
                   13521: 
1.243     albertel 13522: writecoursepref($courseid,%prefs) : write preferences (environment
                   13523: database) for a course
1.191     harris41 13524: 
                   13525: =item *
                   13526: 
1.1011    raeburn  13527: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13528: 
                   13529: =item *
                   13530: 
1.1038    raeburn  13531: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13532: 
1.1167    droeschl 13533: =item *
                   13534: 
                   13535: is_course($courseid), is_course($cdom, $cnum)
                   13536: 
                   13537: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13538: two component version $cdom, $cnum. It checks if the specified course exists.
                   13539: 
                   13540: Returns:
                   13541:     undef if the course doesn't exist, otherwise
                   13542:     in scalar context the combined courseid.
                   13543:     in list context the two components of the course identifier, domain and 
                   13544:     courseid.    
                   13545: 
1.243     albertel 13546: =back
                   13547: 
                   13548: =head2 Resource Subroutines
                   13549: 
                   13550: =over 4
1.191     harris41 13551: 
                   13552: =item *
                   13553: 
1.243     albertel 13554: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13555: 
                   13556: =item *
                   13557: 
1.243     albertel 13558: repcopy($filename) : subscribes to the requested file, and attempts to
                   13559: replicate from the owning library server, Might return
1.607     raeburn  13560: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13561: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13562: resource. Expects the local filesystem pathname
                   13563: (/home/httpd/html/res/....)
                   13564: 
                   13565: =back
                   13566: 
                   13567: =head2 Resource Information
                   13568: 
                   13569: =over 4
1.191     harris41 13570: 
                   13571: =item *
                   13572: 
1.1228    raeburn  13573: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13574: and returns the value of a variety of different possible values,
                   13575: $varname should be a request string, and the other parameters can be
                   13576: used to specify who and what one is asking about. Ordinarily, $cid 
                   13577: does not need to be specified, as it is retrived from 
                   13578: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13579: within lonuserstate::loadmap() when initializing a course, before
                   13580: $env{'request.course.id'} has been set, so it needs to be provided
                   13581: in that one case.
1.243     albertel 13582: 
                   13583: Possible values for $varname are environment.lastname (or other item
                   13584: from the envirnment hash), user.name (or someother aspect about the
                   13585: user), resource.0.maxtries (or some other part and parameter of a
                   13586: resource)
1.204     albertel 13587: 
                   13588: =item *
                   13589: 
1.243     albertel 13590: directcondval($number) : get current value of a condition; reads from a state
                   13591: string
1.204     albertel 13592: 
                   13593: =item *
                   13594: 
1.243     albertel 13595: condval($condidx) : value of condition index based on state
1.204     albertel 13596: 
                   13597: =item *
                   13598: 
1.243     albertel 13599: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13600: resource's metadata, $what should be either a specific key, or either
                   13601: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13602: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13603: 
                   13604: this function automatically caches all requests
1.191     harris41 13605: 
                   13606: =item *
                   13607: 
1.243     albertel 13608: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13609: network of library servers; returns file handle of where SQL and regex results
                   13610: will be stored for query
1.191     harris41 13611: 
                   13612: =item *
                   13613: 
1.1282    raeburn  13614: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   13615: return symbolic list entry (all arguments optional). 
                   13616: 
                   13617: Args: filename is the filename (including path) for the file for which a symb 
                   13618: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   13619: to check access status if more than one resource was found in the bighash 
                   13620: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   13621: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   13622: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   13623: cause possible symbs to be checked to determine if they are subject to content
                   13624: blocking, if so they will not be included as possible symbs; possibles is a
                   13625: ref to a hash, which, as a side effect, will be populated with all possible 
                   13626: symbs (content blocking not tested).
                   13627:  
1.243     albertel 13628: returns the data handle
1.191     harris41 13629: 
                   13630: =item *
                   13631: 
1.1190    raeburn  13632: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   13633: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13634: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  13635: on failure, user must be in a course, as it assumes the existence of
                   13636: the course initial hash, and uses $env('request.course.id'}.  The third
                   13637: arg is an optional reference to a scalar.  If this arg is passed in the 
                   13638: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13639: encrypted; otherwise it will be null.  
1.191     harris41 13640: 
                   13641: =item *
                   13642: 
1.243     albertel 13643: symbclean($symb) : removes versions numbers from a symb, returns the
                   13644: cleaned symb
1.191     harris41 13645: 
                   13646: =item *
                   13647: 
1.243     albertel 13648: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13649: course map, user must be in a course for it to work.
1.191     harris41 13650: 
                   13651: =item *
                   13652: 
1.243     albertel 13653: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13654: 
                   13655: =item *
                   13656: 
1.243     albertel 13657: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13658: a random seed, all arguments are optional, if they aren't sent it uses the
                   13659: environment to derive them. Note: if symb isn't sent and it can't get one
                   13660: from &symbread it will use the current time as its return value
1.191     harris41 13661: 
                   13662: =item *
                   13663: 
1.243     albertel 13664: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13665: unfakeable, receipt
1.191     harris41 13666: 
                   13667: =item *
                   13668: 
1.620     albertel 13669: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13670: 
                   13671: =item *
                   13672: 
1.243     albertel 13673: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13674: 
                   13675: =item *
                   13676: 
1.243     albertel 13677: 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 13678: 
                   13679: =item *
                   13680: 
1.243     albertel 13681: 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 13682: 
                   13683: =item *
                   13684: 
1.243     albertel 13685: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13686: 
                   13687: =item *
                   13688: 
1.243     albertel 13689: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13690: forcing spreadsheet to reevaluate the resource scores next time.
                   13691: 
1.1195    raeburn  13692: =item * 
                   13693: 
1.1196    raeburn  13694: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13695: when viewing in course context.
1.1195    raeburn  13696: 
1.1196    raeburn  13697:  input: six args -- filename (decluttered), course number, course domain,
                   13698:                     url, symb (if registered) and group (if this is a 
                   13699:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  13700: 
1.1196    raeburn  13701:  output: array of five scalars --
1.1195    raeburn  13702:          $cfile -- url for file editing if editable on current server
                   13703:          $home -- homeserver of resource (i.e., for author if published,
                   13704:                                           or course if uploaded.).
                   13705:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  13706:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   13707:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  13708: 
                   13709: =item *
                   13710: 
                   13711: is_course_upload($file,$cnum,$cdom)
                   13712: 
                   13713: Used in course context to determine if current file was uploaded to 
                   13714: the course (i.e., would be found in /userfiles/docs on the course's 
                   13715: homeserver.
                   13716: 
                   13717:   input: 3 args -- filename (decluttered), course number and course domain.
                   13718:   output: boolean -- 1 if file was uploaded.
                   13719: 
1.243     albertel 13720: =back
                   13721: 
                   13722: =head2 Storing/Retreiving Data
                   13723: 
                   13724: =over 4
1.191     harris41 13725: 
                   13726: =item *
                   13727: 
1.1269    raeburn  13728: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   13729: permanently for this url; hashref needs to be given and should be a \%hashname;
                   13730: the remaining args aren't required and if they aren't passed or are '' they will
                   13731: be derived from the env (with the exception of $laststore, which is an 
                   13732: optional arg used when a user's submission is stored in grading).
                   13733: $laststore is $version=$timestamp, where $version is the most recent version
                   13734: number retrieved for the corresponding $symb in the $namespace db file, and
                   13735: $timestamp is the timestamp for that transaction (UNIX time).
                   13736: $laststore is currently only passed when cstore() is called by 
                   13737: structuretags::finalize_storage().
1.191     harris41 13738: 
                   13739: =item *
                   13740: 
1.1269    raeburn  13741: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   13742: but uses critical subroutine
1.191     harris41 13743: 
                   13744: =item *
                   13745: 
1.243     albertel 13746: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13747: all args are optional
1.191     harris41 13748: 
                   13749: =item *
                   13750: 
1.717     albertel 13751: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13752: dumps the complete (or key matching regexp) namespace into a hash
                   13753: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13754: normally &store()ed into
                   13755: 
                   13756: $range should be either an integer '100' (give me the first 100
                   13757:                                            matching records)
                   13758:               or be  two integers sperated by a - with no spaces
                   13759:                  '30-50' (give me the 30th through the 50th matching
                   13760:                           records)
                   13761: 
                   13762: 
                   13763: =item *
                   13764: 
1.1269    raeburn  13765: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 13766: replaces a &store() version of data with a replacement set of data
                   13767: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  13768: reference. If $tolog is true, the transaction is logged in the courselog
                   13769: with an action=PUTSTORE.
1.717     albertel 13770: 
                   13771: =item *
                   13772: 
1.243     albertel 13773: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13774: works very similar to store/cstore, but all data is stored in a
                   13775: temporary location and can be reset using tmpreset, $storehash should
                   13776: be a hash reference, returns nothing on success
1.191     harris41 13777: 
                   13778: =item *
                   13779: 
1.243     albertel 13780: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13781: similar to restore, but all data is stored in a temporary location and
                   13782: can be reset using tmpreset. Returns a hash of values on success,
                   13783: error string otherwise.
1.191     harris41 13784: 
                   13785: =item *
                   13786: 
1.243     albertel 13787: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13788: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13789: 
                   13790: =item *
                   13791: 
1.243     albertel 13792: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13793: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13794: 
                   13795: =item *
                   13796: 
1.243     albertel 13797: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13798: namesp ($udom and $uname are optional)
1.191     harris41 13799: 
                   13800: =item *
                   13801: 
1.702     albertel 13802: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13803: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13804: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13805: 
1.702     albertel 13806: $range should be either an integer '100' (give me the first 100
                   13807:                                            matching records)
                   13808:               or be  two integers sperated by a - with no spaces
                   13809:                  '30-50' (give me the 30th through the 50th matching
                   13810:                           records)
1.449     matthew  13811: =item *
                   13812: 
                   13813: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13814: $store can be a scalar, an array reference, or if the amount to be 
                   13815: incremented is > 1, a hash reference.
                   13816: 
                   13817: ($udom and $uname are optional)
1.191     harris41 13818: 
                   13819: =item *
                   13820: 
1.243     albertel 13821: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13822: ($udom and $uname are optional)
1.191     harris41 13823: 
                   13824: =item *
                   13825: 
1.243     albertel 13826: cput($namespace,$storehash,$udom,$uname) : critical put
                   13827: ($udom and $uname are optional)
1.191     harris41 13828: 
                   13829: =item *
                   13830: 
1.748     albertel 13831: newput($namespace,$storehash,$udom,$uname) :
                   13832: 
                   13833: Attempts to store the items in the $storehash, but only if they don't
                   13834: currently exist, if this succeeds you can be certain that you have 
                   13835: successfully created a new key value pair in the $namespace db.
                   13836: 
                   13837: 
                   13838: Args:
                   13839:  $namespace: name of database to store values to
                   13840:  $storehash: hashref to store to the db
                   13841:  $udom: (optional) domain of user containing the db
                   13842:  $uname: (optional) name of user caontaining the db
                   13843: 
                   13844: Returns:
                   13845:  'ok' -> succeeded in storing all keys of $storehash
                   13846:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13847:                         least <key> already existed in the db (other
                   13848:                         requested keys may also already exist)
1.967     bisitz   13849:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13850:  'con_lost' -> unable to contact request server
                   13851:  'refused' -> action was not allowed by remote machine
                   13852: 
                   13853: 
                   13854: =item *
                   13855: 
1.243     albertel 13856: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13857: reference filled in from namesp (encrypts the return communication)
                   13858: ($udom and $uname are optional)
1.191     harris41 13859: 
                   13860: =item *
                   13861: 
1.243     albertel 13862: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13863: critical subroutine
                   13864: 
1.806     raeburn  13865: =item *
                   13866: 
1.860     raeburn  13867: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13868: array reference filled in from namespace found in domain level on either
                   13869: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13870: 
                   13871: =item *
                   13872: 
1.860     raeburn  13873: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13874: domain level either on specified domain server ($uhome) or primary domain 
                   13875: server ($udom and $uhome are optional)
1.806     raeburn  13876: 
1.943     raeburn  13877: =item * 
                   13878: 
1.1240    raeburn  13879: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   13880: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13881: the target domain.
                   13882: 
                   13883: May also include additional key => value pairs for the following groups:
                   13884: 
                   13885: =over
                   13886: 
                   13887: =item
                   13888: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13889: 
                   13890: =over
                   13891: 
                   13892: =item defaultquota, authorquota
                   13893: 
                   13894: =back
                   13895: 
                   13896: =item
                   13897: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13898: portfolio for users).
                   13899: 
                   13900: =over
                   13901: 
                   13902: =item
                   13903: aboutme, blog, webdav, portfolio
                   13904: 
                   13905: =back
                   13906: 
                   13907: =item
                   13908: requestcourses: ability to request courses, and how requests are processed.
                   13909: 
                   13910: =over
                   13911: 
                   13912: =item
1.1246    raeburn  13913: official, unofficial, community, textbook
1.1240    raeburn  13914: 
                   13915: =back
                   13916: 
                   13917: =item
                   13918: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13919: 
                   13920: =over
                   13921: 
                   13922: =item
1.1256    raeburn  13923: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  13924: 
                   13925: =back
                   13926: 
                   13927: =item
                   13928: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13929: for course's uploaded content.
                   13930: 
                   13931: =over
                   13932: 
                   13933: =item
1.1246    raeburn  13934: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
                   13935: communityquota, textbookquota
1.1240    raeburn  13936: 
                   13937: =back
                   13938: 
                   13939: =item
                   13940: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13941: on your servers.
                   13942: 
                   13943: =over
                   13944: 
                   13945: =item 
                   13946: remotesessions, hostedsessions
                   13947: 
                   13948: =back
                   13949: 
                   13950: =back
                   13951: 
                   13952: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13953: utility to create a configuration.db file on a domain's primary library server 
                   13954: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13955: -- corresponding values are authentication type (internal, krb4, krb5,
                   13956: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   13957: will be available. Values are retrieved from cache (if current), unless the
                   13958: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13959: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13960: 
                   13961: Typical usage:
1.943     raeburn  13962: 
1.1240    raeburn  13963: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13964: 
1.243     albertel 13965: =back
                   13966: 
                   13967: =head2 Network Status Functions
                   13968: 
                   13969: =over 4
1.191     harris41 13970: 
                   13971: =item *
                   13972: 
1.1137    raeburn  13973: dirlist() : return directory list based on URI (first arg).
                   13974: 
                   13975: Inputs: 1 required, 5 optional.
                   13976: 
                   13977: =over
                   13978: 
                   13979: =item 
                   13980: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13981: 
                   13982: =item
                   13983: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13984: 
                   13985: =item
                   13986: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13987: 
                   13988: =item
                   13989: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13990: 
                   13991: =item
                   13992: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13993: 
                   13994: =item 
                   13995: $alternateRoot - path to prepend in place of path from $uri.
                   13996: 
                   13997: =back
                   13998: 
                   13999: Returns: Array of up to two items.
                   14000: 
                   14001: =over
                   14002: 
                   14003: a reference to an array of files/subdirectories
                   14004: 
                   14005: =over
                   14006: 
                   14007: Each element in the array of files/subdirectories is a & separated list of
                   14008: item name and the result of running stat on the item.  If dirlist was requested
                   14009: for a file instead of a directory, the item name will be ''. For a directory 
                   14010: listing, if the item is a metadata file, the element will end &N&M 
                   14011: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14012: default copyright set (1).  
                   14013: 
                   14014: =back
                   14015: 
                   14016: a scalar containing error condition (if encountered).
                   14017: 
                   14018: =over
                   14019: 
                   14020: =item 
                   14021: no_host (no homeserver identified for $username:$domain).
                   14022: 
                   14023: =item 
                   14024: no_such_host (server contacted for listing not identified as valid host).
                   14025: 
                   14026: =item 
                   14027: con_lost (connection to remote server failed).
                   14028: 
                   14029: =item 
                   14030: refused (invalid $username:$domain received on lond side).
                   14031: 
                   14032: =item 
                   14033: no_such_dir (directory at specified path on lond side does not exist). 
                   14034: 
                   14035: =item 
                   14036: empty (directory at specified path on lond side is empty).
                   14037: 
                   14038: =over
                   14039: 
                   14040: This is currently not encountered because the &ls3, &ls2, 
                   14041: &ls (_handler) routines on the lond side do not filter out
                   14042: . and .. from a directory listing. 
                   14043: 
                   14044: =back
                   14045: 
                   14046: =back
                   14047: 
                   14048: =back
1.191     harris41 14049: 
                   14050: =item *
                   14051: 
1.243     albertel 14052: spareserver() : find server with least workload from spare.tab
                   14053: 
1.986     foxr     14054: 
                   14055: =item *
                   14056: 
                   14057: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14058: if there is no corresponding loncapa host.
                   14059: 
1.243     albertel 14060: =back
                   14061: 
1.986     foxr     14062: 
1.243     albertel 14063: =head2 Apache Request
                   14064: 
                   14065: =over 4
1.191     harris41 14066: 
                   14067: =item *
                   14068: 
1.243     albertel 14069: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14070: localhost, posts hash
                   14071: 
                   14072: =back
                   14073: 
                   14074: =head2 Data to String to Data
                   14075: 
                   14076: =over 4
1.191     harris41 14077: 
                   14078: =item *
                   14079: 
1.243     albertel 14080: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14081: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14082: 
                   14083: =item *
                   14084: 
1.243     albertel 14085: hashref2str($hashref) : convert a hashref into a string complete with
                   14086: escaping and '=' and '&' separators, supports elements that are
                   14087: arrayrefs and hashrefs
1.191     harris41 14088: 
                   14089: =item *
                   14090: 
1.243     albertel 14091: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14092: with escaping and '&' separators, supports elements that are arrayrefs
                   14093: and hashrefs
1.191     harris41 14094: 
                   14095: =item *
                   14096: 
1.243     albertel 14097: str2hash($string) : convert string to hash using unescaping and
                   14098: splitting on '=' and '&', supports elements that are arrayrefs and
                   14099: hashrefs
1.191     harris41 14100: 
                   14101: =item *
                   14102: 
1.243     albertel 14103: str2array($string) : convert string to hash using unescaping and
                   14104: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14105: 
                   14106: =back
                   14107: 
                   14108: =head2 Logging Routines
                   14109: 
                   14110: 
                   14111: These routines allow one to make log messages in the lonnet.log and
                   14112: lonnet.perm logfiles.
1.191     harris41 14113: 
1.1119    foxr     14114: =over 4
                   14115: 
1.191     harris41 14116: =item *
                   14117: 
1.243     albertel 14118: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14119: 
                   14120: =item *
                   14121: 
1.243     albertel 14122: logthis() : append message to the normal lonnet.log file, it gets
                   14123: preiodically rolled over and deleted.
1.191     harris41 14124: 
                   14125: =item *
                   14126: 
1.243     albertel 14127: logperm() : append a permanent message to lonnet.perm.log, this log
                   14128: file never gets deleted by any automated portion of the system, only
                   14129: messages of critical importance should go in here.
                   14130: 
1.1119    foxr     14131: 
1.243     albertel 14132: =back
                   14133: 
                   14134: =head2 General File Helper Routines
                   14135: 
                   14136: =over 4
1.191     harris41 14137: 
                   14138: =item *
                   14139: 
1.481     raeburn  14140: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14141: (a) files in /uploaded
                   14142:   (i) If a local copy of the file exists - 
                   14143:       compares modification date of local copy with last-modified date for 
                   14144:       definitive version stored on home server for course. If local copy is 
                   14145:       stale, requests a new version from the home server and stores it. 
                   14146:       If the original has been removed from the home server, then local copy 
                   14147:       is unlinked.
                   14148:   (ii) If local copy does not exist -
                   14149:       requests the file from the home server and stores it. 
                   14150:   
                   14151:   If $caller is 'uploadrep':  
                   14152:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14153:     for request for files originally uploaded via DOCS. 
                   14154:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14155:   
                   14156:   Otherwise:
                   14157:      This indicates a call from the content generation phase of the request.
                   14158:      -  returns the entire contents of the file or -1.
                   14159:      
                   14160: (b) files in /res
                   14161:    - returns the entire contents of a file or -1; 
                   14162:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14163: 
1.712     albertel 14164: 
                   14165: =item *
                   14166: 
                   14167: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14168:                   reference
                   14169: 
                   14170: returns either a stat() list of data about the file or an empty list
                   14171: if the file doesn't exist or couldn't find out about it (connection
                   14172: problems or user unknown)
                   14173: 
1.191     harris41 14174: =item *
                   14175: 
1.243     albertel 14176: filelocation($dir,$file) : returns file system location of a file
                   14177: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14178: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14179: and a file of ../bob will become /a/bob)
1.191     harris41 14180: 
                   14181: =item *
                   14182: 
                   14183: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14184: filelocation except for hrefs
                   14185: 
                   14186: =item *
                   14187: 
1.1261    raeburn  14188: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14189: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14190: 
1.243     albertel 14191: =back
                   14192: 
1.608     albertel 14193: =head2 Usererfile file routines (/uploaded*)
                   14194: 
                   14195: =over 4
                   14196: 
                   14197: =item *
                   14198: 
                   14199: userfileupload(): main rotine for putting a file in a user or course's
                   14200:                   filespace, arguments are,
                   14201: 
1.620     albertel 14202:  formname - required - this is the name of the element in $env where the
1.608     albertel 14203:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14204:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14205:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14206:  context - if coursedoc, store the file in the course of the active role
                   14207:              of the current user; 
                   14208:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14209:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14210:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14211:          if undefined, it will be placed in "unknown"
                   14212: 
                   14213:  (This routine calls clean_filename() to remove any dangerous
                   14214:  characters from the filename, and then calls finuserfileupload() to
                   14215:  complete the transaction)
                   14216: 
                   14217:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14218:  and /adm/notfound.html if unsuccessful
                   14219: 
                   14220: =item *
                   14221: 
                   14222: clean_filename(): routine for cleaing a filename up for storage in
                   14223:                  userfile space, argument is:
                   14224: 
                   14225:  filename - proposed filename
                   14226: 
                   14227: returns: the new clean filename
                   14228: 
                   14229: =item *
                   14230: 
1.1090    raeburn  14231: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14232: userspace, probably shouldn't be called directly
                   14233: 
                   14234:   docuname: username or courseid of destination for the file
                   14235:   docudom: domain of user/course of destination for the file
                   14236:   formname: same as for userfileupload()
1.1090    raeburn  14237:   fname: filename (including subdirectories) for the file
                   14238:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14239:   allfiles: reference to hash used to store objects found by parser
                   14240:   codebase: reference to hash used for codebases of java objects found by parser
                   14241:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14242:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14243:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14244:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14245:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14246:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14247:   mimetype: reference to scalar to accommodate mime type determined
                   14248:             from File::MMagic if $parser = parse.
1.608     albertel 14249: 
                   14250:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14251:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14252:  was 'overwrite').
                   14253:  
1.608     albertel 14254: 
                   14255: =item *
                   14256: 
                   14257: renameuserfile(): renames an existing userfile to a new name
                   14258: 
                   14259:   Args:
                   14260:    docuname: username or courseid of destination for the file
                   14261:    docudom: domain of user/course of destination for the file
                   14262:    old: current file name (including any subdirs under userfiles)
                   14263:    new: desired file name (including any subdirs under userfiles)
                   14264: 
                   14265: =item *
                   14266: 
                   14267: mkdiruserfile(): creates a directory is a userfiles dir
                   14268: 
                   14269:   Args:
                   14270:    docuname: username or courseid of destination for the file
                   14271:    docudom: domain of user/course of destination for the file
                   14272:    dir: dir to create (including any subdirs under userfiles)
                   14273: 
                   14274: =item *
                   14275: 
                   14276: removeuserfile(): removes a file that exists in userfiles
                   14277: 
                   14278:   Args:
                   14279:    docuname: username or courseid of destination for the file
                   14280:    docudom: domain of user/course of destination for the file
                   14281:    fname: filname to delete (including any subdirs under userfiles)
                   14282: 
                   14283: =item *
                   14284: 
                   14285: removeuploadedurl(): convience function for removeuserfile()
                   14286: 
                   14287:   Args:
                   14288:    url:  a full /uploaded/... url to delete
                   14289: 
1.747     albertel 14290: =item * 
                   14291: 
                   14292: get_portfile_permissions():
                   14293:   Args:
                   14294:     domain: domain of user or course contain the portfolio files
                   14295:     user: name of user or num of course contain the portfolio files
                   14296:   Returns:
                   14297:     hashref of a dump of the proper file_permissions.db
                   14298:    
                   14299: 
                   14300: =item * 
                   14301: 
                   14302: get_access_controls():
                   14303: 
                   14304: Args:
                   14305:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14306:   group: (optional) the group you want the files associated with
                   14307:   file: (optional) the file you want access info on
                   14308: 
                   14309: Returns:
1.749     raeburn  14310:     a hash (keys are file names) of hashes containing
                   14311:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14312:         values are XML containing access control settings (see below) 
1.747     albertel 14313: 
                   14314: Internal notes:
                   14315: 
1.749     raeburn  14316:  access controls are stored in file_permissions.db as key=value pairs.
                   14317:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14318:         where scope -> public,guest,course,group,domains or users.
                   14319:               end -> UNIX time for end of access (0 -> no end date)
                   14320:               start -> UNIX time for start of access
                   14321: 
                   14322:     value -> XML description of access control
                   14323:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14324:             <start></start>
                   14325:             <end></end>
                   14326: 
                   14327:             <password></password>  for scope type = guest
                   14328: 
                   14329:             <domain></domain>     for scope type = course or group
                   14330:             <number></number>
                   14331:             <roles id="">
                   14332:              <role></role>
                   14333:              <access></access>
                   14334:              <section></section>
                   14335:              <group></group>
                   14336:             </roles>
                   14337: 
                   14338:             <dom></dom>         for scope type = domains
                   14339: 
                   14340:             <users>             for scope type = users
                   14341:              <user>
                   14342:               <uname></uname>
                   14343:               <udom></udom>
                   14344:              </user>
                   14345:             </users>
                   14346:            </scope> 
                   14347:               
                   14348:  Access data is also aggregated for each file in an additional key=value pair:
                   14349:  key -> path to file/file_name\0accesscontrol 
                   14350:  value -> reference to hash
                   14351:           hash contains key = value pairs
                   14352:           where key = uniqueID:scope_end_start
                   14353:                 value = UNIX time record was last updated
                   14354: 
                   14355:           Used to improve speed of look-ups of access controls for each file.  
                   14356:  
                   14357:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14358: 
1.1198    raeburn  14359: =item *
                   14360: 
1.749     raeburn  14361: modify_access_controls():
                   14362: 
                   14363: Modifies access controls for a portfolio file
                   14364: Args
                   14365: 1. file name
                   14366: 2. reference to hash of required changes,
                   14367: 3. domain
                   14368: 4. username
                   14369:   where domain,username are the domain of the portfolio owner 
                   14370:   (either a user or a course) 
                   14371: 
                   14372: Returns:
                   14373: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14374: 2. result of deletions ('ok' or 'error', with error message).
                   14375: 3. reference to hash of any new or updated access controls.
                   14376: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14377:    key = integer (inbound ID)
1.1198    raeburn  14378:    value = uniqueID
                   14379: 
                   14380: =item *
                   14381: 
                   14382: get_timebased_id():
                   14383: 
                   14384: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   14385: course via the Course Editor (e.g., folders, composite pages, 
                   14386: group bulletin boards).
                   14387: 
                   14388: Args: (first three required; six others optional)
                   14389: 
                   14390: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14391:    docssequence, or name of group
                   14392: 
                   14393: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14394:    e.g., num, boardids
                   14395: 
                   14396: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   14397:    file will be named nohist_namespace.db
                   14398: 
                   14399: 4. cdom: domain of course; default is current course domain from %env
                   14400: 
                   14401: 5. cnum: course number; default is current course number from %env
                   14402: 
                   14403: 6. idtype: set to concat if an additional digit is to be appended to the 
                   14404:    unix timestamp to form the suffix, if the plain timestamp is already
                   14405:    in use.  Default is to not do this, but simply increment the unix 
                   14406:    timestamp by 1 until a unique key is obtained.
                   14407: 
                   14408: 7. who: holder of locking key; defaults to user:domain for user.
                   14409: 
                   14410: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   14411:    retrying); default is 3.
                   14412: 
                   14413: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   14414: 
                   14415: Returns:
                   14416: 
                   14417: 1. suffix obtained (numeric)
                   14418: 
                   14419: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14420: 
                   14421: 3. error: contains (localized) error message if an error occurred.
                   14422: 
1.747     albertel 14423: 
1.608     albertel 14424: =back
                   14425: 
1.243     albertel 14426: =head2 HTTP Helper Routines
                   14427: 
                   14428: =over 4
                   14429: 
1.191     harris41 14430: =item *
                   14431: 
                   14432: escape() : unpack non-word characters into CGI-compatible hex codes
                   14433: 
                   14434: =item *
                   14435: 
                   14436: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14437: 
1.243     albertel 14438: =back
                   14439: 
                   14440: =head1 PRIVATE SUBROUTINES
                   14441: 
                   14442: =head2 Underlying communication routines (Shouldn't call)
                   14443: 
                   14444: =over 4
                   14445: 
                   14446: =item *
                   14447: 
                   14448: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14449: 
                   14450: =item *
                   14451: 
                   14452: reply() : uses subreply to send a message to remote machine, logs all failures
                   14453: 
                   14454: =item *
                   14455: 
                   14456: critical() : passes a critical message to another server; if cannot
                   14457: get through then place message in connection buffer directory and
                   14458: returns con_delayed, if incapable of saving message, returns
                   14459: con_failed
                   14460: 
                   14461: =item *
                   14462: 
                   14463: reconlonc() : tries to reconnect lonc client processes.
                   14464: 
                   14465: =back
                   14466: 
                   14467: =head2 Resource Access Logging
                   14468: 
                   14469: =over 4
                   14470: 
                   14471: =item *
                   14472: 
                   14473: flushcourselogs() : flush (save) buffer logs and access logs
                   14474: 
                   14475: =item *
                   14476: 
                   14477: courselog($what) : save message for course in hash
                   14478: 
                   14479: =item *
                   14480: 
                   14481: courseacclog($what) : save message for course using &courselog().  Perform
                   14482: special processing for specific resource types (problems, exams, quizzes, etc).
                   14483: 
1.191     harris41 14484: =item *
                   14485: 
                   14486: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14487: as a PerlChildExitHandler
1.243     albertel 14488: 
                   14489: =back
                   14490: 
                   14491: =head2 Other
                   14492: 
                   14493: =over 4
                   14494: 
                   14495: =item *
                   14496: 
                   14497: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14498: 
                   14499: =back
                   14500: 
                   14501: =cut
1.877     foxr     14502: 

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