Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1151
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1151 ! raeburn 4: # $Id: lonnet.pm,v 1.1150 2011/12/20 22:40:06 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.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.539 albertel 92: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1117 foxr 99:
1.1090 raeburn 100: use File::Copy;
1.676 albertel 101:
1.195 www 102: my $readit;
1.550 foxr 103: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 104:
1.619 albertel 105: require Exporter;
106:
107: our @ISA = qw (Exporter);
108: our @EXPORT = qw(%env);
109:
1.449 matthew 110:
1.1 albertel 111: # --------------------------------------------------------------------- Logging
1.729 www 112: {
113: my $logid;
114: sub instructor_log {
1.957 raeburn 115: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
116: if (($cnum eq '') || ($cdom eq '')) {
117: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
118: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
119: }
1.729 www 120: $logid++;
1.957 raeburn 121: my $now = time();
122: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 123: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 124: { $id => {
125: 'exe_uname' => $env{'user.name'},
126: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 127: 'exe_time' => $now,
1.730 www 128: 'exe_ip' => $ENV{'REMOTE_ADDR'},
129: 'delflag' => $delflag,
130: 'logentry' => $storehash,
131: 'uname' => $uname,
132: 'udom' => $udom,
133: }
1.957 raeburn 134: },$cdom,$cnum);
1.729 www 135: }
136: }
1.1 albertel 137:
1.163 harris41 138: sub logtouch {
139: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 140: unless (-e "$execdir/logs/lonnet.log") {
141: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 142: close $fh;
143: }
144: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
145: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
146: }
147:
1.1 albertel 148: sub logthis {
149: my $message=shift;
150: my $execdir=$perlvar{'lonDaemons'};
151: my $now=time;
152: my $local=localtime($now);
1.448 albertel 153: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 154: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
155: print $fh $logstring;
1.448 albertel 156: close($fh);
157: }
1.1 albertel 158: return 1;
159: }
160:
161: sub logperm {
162: my $message=shift;
163: my $execdir=$perlvar{'lonDaemons'};
164: my $now=time;
165: my $local=localtime($now);
1.448 albertel 166: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
167: print $fh "$now:$message:$local\n";
168: close($fh);
169: }
1.1 albertel 170: return 1;
171: }
172:
1.850 albertel 173: sub create_connection {
1.853 albertel 174: my ($hostname,$lonid) = @_;
1.851 albertel 175: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 176: Type => SOCK_STREAM,
177: Timeout => 10);
178: return 0 if (!$client);
1.890 albertel 179: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 180: my $result = <$client>;
181: chomp($result);
182: return 1 if ($result eq 'done');
183: return 0;
184: }
185:
1.983 raeburn 186: sub get_server_timezone {
187: my ($cnum,$cdom) = @_;
188: my $home=&homeserver($cnum,$cdom);
189: if ($home ne 'no_host') {
190: my $cachetime = 24*3600;
191: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
192: if (defined($cached)) {
193: return $timezone;
194: } else {
195: my $timezone = &reply('servertimezone',$home);
196: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
197: }
198: }
199: }
1.850 albertel 200:
1.1106 raeburn 201: sub get_server_distarch {
202: my ($lonhost,$ignore_cache) = @_;
203: if (defined($lonhost)) {
204: if (!defined(&hostname($lonhost))) {
205: return;
206: }
207: my $cachetime = 12*3600;
208: if (!$ignore_cache) {
209: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
210: if (defined($cached)) {
211: return $distarch;
212: }
213: }
214: my $rep = &reply('serverdistarch',$lonhost);
215: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
216: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
217: $rep eq '') {
218: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
219: }
220: }
221: return;
222: }
223:
1.993 raeburn 224: sub get_server_loncaparev {
1.1073 raeburn 225: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 226: if (defined($lonhost)) {
227: if (!defined(&hostname($lonhost))) {
228: undef($lonhost);
229: }
230: }
231: if (!defined($lonhost)) {
232: if (defined(&domain($dom,'primary'))) {
233: $lonhost=&domain($dom,'primary');
234: if ($lonhost eq 'no_host') {
235: undef($lonhost);
236: }
237: }
238: }
239: if (defined($lonhost)) {
1.1073 raeburn 240: my $cachetime = 12*3600;
241: if (!$ignore_cache) {
242: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
243: if (defined($cached)) {
244: return $loncaparev;
245: }
246: }
247: my ($answer,$loncaparev);
248: my @ids=¤t_machine_ids();
249: if (grep(/^\Q$lonhost\E$/,@ids)) {
250: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 251: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 252: $loncaparev = $1;
253: }
254: } else {
255: $answer = &reply('serverloncaparev',$lonhost);
256: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
257: if ($caller eq 'loncron') {
258: my $ua=new LWP::UserAgent;
1.1082 raeburn 259: $ua->timeout(4);
1.1073 raeburn 260: my $protocol = $protocol{$lonhost};
261: $protocol = 'http' if ($protocol ne 'https');
262: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
263: my $request=new HTTP::Request('GET',$url);
264: my $response=$ua->request($request);
265: unless ($response->is_error()) {
266: my $content = $response->content;
1.1081 raeburn 267: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 268: $loncaparev = $1;
269: }
270: }
271: } else {
272: $loncaparev = $loncaparevs{$lonhost};
273: }
1.1081 raeburn 274: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 275: $loncaparev = $1;
276: }
1.993 raeburn 277: }
1.1073 raeburn 278: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 279: }
280: }
281:
1.1074 raeburn 282: sub get_server_homeID {
283: my ($hostname,$ignore_cache,$caller) = @_;
284: unless ($ignore_cache) {
285: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
286: if (defined($cached)) {
287: return $serverhomeID;
288: }
289: }
290: my $cachetime = 12*3600;
291: my $serverhomeID;
292: if ($caller eq 'loncron') {
293: my @machine_ids = &machine_ids($hostname);
294: foreach my $id (@machine_ids) {
295: my $response = &reply('serverhomeID',$id);
296: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
297: $serverhomeID = $response;
298: last;
299: }
300: }
301: if ($serverhomeID eq '') {
302: $serverhomeID = $machine_ids[-1];
303: }
304: } else {
305: $serverhomeID = $serverhomeIDs{$hostname};
306: }
307: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
308: }
309:
1.1121 raeburn 310: sub get_remote_globals {
311: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 312: my ($result,%returnhash,%whatneeded);
313: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 314: foreach my $what (sort(keys(%{$whathash}))) {
315: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 316: my ($response,$cached);
1.1121 raeburn 317: unless ($ignore_cache) {
1.1125 raeburn 318: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 319: }
320: if (defined($cached)) {
1.1125 raeburn 321: $returnhash{$what} = $response;
1.1121 raeburn 322: } else {
1.1125 raeburn 323: $whatneeded{$what} = 1;
1.1121 raeburn 324: }
325: }
1.1125 raeburn 326: if (keys(%whatneeded) == 0) {
327: $result = 'ok';
328: } else {
1.1121 raeburn 329: my $requested = &freeze_escape(\%whatneeded);
330: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 331: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
332: ($rep eq 'unknown_cmd')) {
333: $result = $rep;
334: } else {
335: $result = 'ok';
1.1121 raeburn 336: my @pairs=split(/\&/,$rep);
1.1125 raeburn 337: foreach my $item (@pairs) {
338: my ($key,$value)=split(/=/,$item,2);
339: my $what = &unescape($key);
340: my $hashid = $lonhost.'-'.$what;
341: $returnhash{$what}=&thaw_unescape($value);
342: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 343: }
344: }
345: }
346: }
1.1125 raeburn 347: return ($result,\%returnhash);
1.1121 raeburn 348: }
349:
1.1124 raeburn 350: sub remote_devalidate_cache {
351: my ($lonhost,$name,$id) = @_;
1.1130 raeburn 352: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124 raeburn 353: return $response;
354: }
355:
1.1 albertel 356: # -------------------------------------------------- Non-critical communication
357: sub subreply {
358: my ($cmd,$server)=@_;
1.838 albertel 359: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 360: #
361: # With loncnew process trimming, there's a timing hole between lonc server
362: # process exit and the master server picking up the listen on the AF_UNIX
363: # socket. In that time interval, a lock file will exist:
364:
365: my $lockfile=$peerfile.".lock";
366: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
367: sleep(1);
368: }
369: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 370: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 371: #
1.550 foxr 372: # We'll give the connection a few tries before abandoning it. If
373: # connection is not possible, we'll con_lost back to the client.
374: #
375: my $client;
376: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
377: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
378: Type => SOCK_STREAM,
379: Timeout => 10);
1.869 albertel 380: if ($client) {
1.550 foxr 381: last; # Connected!
1.850 albertel 382: } else {
1.853 albertel 383: &create_connection(&hostname($server),$server);
1.550 foxr 384: }
1.850 albertel 385: sleep(1); # Try again later if failed connection.
1.550 foxr 386: }
387: my $answer;
388: if ($client) {
1.704 albertel 389: print $client "sethost:$server:$cmd\n";
1.550 foxr 390: $answer=<$client>;
391: if (!$answer) { $answer="con_lost"; }
392: chomp($answer);
393: } else {
394: $answer = 'con_lost'; # Failed connection.
395: }
1.1 albertel 396: return $answer;
397: }
398:
399: sub reply {
400: my ($cmd,$server)=@_;
1.838 albertel 401: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 402: my $answer=subreply($cmd,$server);
1.65 www 403: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 404: &logthis("<font color=\"blue\">WARNING:".
1.12 www 405: " $cmd to $server returned $answer</font>");
406: }
1.1 albertel 407: return $answer;
408: }
409:
410: # ----------------------------------------------------------- Send USR1 to lonc
411:
412: sub reconlonc {
1.891 albertel 413: my ($lonid) = @_;
414: my $hostname = &hostname($lonid);
415: if ($lonid) {
416: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
417: if ($hostname && -e $peerfile) {
418: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
419: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
420: Type => SOCK_STREAM,
421: Timeout => 10);
422: if ($client) {
423: print $client ("reset_retries\n");
424: my $answer=<$client>;
425: #reset just this one.
426: }
427: }
428: return;
429: }
430:
1.836 www 431: &logthis("Trying to reconnect lonc");
1.1 albertel 432: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 433: if (open(my $fh,"<$loncfile")) {
1.1 albertel 434: my $loncpid=<$fh>;
435: chomp($loncpid);
436: if (kill 0 => $loncpid) {
437: &logthis("lonc at pid $loncpid responding, sending USR1");
438: kill USR1 => $loncpid;
439: sleep 1;
1.836 www 440: } else {
1.12 www 441: &logthis(
1.672 albertel 442: "<font color=\"blue\">WARNING:".
1.12 www 443: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 444: }
445: } else {
1.836 www 446: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 447: }
448: }
449:
450: # ------------------------------------------------------ Critical communication
1.12 www 451:
1.1 albertel 452: sub critical {
453: my ($cmd,$server)=@_;
1.838 albertel 454: unless (&hostname($server)) {
1.672 albertel 455: &logthis("<font color=\"blue\">WARNING:".
1.89 www 456: " Critical message to unknown server ($server)</font>");
457: return 'no_such_host';
458: }
1.1 albertel 459: my $answer=reply($cmd,$server);
460: if ($answer eq 'con_lost') {
461: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 462: my $answer=reply($cmd,$server);
1.1 albertel 463: if ($answer eq 'con_lost') {
464: my $now=time;
465: my $middlename=$cmd;
1.5 www 466: $middlename=substr($middlename,0,16);
1.1 albertel 467: $middlename=~s/\W//g;
468: my $dfilename=
1.305 www 469: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
470: $dumpcount++;
1.1 albertel 471: {
1.448 albertel 472: my $dfh;
473: if (open($dfh,">$dfilename")) {
474: print $dfh "$cmd\n";
475: close($dfh);
476: }
1.1 albertel 477: }
478: sleep 2;
479: my $wcmd='';
480: {
1.448 albertel 481: my $dfh;
482: if (open($dfh,"<$dfilename")) {
483: $wcmd=<$dfh>;
484: close($dfh);
485: }
1.1 albertel 486: }
487: chomp($wcmd);
1.7 www 488: if ($wcmd eq $cmd) {
1.672 albertel 489: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 490: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 491: &logperm("D:$server:$cmd");
492: return 'con_delayed';
493: } else {
1.672 albertel 494: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 495: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 496: &logperm("F:$server:$cmd");
497: return 'con_failed';
498: }
499: }
500: }
501: return $answer;
1.405 albertel 502: }
503:
1.755 albertel 504: # ------------------------------------------- check if return value is an error
505:
506: sub error {
507: my ($result) = @_;
1.756 albertel 508: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 509: if ($2 == 2) { return undef; }
510: return $1;
511: }
512: return undef;
513: }
514:
1.783 albertel 515: sub convert_and_load_session_env {
516: my ($lonidsdir,$handle)=@_;
517: my @profile;
518: {
1.917 albertel 519: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
520: if (!$opened) {
1.915 albertel 521: return 0;
522: }
1.783 albertel 523: flock($idf,LOCK_SH);
524: @profile=<$idf>;
525: close($idf);
526: }
527: my %temp_env;
528: foreach my $line (@profile) {
1.786 albertel 529: if ($line !~ m/=/) {
530: return 0;
531: }
1.783 albertel 532: chomp($line);
533: my ($envname,$envvalue)=split(/=/,$line,2);
534: $temp_env{&unescape($envname)} = &unescape($envvalue);
535: }
536: unlink("$lonidsdir/$handle.id");
537: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
538: 0640)) {
539: %disk_env = %temp_env;
540: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
541: untie(%disk_env);
542: }
1.786 albertel 543: return 1;
1.783 albertel 544: }
545:
1.374 www 546: # ------------------------------------------- Transfer profile into environment
1.780 albertel 547: my $env_loaded;
548: sub transfer_profile_to_env {
1.788 albertel 549: my ($lonidsdir,$handle,$force_transfer) = @_;
550: if (!$force_transfer && $env_loaded) { return; }
1.374 www 551:
1.720 albertel 552: if (!defined($lonidsdir)) {
553: $lonidsdir = $perlvar{'lonIDsDir'};
554: }
555: if (!defined($handle)) {
556: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
557: }
558:
1.786 albertel 559: my $convert;
560: {
1.917 albertel 561: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
562: if (!$opened) {
1.915 albertel 563: return;
564: }
1.786 albertel 565: flock($idf,LOCK_SH);
566: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
567: &GDBM_READER(),0640)) {
568: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
569: untie(%disk_env);
570: } else {
571: $convert = 1;
572: }
573: }
574: if ($convert) {
575: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
576: &logthis("Failed to load session, or convert session.");
577: }
1.374 www 578: }
1.783 albertel 579:
1.786 albertel 580: my %remove;
1.783 albertel 581: while ( my $envname = each(%env) ) {
1.433 matthew 582: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
583: if ($time < time-300) {
1.783 albertel 584: $remove{$key}++;
1.433 matthew 585: }
586: }
587: }
1.783 albertel 588:
1.619 albertel 589: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 590: $env_loaded=1;
1.783 albertel 591: foreach my $expired_key (keys(%remove)) {
1.433 matthew 592: &delenv($expired_key);
1.374 www 593: }
1.1 albertel 594: }
595:
1.916 albertel 596: # ---------------------------------------------------- Check for valid session
597: sub check_for_valid_session {
598: my ($r) = @_;
599: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
600: my $lonid=$cookies{'lonID'};
601: return undef if (!$lonid);
602:
603: my $handle=&LONCAPA::clean_handle($lonid->value);
604: my $lonidsdir=$r->dir_config('lonIDsDir');
605: return undef if (!-e "$lonidsdir/$handle.id");
606:
1.917 albertel 607: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
608: return undef if (!$opened);
1.916 albertel 609:
610: flock($idf,LOCK_SH);
611: my %disk_env;
612: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
613: &GDBM_READER(),0640)) {
614: return undef;
615: }
616:
617: if (!defined($disk_env{'user.name'})
618: || !defined($disk_env{'user.domain'})) {
619: return undef;
620: }
621: return $handle;
622: }
623:
1.830 albertel 624: sub timed_flock {
625: my ($file,$lock_type) = @_;
626: my $failed=0;
627: eval {
628: local $SIG{__DIE__}='DEFAULT';
629: local $SIG{ALRM}=sub {
630: $failed=1;
631: die("failed lock");
632: };
633: alarm(13);
634: flock($file,$lock_type);
635: alarm(0);
636: };
637: if ($failed) {
638: return undef;
639: } else {
640: return 1;
641: }
642: }
643:
1.5 www 644: # ---------------------------------------------------------- Append Environment
645:
646: sub appenv {
1.949 raeburn 647: my ($newenv,$roles) = @_;
648: if (ref($newenv) eq 'HASH') {
649: foreach my $key (keys(%{$newenv})) {
650: my $refused = 0;
651: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
652: $refused = 1;
653: if (ref($roles) eq 'ARRAY') {
654: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
655: if (grep(/^\Q$role\E$/,@{$roles})) {
656: $refused = 0;
657: }
658: }
659: }
660: if ($refused) {
661: &logthis("<font color=\"blue\">WARNING: ".
662: "Attempt to modify environment ".$key." to ".$newenv->{$key}
663: .'</font>');
664: delete($newenv->{$key});
665: } else {
666: $env{$key}=$newenv->{$key};
667: }
668: }
669: my $opened = open(my $env_file,'+<',$env{'user.environment'});
670: if ($opened
671: && &timed_flock($env_file,LOCK_EX)
672: &&
673: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
674: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
675: while (my ($key,$value) = each(%{$newenv})) {
676: $disk_env{$key} = $value;
677: }
678: untie(%disk_env);
1.35 www 679: }
1.191 harris41 680: }
1.56 www 681: return 'ok';
682: }
683: # ----------------------------------------------------- Delete from Environment
684:
685: sub delenv {
1.1104 raeburn 686: my ($delthis,$regexp,$roles) = @_;
687: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
688: my $refused = 1;
689: if (ref($roles) eq 'ARRAY') {
690: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
691: if (grep(/^\Q$role\E$/,@{$roles})) {
692: $refused = 0;
693: }
694: }
695: if ($refused) {
696: &logthis("<font color=\"blue\">WARNING: ".
697: "Attempt to delete from environment ".$delthis);
698: return 'error';
699: }
1.56 www 700: }
1.917 albertel 701: my $opened = open(my $env_file,'+<',$env{'user.environment'});
702: if ($opened
1.915 albertel 703: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 704: &&
705: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
706: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 707: foreach my $key (keys(%disk_env)) {
1.987 raeburn 708: if ($regexp) {
709: if ($key=~/^$delthis/) {
710: delete($env{$key});
711: delete($disk_env{$key});
712: }
713: } else {
714: if ($key=~/^\Q$delthis\E/) {
715: delete($env{$key});
716: delete($disk_env{$key});
717: }
718: }
1.448 albertel 719: }
1.783 albertel 720: untie(%disk_env);
1.5 www 721: }
722: return 'ok';
1.369 albertel 723: }
724:
1.790 albertel 725: sub get_env_multiple {
726: my ($name) = @_;
727: my @values;
728: if (defined($env{$name})) {
729: # exists is it an array
730: if (ref($env{$name})) {
731: @values=@{ $env{$name} };
732: } else {
733: $values[0]=$env{$name};
734: }
735: }
736: return(@values);
737: }
738:
1.958 www 739: # ------------------------------------------------------------------- Locking
740:
741: sub set_lock {
742: my ($text)=@_;
743: $locknum++;
744: my $id=$$.'-'.$locknum;
745: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
746: 'session.lock.'.$id => $text});
747: return $id;
748: }
749:
750: sub get_locks {
751: my $num=0;
752: my %texts=();
753: foreach my $lock (split(/\,/,$env{'session.locks'})) {
754: if ($lock=~/\w/) {
755: $num++;
756: $texts{$lock}=$env{'session.lock.'.$lock};
757: }
758: }
759: return ($num,%texts);
760: }
761:
762: sub remove_lock {
763: my ($id)=@_;
764: my $newlocks='';
765: foreach my $lock (split(/\,/,$env{'session.locks'})) {
766: if (($lock=~/\w/) && ($lock ne $id)) {
767: $newlocks.=','.$lock;
768: }
769: }
770: &appenv({'session.locks' => $newlocks});
771: &delenv('session.lock.'.$id);
772: }
773:
774: sub remove_all_locks {
775: my $activelocks=$env{'session.locks'};
776: foreach my $lock (split(/\,/,$env{'session.locks'})) {
777: if ($lock=~/\w/) {
778: &remove_lock($lock);
779: }
780: }
781: }
782:
783:
1.369 albertel 784: # ------------------------------------------ Find out current server userload
785: sub userload {
786: my $numusers=0;
787: {
788: opendir(LONIDS,$perlvar{'lonIDsDir'});
789: my $filename;
790: my $curtime=time;
791: while ($filename=readdir(LONIDS)) {
1.925 albertel 792: next if ($filename eq '.' || $filename eq '..');
793: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 794: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 795: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 796: }
797: closedir(LONIDS);
798: }
799: my $userloadpercent=0;
800: my $maxuserload=$perlvar{'lonUserLoadLim'};
801: if ($maxuserload) {
1.371 albertel 802: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 803: }
1.372 albertel 804: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 805: return $userloadpercent;
1.283 www 806: }
807:
1.1 albertel 808: # ------------------------------ Find server with least workload from spare.tab
1.11 www 809:
1.1 albertel 810: sub spareserver {
1.1083 raeburn 811: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 812: my $spare_server;
1.370 albertel 813: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 814: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
815: : $userloadpercent;
1.1083 raeburn 816: my ($uint_dom,$remotesessions);
817: if (($udom ne '') && (&domain($udom) ne '')) {
818: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
819: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
820: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
821: $remotesessions = $udomdefaults{'remotesessions'};
822: }
1.1123 raeburn 823: my $spareshash = &this_host_spares($udom);
824: if (ref($spareshash) eq 'HASH') {
825: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
826: foreach my $try_server (@{ $spareshash->{'primary'} }) {
827: if ($uint_dom) {
828: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
829: $try_server));
830: }
831: ($spare_server, $lowest_load) =
832: &compare_server_load($try_server, $spare_server, $lowest_load);
833: }
1.1083 raeburn 834: }
1.784 albertel 835:
1.1123 raeburn 836: my $found_server = ($spare_server ne '' && $lowest_load < 100);
837:
838: if (!$found_server) {
839: if (ref($spareshash->{'default'}) eq 'ARRAY') {
840: foreach my $try_server (@{ $spareshash->{'default'} }) {
841: if ($uint_dom) {
842: next unless (&spare_can_host($udom,$uint_dom,
843: $remotesessions,$try_server));
844: }
845: ($spare_server, $lowest_load) =
846: &compare_server_load($try_server, $spare_server, $lowest_load);
847: }
848: }
849: }
1.784 albertel 850: }
851:
852: if (!$want_server_name) {
1.968 raeburn 853: my $protocol = 'http';
854: if ($protocol{$spare_server} eq 'https') {
855: $protocol = $protocol{$spare_server};
856: }
1.1001 raeburn 857: if (defined($spare_server)) {
858: my $hostname = &hostname($spare_server);
1.1083 raeburn 859: if (defined($hostname)) {
1.1001 raeburn 860: $spare_server = $protocol.'://'.$hostname;
861: }
862: }
1.784 albertel 863: }
864: return $spare_server;
865: }
866:
867: sub compare_server_load {
868: my ($try_server, $spare_server, $lowest_load) = @_;
869:
870: my $loadans = &reply('load', $try_server);
871: my $userloadans = &reply('userload',$try_server);
872:
873: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 874: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 875: }
876:
877: my $load;
878: if ($loadans =~ /\d/) {
879: if ($userloadans =~ /\d/) {
880: #both are numbers, pick the bigger one
881: $load = ($loadans > $userloadans) ? $loadans
882: : $userloadans;
1.411 albertel 883: } else {
1.784 albertel 884: $load = $loadans;
1.411 albertel 885: }
1.784 albertel 886: } else {
887: $load = $userloadans;
888: }
889:
890: if (($load =~ /\d/) && ($load < $lowest_load)) {
891: $spare_server = $try_server;
892: $lowest_load = $load;
1.370 albertel 893: }
1.784 albertel 894: return ($spare_server,$lowest_load);
1.202 matthew 895: }
1.914 albertel 896:
897: # --------------------------- ask offload servers if user already has a session
898: sub find_existing_session {
899: my ($udom,$uname) = @_;
1.1123 raeburn 900: my $spareshash = &this_host_spares($udom);
901: if (ref($spareshash) eq 'HASH') {
902: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
903: foreach my $try_server (@{ $spareshash->{'primary'} }) {
904: return $try_server if (&has_user_session($try_server, $udom, $uname));
905: }
906: }
907: if (ref($spareshash->{'default'}) eq 'ARRAY') {
908: foreach my $try_server (@{ $spareshash->{'default'} }) {
909: return $try_server if (&has_user_session($try_server, $udom, $uname));
910: }
911: }
1.914 albertel 912: }
913: return;
914: }
915:
916: # -------------------------------- ask if server already has a session for user
917: sub has_user_session {
918: my ($lonid,$udom,$uname) = @_;
919: my $result = &reply(join(':','userhassession',
920: map {&escape($_)} ($udom,$uname)),$lonid);
921: return 1 if ($result eq 'ok');
922:
923: return 0;
924: }
925:
1.1076 raeburn 926: # --------- determine least loaded server in a user's domain which allows login
927:
928: sub choose_server {
1.1115 raeburn 929: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 930: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 931: my %servers = &get_servers($udom);
1.1076 raeburn 932: my $lowest_load = 30000;
1.1151 ! raeburn 933: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 934: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 935: my $loginvia;
936: if ($checkloginvia) {
937: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 938: if ($loginvia) {
939: my ($server,$path) = split(/:/,$loginvia);
940: ($login_host, $lowest_load) =
941: &compare_server_load($server, $login_host, $lowest_load);
942: if ($login_host eq $server) {
943: $portal_path = $path;
1.1151 ! raeburn 944: $isredirect = 1;
1.1116 raeburn 945: }
946: } else {
947: ($login_host, $lowest_load) =
948: &compare_server_load($lonhost, $login_host, $lowest_load);
949: if ($login_host eq $lonhost) {
950: $portal_path = '';
1.1151 ! raeburn 951: $isredirect = '';
1.1116 raeburn 952: }
953: }
954: } else {
1.1076 raeburn 955: ($login_host, $lowest_load) =
1.1116 raeburn 956: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 957: }
958: }
959: if ($login_host ne '') {
1.1116 raeburn 960: $hostname = &hostname($login_host);
1.1076 raeburn 961: }
1.1151 ! raeburn 962: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 963: }
964:
1.202 matthew 965: # --------------------------------------------- Try to change a user's password
966:
967: sub changepass {
1.799 raeburn 968: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 969: $currentpass = &escape($currentpass);
970: $newpass = &escape($newpass);
1.1030 raeburn 971: my $lonhost = $perlvar{'lonHostID'};
972: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 973: $server);
974: if (! $answer) {
975: &logthis("No reply on password change request to $server ".
976: "by $uname in domain $udom.");
977: } elsif ($answer =~ "^ok") {
978: &logthis("$uname in $udom successfully changed their password ".
979: "on $server.");
980: } elsif ($answer =~ "^pwchange_failure") {
981: &logthis("$uname in $udom was unable to change their password ".
982: "on $server. The action was blocked by either lcpasswd ".
983: "or pwchange");
984: } elsif ($answer =~ "^non_authorized") {
985: &logthis("$uname in $udom did not get their password correct when ".
986: "attempting to change it on $server.");
987: } elsif ($answer =~ "^auth_mode_error") {
988: &logthis("$uname in $udom attempted to change their password despite ".
989: "not being locally or internally authenticated on $server.");
990: } elsif ($answer =~ "^unknown_user") {
991: &logthis("$uname in $udom attempted to change their password ".
992: "on $server but were unable to because $server is not ".
993: "their home server.");
994: } elsif ($answer =~ "^refused") {
995: &logthis("$server refused to change $uname in $udom password because ".
996: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 997: } elsif ($answer =~ "invalid_client") {
998: &logthis("$server refused to change $uname in $udom password because ".
999: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1000: }
1001: return $answer;
1.1 albertel 1002: }
1003:
1.169 harris41 1004: # ----------------------- Try to determine user's current authentication scheme
1005:
1006: sub queryauthenticate {
1007: my ($uname,$udom)=@_;
1.456 albertel 1008: my $uhome=&homeserver($uname,$udom);
1009: if (!$uhome) {
1010: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1011: return 'no_host';
1012: }
1013: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1014: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1015: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1016: }
1.456 albertel 1017: return $answer;
1.169 harris41 1018: }
1019:
1.1 albertel 1020: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1021:
1.1 albertel 1022: sub authenticate {
1.1073 raeburn 1023: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1024: $upass=&escape($upass);
1025: $uname= &LONCAPA::clean_username($uname);
1.836 www 1026: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1027: my $newhome;
1.836 www 1028: if ((!$uhome) || ($uhome eq 'no_host')) {
1029: # Maybe the machine was offline and only re-appeared again recently?
1030: &reconlonc();
1031: # One more
1.952 raeburn 1032: $uhome=&homeserver($uname,$udom,1);
1033: if (($uhome eq 'no_host') && $checkdefauth) {
1034: if (defined(&domain($udom,'primary'))) {
1035: $newhome=&domain($udom,'primary');
1036: }
1037: if ($newhome ne '') {
1038: $uhome = $newhome;
1039: }
1040: }
1.836 www 1041: if ((!$uhome) || ($uhome eq 'no_host')) {
1042: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1043: return 'no_host';
1044: }
1.1 albertel 1045: }
1.1073 raeburn 1046: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1047: if ($answer eq 'authorized') {
1.952 raeburn 1048: if ($newhome) {
1049: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1050: return 'no_account_on_host';
1051: } else {
1052: &logthis("User $uname at $udom authorized by $uhome");
1053: return $uhome;
1054: }
1.471 albertel 1055: }
1056: if ($answer eq 'non_authorized') {
1057: &logthis("User $uname at $udom rejected by $uhome");
1058: return 'no_host';
1.9 www 1059: }
1.471 albertel 1060: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1061: return 'no_host';
1062: }
1063:
1.1073 raeburn 1064: sub can_host_session {
1.1074 raeburn 1065: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1066: my $canhost = 1;
1.1074 raeburn 1067: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1068: if (ref($remotesessions) eq 'HASH') {
1069: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1070: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1071: $canhost = 0;
1072: } else {
1073: $canhost = 1;
1074: }
1075: }
1076: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1077: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1078: $canhost = 1;
1079: } else {
1080: $canhost = 0;
1081: }
1082: }
1083: if ($canhost) {
1084: if ($remotesessions->{'version'} ne '') {
1085: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1086: if ($reqmajor ne '' && $reqminor ne '') {
1087: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1088: my $major = $1;
1089: my $minor = $2;
1090: if (($major < $reqmajor ) ||
1091: (($major == $reqmajor) && ($minor < $reqminor))) {
1092: $canhost = 0;
1093: }
1094: } else {
1095: $canhost = 0;
1096: }
1097: }
1098: }
1099: }
1100: }
1101: if ($canhost) {
1102: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1103: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1104: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1105: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1106: if (($uint_dom ne '') &&
1107: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1108: $canhost = 0;
1109: } else {
1110: $canhost = 1;
1111: }
1112: }
1113: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1114: if (($uint_dom ne '') &&
1115: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1116: $canhost = 1;
1117: } else {
1118: $canhost = 0;
1119: }
1120: }
1121: }
1122: }
1123: return $canhost;
1124: }
1125:
1.1083 raeburn 1126: sub spare_can_host {
1127: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1128: my $canhost=1;
1129: my @intdoms;
1130: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1131: if (ref($internet_names) eq 'ARRAY') {
1132: @intdoms = @{$internet_names};
1133: }
1134: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1135: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1136: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1137: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1138: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1139: $canhost = &can_host_session($udom,$try_server,$remoterev,
1140: $remotesessions,
1141: $defdomdefaults{'hostedsessions'});
1142: }
1143: return $canhost;
1144: }
1145:
1.1123 raeburn 1146: sub this_host_spares {
1147: my ($dom) = @_;
1.1126 raeburn 1148: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1149: my @hosts = ¤t_machine_ids();
1150: foreach my $lonhost (@hosts) {
1151: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1152: $dom_in_use = $dom;
1153: $lonhost_in_use = $lonhost;
1.1123 raeburn 1154: last;
1155: }
1156: }
1.1126 raeburn 1157: if ($dom_in_use ne '') {
1158: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1159: }
1160: if (ref($result) ne 'HASH') {
1161: $lonhost_in_use = $perlvar{'lonHostID'};
1162: $dom_in_use = &host_domain($lonhost_in_use);
1163: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1164: if (ref($result) ne 'HASH') {
1165: $result = \%spareid;
1166: }
1167: }
1168: return $result;
1169: }
1170:
1171: sub spares_for_offload {
1172: my ($dom_in_use,$lonhost_in_use) = @_;
1173: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1174: if (defined($cached)) {
1175: return $result;
1176: } else {
1.1126 raeburn 1177: my $cachetime = 60*60*24;
1178: my %domconfig =
1179: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1180: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1181: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1182: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1183: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1184: }
1185: }
1186: }
1187: }
1.1126 raeburn 1188: return;
1.1123 raeburn 1189: }
1190:
1.1129 raeburn 1191: sub get_lonbalancer_config {
1192: my ($servers) = @_;
1193: my ($currbalancer,$currtargets);
1194: if (ref($servers) eq 'HASH') {
1195: foreach my $server (keys(%{$servers})) {
1196: my %what = (
1197: spareid => 1,
1198: perlvar => 1,
1199: );
1200: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1201: if ($result eq 'ok') {
1202: if (ref($returnhash) eq 'HASH') {
1203: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1204: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1205: $currbalancer = $server;
1206: $currtargets = {};
1207: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1208: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1209: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1210: }
1211: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1212: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1213: }
1214: }
1215: last;
1216: }
1217: }
1218: }
1219: }
1220: }
1221: }
1222: return ($currbalancer,$currtargets);
1223: }
1224:
1225: sub check_loadbalancing {
1226: my ($uname,$udom) = @_;
1227: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
1228: $offloadto,$otherserver);
1229: my $lonhost = $perlvar{'lonHostID'};
1230: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1231: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1232: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1233: my $serverhomedom = &host_domain($lonhost);
1234:
1235: my $cachetime = 60*60*24;
1236:
1237: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1238: $dom_in_use = $udom;
1239: $homeintdom = 1;
1240: } else {
1241: $dom_in_use = $serverhomedom;
1242: }
1243: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1244: unless (defined($cached)) {
1245: my %domconfig =
1246: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1247: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1248: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1249: }
1250: }
1251: if (ref($result) eq 'HASH') {
1252: my $currbalancer = $result->{'lonhost'};
1253: my $currtargets = $result->{'targets'};
1254: my $currrules = $result->{'rules'};
1255: if ($currbalancer ne '') {
1256: my @hosts = ¤t_machine_ids();
1257: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1258: $is_balancer = 1;
1259: }
1260: }
1261: if ($is_balancer) {
1262: if (ref($currrules) eq 'HASH') {
1263: if ($homeintdom) {
1264: if ($uname ne '') {
1265: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1266: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1267: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1268: $rule_in_effect = $currrules->{'_LC_author'};
1269: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1270: $rule_in_effect = $currrules->{'_LC_adv'}
1271: }
1272: }
1273: if ($rule_in_effect eq '') {
1274: my %userenv = &userenvironment($udom,$uname,'inststatus');
1275: if ($userenv{'inststatus'} ne '') {
1276: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1277: my ($othertitle,$usertypes,$types) =
1278: &Apache::loncommon::sorted_inst_types($udom);
1279: if (ref($types) eq 'ARRAY') {
1280: foreach my $type (@{$types}) {
1281: if (grep(/^\Q$type\E$/,@statuses)) {
1282: if (exists($currrules->{$type})) {
1283: $rule_in_effect = $currrules->{$type};
1284: }
1285: }
1286: }
1287: }
1288: } else {
1289: if (exists($currrules->{'default'})) {
1290: $rule_in_effect = $currrules->{'default'};
1291: }
1292: }
1293: }
1294: } else {
1295: if (exists($currrules->{'default'})) {
1296: $rule_in_effect = $currrules->{'default'};
1297: }
1298: }
1299: } else {
1300: if ($currrules->{'_LC_external'} ne '') {
1301: $rule_in_effect = $currrules->{'_LC_external'};
1302: }
1303: }
1304: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1305: $uname,$udom);
1306: }
1307: }
1308: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1309: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1310: unless (defined($cached)) {
1311: my %domconfig =
1312: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1313: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1314: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1315: }
1316: }
1317: if (ref($result) eq 'HASH') {
1318: my $currbalancer = $result->{'lonhost'};
1319: my $currtargets = $result->{'targets'};
1320: my $currrules = $result->{'rules'};
1321:
1322: if ($currbalancer eq $lonhost) {
1323: $is_balancer = 1;
1324: if (ref($currrules) eq 'HASH') {
1325: if ($currrules->{'_LC_internetdom'} ne '') {
1326: $rule_in_effect = $currrules->{'_LC_internetdom'};
1327: }
1328: }
1329: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1330: $uname,$udom);
1331: }
1332: } else {
1333: if ($perlvar{'lonBalancer'} eq 'yes') {
1334: $is_balancer = 1;
1335: $offloadto = &this_host_spares($dom_in_use);
1336: }
1337: }
1338: } else {
1339: if ($perlvar{'lonBalancer'} eq 'yes') {
1340: $is_balancer = 1;
1341: $offloadto = &this_host_spares($dom_in_use);
1342: }
1343: }
1344: my $lowest_load = 30000;
1345: if (ref($offloadto) eq 'HASH') {
1346: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1347: foreach my $try_server (@{$offloadto->{'primary'}}) {
1348: ($otherserver,$lowest_load) =
1349: &compare_server_load($try_server,$otherserver,$lowest_load);
1350: }
1351: }
1352: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1353:
1354: if (!$found_server) {
1355: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1356: foreach my $try_server (@{$offloadto->{'default'}}) {
1357: ($otherserver,$lowest_load) =
1358: &compare_server_load($try_server,$otherserver,$lowest_load);
1359: }
1360: }
1361: }
1362: } elsif (ref($offloadto) eq 'ARRAY') {
1363: if (@{$offloadto} == 1) {
1364: $otherserver = $offloadto->[0];
1365: } elsif (@{$offloadto} > 1) {
1366: foreach my $try_server (@{$offloadto}) {
1367: ($otherserver,$lowest_load) =
1368: &compare_server_load($try_server,$otherserver,$lowest_load);
1369: }
1370: }
1371: }
1372: return ($is_balancer,$otherserver);
1373: }
1374:
1375: sub get_loadbalancer_targets {
1376: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1377: my $offloadto;
1378: if ($rule_in_effect eq '') {
1379: $offloadto = $currtargets;
1380: } else {
1381: if ($rule_in_effect eq 'homeserver') {
1382: my $homeserver = &homeserver($uname,$udom);
1383: if ($homeserver ne 'no_host') {
1384: $offloadto = [$homeserver];
1385: }
1386: } elsif ($rule_in_effect eq 'externalbalancer') {
1387: my %domconfig =
1388: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1389: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1390: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1391: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1392: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1393: }
1394: }
1395: } else {
1396: my %servers = &dom_servers($udom);
1397: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1398: if (&hostname($remotebalancer) ne '') {
1399: $offloadto = [$remotebalancer];
1400: }
1401: }
1402: } elsif (&hostname($rule_in_effect) ne '') {
1403: $offloadto = [$rule_in_effect];
1404: }
1405: }
1406: return $offloadto;
1407: }
1408:
1.1127 raeburn 1409: sub internet_dom_servers {
1410: my ($dom) = @_;
1411: my (%uniqservers,%servers);
1412: my $primaryserver = &hostname(&domain($dom,'primary'));
1413: my @machinedoms = &machine_domains($primaryserver);
1414: foreach my $mdom (@machinedoms) {
1415: my %currservers = %servers;
1416: my %server = &get_servers($mdom);
1417: %servers = (%currservers,%server);
1418: }
1419: my %by_hostname;
1420: foreach my $id (keys(%servers)) {
1421: push(@{$by_hostname{$servers{$id}}},$id);
1422: }
1423: foreach my $hostname (sort(keys(%by_hostname))) {
1424: if (@{$by_hostname{$hostname}} > 1) {
1425: my $match = 0;
1426: foreach my $id (@{$by_hostname{$hostname}}) {
1427: if (&host_domain($id) eq $dom) {
1428: $uniqservers{$id} = $hostname;
1429: $match = 1;
1430: }
1431: }
1432: unless ($match) {
1433: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1434: }
1435: } else {
1436: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1437: }
1438: }
1439: return %uniqservers;
1440: }
1441:
1.1 albertel 1442: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1443:
1.599 albertel 1444: my %homecache;
1.1 albertel 1445: sub homeserver {
1.230 stredwic 1446: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1447: my $index="$uname:$udom";
1.426 albertel 1448:
1.599 albertel 1449: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1450:
1451: my %servers = &get_servers($udom,'library');
1452: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1453: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1454: exists($badServerCache{$tryserver}));
1.841 albertel 1455:
1456: my $answer=reply("home:$udom:$uname",$tryserver);
1457: if ($answer eq 'found') {
1458: delete($badServerCache{$tryserver});
1459: return $homecache{$index}=$tryserver;
1460: } elsif ($answer eq 'no_host') {
1461: $badServerCache{$tryserver}=1;
1462: }
1.1 albertel 1463: }
1464: return 'no_host';
1.70 www 1465: }
1466:
1467: # ------------------------------------- Find the usernames behind a list of IDs
1468:
1469: sub idget {
1470: my ($udom,@ids)=@_;
1471: my %returnhash=();
1472:
1.841 albertel 1473: my %servers = &get_servers($udom,'library');
1474: foreach my $tryserver (keys(%servers)) {
1475: my $idlist=join('&',@ids);
1476: $idlist=~tr/A-Z/a-z/;
1477: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1478: my @answer=();
1479: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1480: @answer=split(/\&/,$reply);
1481: } ;
1482: my $i;
1483: for ($i=0;$i<=$#ids;$i++) {
1484: if ($answer[$i]) {
1485: $returnhash{$ids[$i]}=$answer[$i];
1486: }
1487: }
1488: }
1.70 www 1489: return %returnhash;
1490: }
1491:
1492: # ------------------------------------- Find the IDs behind a list of usernames
1493:
1494: sub idrget {
1495: my ($udom,@unames)=@_;
1496: my %returnhash=();
1.800 albertel 1497: foreach my $uname (@unames) {
1498: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1499: }
1.70 www 1500: return %returnhash;
1501: }
1502:
1503: # ------------------------------- Store away a list of names and associated IDs
1504:
1505: sub idput {
1506: my ($udom,%ids)=@_;
1507: my %servers=();
1.800 albertel 1508: foreach my $uname (keys(%ids)) {
1509: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1510: my $uhom=&homeserver($uname,$udom);
1.70 www 1511: if ($uhom ne 'no_host') {
1.800 albertel 1512: my $id=&escape($ids{$uname});
1.70 www 1513: $id=~tr/A-Z/a-z/;
1.800 albertel 1514: my $esc_unam=&escape($uname);
1.70 www 1515: if ($servers{$uhom}) {
1.800 albertel 1516: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1517: } else {
1.800 albertel 1518: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1519: }
1520: }
1.191 harris41 1521: }
1.800 albertel 1522: foreach my $server (keys(%servers)) {
1523: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1524: }
1.344 www 1525: }
1526:
1.1023 raeburn 1527: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1528: sub dump_dom {
1.1023 raeburn 1529: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1530: if (!$udom) {
1531: $udom=$env{'user.domain'};
1532: }
1533: my %returnhash;
1.1023 raeburn 1534: if ($udom) {
1535: my $uname = &get_domainconfiguser($udom);
1536: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1537: }
1538: return %returnhash;
1539: }
1540:
1.1023 raeburn 1541: # ------------------------------------------ get items from domain db files
1.806 raeburn 1542:
1543: sub get_dom {
1.860 raeburn 1544: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1545: my $items='';
1546: foreach my $item (@$storearr) {
1547: $items.=&escape($item).'&';
1548: }
1549: $items=~s/\&$//;
1.860 raeburn 1550: if (!$udom) {
1551: $udom=$env{'user.domain'};
1552: if (defined(&domain($udom,'primary'))) {
1553: $uhome=&domain($udom,'primary');
1554: } else {
1.874 albertel 1555: undef($uhome);
1.860 raeburn 1556: }
1557: } else {
1558: if (!$uhome) {
1559: if (defined(&domain($udom,'primary'))) {
1560: $uhome=&domain($udom,'primary');
1561: }
1562: }
1563: }
1564: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1565: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1566: my %returnhash;
1.875 albertel 1567: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1568: return %returnhash;
1569: }
1.806 raeburn 1570: my @pairs=split(/\&/,$rep);
1571: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1572: return @pairs;
1573: }
1574: my $i=0;
1575: foreach my $item (@$storearr) {
1576: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1577: $i++;
1578: }
1579: return %returnhash;
1580: } else {
1.880 banghart 1581: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1582: }
1583: }
1584:
1585: # -------------------------------------------- put items in domain db files
1586:
1587: sub put_dom {
1.860 raeburn 1588: my ($namespace,$storehash,$udom,$uhome)=@_;
1589: if (!$udom) {
1590: $udom=$env{'user.domain'};
1591: if (defined(&domain($udom,'primary'))) {
1592: $uhome=&domain($udom,'primary');
1593: } else {
1.874 albertel 1594: undef($uhome);
1.860 raeburn 1595: }
1596: } else {
1597: if (!$uhome) {
1598: if (defined(&domain($udom,'primary'))) {
1599: $uhome=&domain($udom,'primary');
1600: }
1601: }
1602: }
1603: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1604: my $items='';
1605: foreach my $item (keys(%$storehash)) {
1606: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1607: }
1608: $items=~s/\&$//;
1609: return &reply("putdom:$udom:$namespace:$items",$uhome);
1610: } else {
1.860 raeburn 1611: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1612: }
1613: }
1614:
1.1023 raeburn 1615: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1616: sub newput_dom {
1.1023 raeburn 1617: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1618: my $result;
1619: if (!$udom) {
1620: $udom=$env{'user.domain'};
1621: }
1.1023 raeburn 1622: if ($udom) {
1623: my $uname = &get_domainconfiguser($udom);
1624: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1625: }
1626: return $result;
1627: }
1628:
1.1023 raeburn 1629: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1630: sub del_dom {
1.1023 raeburn 1631: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1632: if (ref($storearr) eq 'ARRAY') {
1633: if (!$udom) {
1634: $udom=$env{'user.domain'};
1635: }
1.1023 raeburn 1636: if ($udom) {
1637: my $uname = &get_domainconfiguser($udom);
1638: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1639: }
1640: }
1641: }
1642:
1.1023 raeburn 1643: # ----------------------------------construct domainconfig user for a domain
1644: sub get_domainconfiguser {
1645: my ($udom) = @_;
1646: return $udom.'-domainconfig';
1647: }
1648:
1.837 raeburn 1649: sub retrieve_inst_usertypes {
1650: my ($udom) = @_;
1651: my (%returnhash,@order);
1.989 raeburn 1652: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1653: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1654: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1655: %returnhash = %{$domdefs{'inststatustypes'}};
1656: @order = @{$domdefs{'inststatusorder'}};
1657: } else {
1658: if (defined(&domain($udom,'primary'))) {
1659: my $uhome=&domain($udom,'primary');
1660: my $rep=&reply("inst_usertypes:$udom",$uhome);
1661: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1662: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1663: return (\%returnhash,\@order);
1664: }
1665: my ($hashitems,$orderitems) = split(/:/,$rep);
1666: my @pairs=split(/\&/,$hashitems);
1667: foreach my $item (@pairs) {
1668: my ($key,$value)=split(/=/,$item,2);
1669: $key = &unescape($key);
1670: next if ($key =~ /^error: 2 /);
1671: $returnhash{$key}=&thaw_unescape($value);
1672: }
1673: my @esc_order = split(/\&/,$orderitems);
1674: foreach my $item (@esc_order) {
1675: push(@order,&unescape($item));
1676: }
1677: } else {
1678: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1679: }
1680: }
1681: return (\%returnhash,\@order);
1682: }
1683:
1.868 raeburn 1684: sub is_domainimage {
1685: my ($url) = @_;
1686: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1687: if (&domain($1) ne '') {
1688: return '1';
1689: }
1690: }
1691: return;
1692: }
1693:
1.899 raeburn 1694: sub inst_directory_query {
1695: my ($srch) = @_;
1696: my $udom = $srch->{'srchdomain'};
1697: my %results;
1698: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1699: my $outcome;
1.899 raeburn 1700: if ($homeserver ne '') {
1.904 albertel 1701: my $queryid=&reply("querysend:instdirsearch:".
1702: &escape($srch->{'srchby'}).':'.
1703: &escape($srch->{'srchterm'}).':'.
1704: &escape($srch->{'srchtype'}),$homeserver);
1705: my $host=&hostname($homeserver);
1706: if ($queryid !~/^\Q$host\E\_/) {
1707: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1708: return;
1709: }
1710: my $response = &get_query_reply($queryid);
1711: my $maxtries = 5;
1712: my $tries = 1;
1713: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1714: $response = &get_query_reply($queryid);
1715: $tries ++;
1716: }
1717:
1718: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1719: if ($response eq 'unavailable') {
1720: $outcome = $response;
1721: } else {
1722: $outcome = 'ok';
1723: my @matches = split(/\n/,$response);
1724: foreach my $match (@matches) {
1725: my ($key,$value) = split(/=/,$match);
1726: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1727: }
1.899 raeburn 1728: }
1729: }
1730: }
1.909 raeburn 1731: return ($outcome,%results);
1.899 raeburn 1732: }
1733:
1734: sub usersearch {
1735: my ($srch) = @_;
1736: my $dom = $srch->{'srchdomain'};
1737: my %results;
1738: my %libserv = &all_library();
1739: my $query = 'usersearch';
1740: foreach my $tryserver (keys(%libserv)) {
1741: if (&host_domain($tryserver) eq $dom) {
1742: my $host=&hostname($tryserver);
1743: my $queryid=
1.911 raeburn 1744: &reply("querysend:".&escape($query).':'.
1745: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1746: &escape($srch->{'srchtype'}).':'.
1747: &escape($srch->{'srchterm'}),$tryserver);
1748: if ($queryid !~/^\Q$host\E\_/) {
1749: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1750: next;
1.899 raeburn 1751: }
1752: my $reply = &get_query_reply($queryid);
1753: my $maxtries = 1;
1754: my $tries = 1;
1755: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1756: $reply = &get_query_reply($queryid);
1757: $tries ++;
1758: }
1759: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1760: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1761: } else {
1.911 raeburn 1762: my @matches;
1763: if ($reply =~ /\n/) {
1764: @matches = split(/\n/,$reply);
1765: } else {
1766: @matches = split(/\&/,$reply);
1767: }
1.899 raeburn 1768: foreach my $match (@matches) {
1769: my ($uname,$udom,%userhash);
1.911 raeburn 1770: foreach my $entry (split(/:/,$match)) {
1771: my ($key,$value) =
1772: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1773: $userhash{$key} = $value;
1774: if ($key eq 'username') {
1775: $uname = $value;
1776: } elsif ($key eq 'domain') {
1777: $udom = $value;
1.911 raeburn 1778: }
1.899 raeburn 1779: }
1780: $results{$uname.':'.$udom} = \%userhash;
1781: }
1782: }
1783: }
1784: }
1785: return %results;
1786: }
1787:
1.912 raeburn 1788: sub get_instuser {
1789: my ($udom,$uname,$id) = @_;
1790: my $homeserver = &domain($udom,'primary');
1791: my ($outcome,%results);
1792: if ($homeserver ne '') {
1793: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1794: &escape($id).':'.&escape($udom),$homeserver);
1795: my $host=&hostname($homeserver);
1796: if ($queryid !~/^\Q$host\E\_/) {
1797: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1798: return;
1799: }
1800: my $response = &get_query_reply($queryid);
1801: my $maxtries = 5;
1802: my $tries = 1;
1803: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1804: $response = &get_query_reply($queryid);
1805: $tries ++;
1806: }
1807: if (!&error($response) && $response ne 'refused') {
1808: if ($response eq 'unavailable') {
1809: $outcome = $response;
1810: } else {
1811: $outcome = 'ok';
1812: my @matches = split(/\n/,$response);
1813: foreach my $match (@matches) {
1814: my ($key,$value) = split(/=/,$match);
1815: $results{&unescape($key)} = &thaw_unescape($value);
1816: }
1817: }
1818: }
1819: }
1820: my %userinfo;
1821: if (ref($results{$uname}) eq 'HASH') {
1822: %userinfo = %{$results{$uname}};
1823: }
1824: return ($outcome,%userinfo);
1825: }
1826:
1827: sub inst_rulecheck {
1.923 raeburn 1828: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1829: my %returnhash;
1830: if ($udom ne '') {
1831: if (ref($rules) eq 'ARRAY') {
1832: @{$rules} = map {&escape($_);} (@{$rules});
1833: my $rulestr = join(':',@{$rules});
1834: my $homeserver=&domain($udom,'primary');
1835: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1836: my $response;
1837: if ($item eq 'username') {
1838: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1839: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1840: $homeserver));
1.923 raeburn 1841: } elsif ($item eq 'id') {
1842: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1843: ':'.&escape($id).':'.$rulestr,
1844: $homeserver));
1.945 raeburn 1845: } elsif ($item eq 'selfcreate') {
1846: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1847: &escape($udom).':'.&escape($uname).
1848: ':'.$rulestr,$homeserver));
1.923 raeburn 1849: }
1.912 raeburn 1850: if ($response ne 'refused') {
1851: my @pairs=split(/\&/,$response);
1852: foreach my $item (@pairs) {
1853: my ($key,$value)=split(/=/,$item,2);
1854: $key = &unescape($key);
1855: next if ($key =~ /^error: 2 /);
1856: $returnhash{$key}=&thaw_unescape($value);
1857: }
1858: }
1859: }
1860: }
1861: }
1862: return %returnhash;
1863: }
1864:
1865: sub inst_userrules {
1.923 raeburn 1866: my ($udom,$check) = @_;
1.912 raeburn 1867: my (%ruleshash,@ruleorder);
1868: if ($udom ne '') {
1869: my $homeserver=&domain($udom,'primary');
1870: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1871: my $response;
1872: if ($check eq 'id') {
1873: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1874: $homeserver);
1.943 raeburn 1875: } elsif ($check eq 'email') {
1876: $response=&reply('instemailrules:'.&escape($udom),
1877: $homeserver);
1.923 raeburn 1878: } else {
1879: $response=&reply('instuserrules:'.&escape($udom),
1880: $homeserver);
1881: }
1.912 raeburn 1882: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1883: ($response ne 'unknown_cmd') &&
1.912 raeburn 1884: ($response ne 'no_such_host')) {
1885: my ($hashitems,$orderitems) = split(/:/,$response);
1886: my @pairs=split(/\&/,$hashitems);
1887: foreach my $item (@pairs) {
1888: my ($key,$value)=split(/=/,$item,2);
1889: $key = &unescape($key);
1890: next if ($key =~ /^error: 2 /);
1891: $ruleshash{$key}=&thaw_unescape($value);
1892: }
1893: my @esc_order = split(/\&/,$orderitems);
1894: foreach my $item (@esc_order) {
1895: push(@ruleorder,&unescape($item));
1896: }
1897: }
1898: }
1899: }
1900: return (\%ruleshash,\@ruleorder);
1901: }
1902:
1.976 raeburn 1903: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1904:
1905: sub get_domain_defaults {
1906: my ($domain) = @_;
1907: my $cachetime = 60*60*24;
1908: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1909: if (defined($cached)) {
1910: if (ref($result) eq 'HASH') {
1911: return %{$result};
1912: }
1913: }
1914: my %domdefaults;
1915: my %domconfig =
1.989 raeburn 1916: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1917: 'requestcourses','inststatus',
1.1073 raeburn 1918: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1919: if (ref($domconfig{'defaults'}) eq 'HASH') {
1920: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1921: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1922: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1923: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1924: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 1925: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 1926: } else {
1927: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1928: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1929: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1930: }
1.976 raeburn 1931: if (ref($domconfig{'quotas'}) eq 'HASH') {
1932: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1933: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1934: } else {
1935: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1936: }
1937: my @usertools = ('aboutme','blog','portfolio');
1938: foreach my $item (@usertools) {
1939: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1940: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1941: }
1942: }
1943: }
1.985 raeburn 1944: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1945: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1946: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1947: }
1948: }
1.989 raeburn 1949: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1950: foreach my $item ('inststatustypes','inststatusorder') {
1951: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1952: }
1953: }
1.1047 raeburn 1954: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1955: foreach my $item ('canuse_pdfforms') {
1956: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1957: }
1958: }
1.1073 raeburn 1959: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1960: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1961: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1962: }
1963: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1964: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1965: }
1966: }
1.943 raeburn 1967: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1968: $cachetime);
1969: return %domdefaults;
1970: }
1971:
1.344 www 1972: # --------------------------------------------------- Assign a key to a student
1973:
1974: sub assign_access_key {
1.364 www 1975: #
1976: # a valid key looks like uname:udom#comments
1977: # comments are being appended
1978: #
1.498 www 1979: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1980: $kdom=
1.620 albertel 1981: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1982: $knum=
1.620 albertel 1983: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1984: $cdom=
1.620 albertel 1985: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1986: $cnum=
1.620 albertel 1987: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1988: $udom=$env{'user.name'} unless (defined($udom));
1989: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1990: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1991: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1992: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1993: # assigned to this person
1994: # - this should not happen,
1.345 www 1995: # unless something went wrong
1996: # the first time around
1997: # ready to assign
1.364 www 1998: $logentry=$1.'; '.$logentry;
1.496 www 1999: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2000: $kdom,$knum) eq 'ok') {
1.345 www 2001: # key now belongs to user
1.346 www 2002: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2003: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2004: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2005: return 'ok';
2006: } else {
2007: return
2008: 'error: Count not permanently assign key, will need to be re-entered later.';
2009: }
2010: } else {
2011: return 'error: Could not assign key, try again later.';
2012: }
1.364 www 2013: } elsif (!$existing{$ckey}) {
1.345 www 2014: # the key does not exist
2015: return 'error: The key does not exist';
2016: } else {
2017: # the key is somebody else's
2018: return 'error: The key is already in use';
2019: }
1.344 www 2020: }
2021:
1.364 www 2022: # ------------------------------------------ put an additional comment on a key
2023:
2024: sub comment_access_key {
2025: #
2026: # a valid key looks like uname:udom#comments
2027: # comments are being appended
2028: #
2029: my ($ckey,$cdom,$cnum,$logentry)=@_;
2030: $cdom=
1.620 albertel 2031: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2032: $cnum=
1.620 albertel 2033: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2034: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2035: if ($existing{$ckey}) {
2036: $existing{$ckey}.='; '.$logentry;
2037: # ready to assign
1.367 www 2038: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2039: $cdom,$cnum) eq 'ok') {
2040: return 'ok';
2041: } else {
2042: return 'error: Count not store comment.';
2043: }
2044: } else {
2045: # the key does not exist
2046: return 'error: The key does not exist';
2047: }
2048: }
2049:
1.344 www 2050: # ------------------------------------------------------ Generate a set of keys
2051:
2052: sub generate_access_keys {
1.364 www 2053: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2054: $cdom=
1.620 albertel 2055: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2056: $cnum=
1.620 albertel 2057: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2058: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2059: unless (($cdom) && ($cnum)) { return 0; }
2060: if ($number>10000) { return 0; }
2061: sleep(2); # make sure don't get same seed twice
2062: srand(time()^($$+($$<<15))); # from "Programming Perl"
2063: my $total=0;
2064: for (my $i=1;$i<=$number;$i++) {
2065: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2066: sprintf("%lx",int(100000*rand)).'-'.
2067: sprintf("%lx",int(100000*rand));
2068: $newkey=~s/1/g/g; # folks mix up 1 and l
2069: $newkey=~s/0/h/g; # and also 0 and O
2070: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2071: if ($existing{$newkey}) {
2072: $i--;
2073: } else {
1.364 www 2074: if (&put('accesskeys',
2075: { $newkey => '# generated '.localtime().
1.620 albertel 2076: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2077: '; '.$logentry },
2078: $cdom,$cnum) eq 'ok') {
1.344 www 2079: $total++;
2080: }
2081: }
2082: }
1.620 albertel 2083: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2084: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2085: return $total;
2086: }
2087:
2088: # ------------------------------------------------------- Validate an accesskey
2089:
2090: sub validate_access_key {
2091: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2092: $cdom=
1.620 albertel 2093: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2094: $cnum=
1.620 albertel 2095: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2096: $udom=$env{'user.domain'} unless (defined($udom));
2097: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2098: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2099: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2100: }
2101:
2102: # ------------------------------------- Find the section of student in a course
1.652 albertel 2103: sub devalidate_getsection_cache {
2104: my ($udom,$unam,$courseid)=@_;
2105: my $hashid="$udom:$unam:$courseid";
2106: &devalidate_cache_new('getsection',$hashid);
2107: }
1.298 matthew 2108:
1.815 albertel 2109: sub courseid_to_courseurl {
2110: my ($courseid) = @_;
2111: #already url style courseid
2112: return $courseid if ($courseid =~ m{^/});
2113:
2114: if (exists($env{'course.'.$courseid.'.num'})) {
2115: my $cnum = $env{'course.'.$courseid.'.num'};
2116: my $cdom = $env{'course.'.$courseid.'.domain'};
2117: return "/$cdom/$cnum";
2118: }
2119:
2120: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2121: if (exists($courseinfo{'num'})) {
2122: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2123: }
2124:
2125: return undef;
2126: }
2127:
1.298 matthew 2128: sub getsection {
2129: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2130: my $cachetime=1800;
1.551 albertel 2131:
2132: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2133: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2134: if (defined($cached)) { return $result; }
2135:
1.298 matthew 2136: my %Pending;
2137: my %Expired;
2138: #
2139: # Each role can either have not started yet (pending), be active,
2140: # or have expired.
2141: #
2142: # If there is an active role, we are done.
2143: #
2144: # If there is more than one role which has not started yet,
2145: # choose the one which will start sooner
2146: # If there is one role which has not started yet, return it.
2147: #
2148: # If there is more than one expired role, choose the one which ended last.
2149: # If there is a role which has expired, return it.
2150: #
1.815 albertel 2151: $courseid = &courseid_to_courseurl($courseid);
1.1086 raeburn 2152: my $extra = &freeze_escape({'skipcheck' => 1});
2153: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 2154: foreach my $key (keys(%roleshash)) {
1.479 albertel 2155: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2156: my $section=$1;
2157: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2158: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2159: my $now=time;
1.548 albertel 2160: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2161: $Expired{$end}=$section;
2162: next;
2163: }
1.548 albertel 2164: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2165: $Pending{$start}=$section;
2166: next;
2167: }
1.599 albertel 2168: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2169: }
2170: #
2171: # Presumedly there will be few matching roles from the above
2172: # loop and the sorting time will be negligible.
2173: if (scalar(keys(%Pending))) {
2174: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2175: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2176: }
2177: if (scalar(keys(%Expired))) {
2178: my @sorted = sort {$a <=> $b} keys(%Expired);
2179: my $time = pop(@sorted);
1.599 albertel 2180: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2181: }
1.599 albertel 2182: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2183: }
1.70 www 2184:
1.599 albertel 2185: sub save_cache {
2186: &purge_remembered();
1.722 albertel 2187: #&Apache::loncommon::validate_page();
1.620 albertel 2188: undef(%env);
1.780 albertel 2189: undef($env_loaded);
1.599 albertel 2190: }
1.452 albertel 2191:
1.599 albertel 2192: my $to_remember=-1;
2193: my %remembered;
2194: my %accessed;
2195: my $kicks=0;
2196: my $hits=0;
1.849 albertel 2197: sub make_key {
2198: my ($name,$id) = @_;
1.872 albertel 2199: if (length($id) > 65
2200: && length(&escape($id)) > 200) {
2201: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2202: }
1.849 albertel 2203: return &escape($name.':'.$id);
2204: }
2205:
1.599 albertel 2206: sub devalidate_cache_new {
2207: my ($name,$id,$debug) = @_;
2208: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2209: $id=&make_key($name,$id);
1.599 albertel 2210: $memcache->delete($id);
2211: delete($remembered{$id});
2212: delete($accessed{$id});
2213: }
2214:
2215: sub is_cached_new {
2216: my ($name,$id,$debug) = @_;
1.849 albertel 2217: $id=&make_key($name,$id);
1.599 albertel 2218: if (exists($remembered{$id})) {
1.1133 foxr 2219: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2220: $accessed{$id}=[&gettimeofday()];
2221: $hits++;
2222: return ($remembered{$id},1);
2223: }
2224: my $value = $memcache->get($id);
2225: if (!(defined($value))) {
2226: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2227: return (undef,undef);
1.416 albertel 2228: }
1.599 albertel 2229: if ($value eq '__undef__') {
2230: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2231: $value=undef;
2232: }
2233: &make_room($id,$value,$debug);
2234: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2235: return ($value,1);
2236: }
2237:
2238: sub do_cache_new {
2239: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2240: $id=&make_key($name,$id);
1.599 albertel 2241: my $setvalue=$value;
2242: if (!defined($setvalue)) {
2243: $setvalue='__undef__';
2244: }
1.623 albertel 2245: if (!defined($time) ) {
2246: $time=600;
2247: }
1.599 albertel 2248: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2249: my $result = $memcache->set($id,$setvalue,$time);
2250: if (! $result) {
1.872 albertel 2251: &logthis("caching of id -> $id failed");
1.910 albertel 2252: $memcache->disconnect_all();
1.872 albertel 2253: }
1.600 albertel 2254: # need to make a copy of $value
1.919 albertel 2255: &make_room($id,$value,$debug);
1.599 albertel 2256: return $value;
2257: }
2258:
2259: sub make_room {
2260: my ($id,$value,$debug)=@_;
1.919 albertel 2261:
2262: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2263: : $value;
1.599 albertel 2264: if ($to_remember<0) { return; }
2265: $accessed{$id}=[&gettimeofday()];
2266: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2267: my $to_kick;
2268: my $max_time=0;
2269: foreach my $other (keys(%accessed)) {
2270: if (&tv_interval($accessed{$other}) > $max_time) {
2271: $to_kick=$other;
2272: $max_time=&tv_interval($accessed{$other});
2273: }
2274: }
2275: delete($remembered{$to_kick});
2276: delete($accessed{$to_kick});
2277: $kicks++;
2278: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2279: return;
2280: }
2281:
1.599 albertel 2282: sub purge_remembered {
1.604 albertel 2283: #&logthis("Tossing ".scalar(keys(%remembered)));
2284: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2285: undef(%remembered);
2286: undef(%accessed);
1.428 albertel 2287: }
1.70 www 2288: # ------------------------------------- Read an entry from a user's environment
2289:
2290: sub userenvironment {
2291: my ($udom,$unam,@what)=@_;
1.976 raeburn 2292: my $items;
2293: foreach my $item (@what) {
2294: $items.=&escape($item).'&';
2295: }
2296: $items=~s/\&$//;
1.70 www 2297: my %returnhash=();
1.1009 raeburn 2298: my $uhome = &homeserver($unam,$udom);
2299: unless ($uhome eq 'no_host') {
2300: my @answer=split(/\&/,
2301: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2302: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2303: return %returnhash;
2304: }
1.1009 raeburn 2305: my $i;
2306: for ($i=0;$i<=$#what;$i++) {
2307: $returnhash{$what[$i]}=&unescape($answer[$i]);
2308: }
1.70 www 2309: }
2310: return %returnhash;
1.1 albertel 2311: }
2312:
1.617 albertel 2313: # ---------------------------------------------------------- Get a studentphoto
2314: sub studentphoto {
2315: my ($udom,$unam,$ext) = @_;
2316: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2317: if (defined($env{'request.course.id'})) {
1.708 raeburn 2318: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2319: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2320: return(&retrievestudentphoto($udom,$unam,$ext));
2321: } else {
2322: my ($result,$perm_reqd)=
1.707 albertel 2323: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2324: if ($result eq 'ok') {
2325: if (!($perm_reqd eq 'yes')) {
2326: return(&retrievestudentphoto($udom,$unam,$ext));
2327: }
2328: }
2329: }
2330: }
2331: } else {
2332: my ($result,$perm_reqd) =
1.707 albertel 2333: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2334: if ($result eq 'ok') {
2335: if (!($perm_reqd eq 'yes')) {
2336: return(&retrievestudentphoto($udom,$unam,$ext));
2337: }
2338: }
2339: }
2340: return '/adm/lonKaputt/lonlogo_broken.gif';
2341: }
2342:
2343: sub retrievestudentphoto {
2344: my ($udom,$unam,$ext,$type) = @_;
2345: my $home=&Apache::lonnet::homeserver($unam,$udom);
2346: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2347: if ($ret eq 'ok') {
2348: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2349: if ($type eq 'thumbnail') {
2350: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2351: }
2352: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2353: return $tokenurl;
2354: } else {
2355: if ($type eq 'thumbnail') {
2356: return '/adm/lonKaputt/genericstudent_tn.gif';
2357: } else {
2358: return '/adm/lonKaputt/lonlogo_broken.gif';
2359: }
1.617 albertel 2360: }
2361: }
2362:
1.263 www 2363: # -------------------------------------------------------------------- New chat
2364:
2365: sub chatsend {
1.724 raeburn 2366: my ($newentry,$anon,$group)=@_;
1.620 albertel 2367: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2368: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2369: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2370: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2371: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2372: &escape($newentry)).':'.$group,$chome);
1.292 www 2373: }
2374:
2375: # ------------------------------------------ Find current version of a resource
2376:
2377: sub getversion {
2378: my $fname=&clutter(shift);
2379: unless ($fname=~/^\/res\//) { return -1; }
2380: return ¤tversion(&filelocation('',$fname));
2381: }
2382:
2383: sub currentversion {
2384: my $fname=shift;
2385: my $author=$fname;
2386: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2387: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2388: my $home=&homeserver($uname,$udom);
1.292 www 2389: if ($home eq 'no_host') {
2390: return -1;
2391: }
1.1112 www 2392: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2393: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2394: return -1;
2395: }
1.1112 www 2396: return $answer;
1.263 www 2397: }
2398:
1.1111 www 2399: #
2400: # Return special version number of resource if set by override, empty otherwise
2401: #
2402: sub usedversion {
2403: my $fname=shift;
2404: unless ($fname) { $fname=$env{'request.uri'}; }
2405: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2406: if ($urlversion) { return $urlversion; }
2407: return '';
2408: }
2409:
1.1 albertel 2410: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2411:
1.1 albertel 2412: sub subscribe {
2413: my $fname=shift;
1.761 raeburn 2414: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2415: $fname=~s/[\n\r]//g;
1.1 albertel 2416: my $author=$fname;
2417: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2418: my ($udom,$uname)=split(/\//,$author);
2419: my $home=homeserver($uname,$udom);
1.335 albertel 2420: if ($home eq 'no_host') {
2421: return 'not_found';
1.1 albertel 2422: }
2423: my $answer=reply("sub:$fname",$home);
1.64 www 2424: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2425: $answer.=' by '.$home;
2426: }
1.1 albertel 2427: return $answer;
2428: }
2429:
1.8 www 2430: # -------------------------------------------------------------- Replicate file
2431:
2432: sub repcopy {
2433: my $filename=shift;
1.23 www 2434: $filename=~s/\/+/\//g;
1.1142 raeburn 2435: my $londocroot = $perlvar{'lonDocRoot'};
2436: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
2437: if ($filename=~m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
2438: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2439: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2440: return &repcopy_userfile($filename);
2441: }
1.532 albertel 2442: $filename=~s/[\n\r]//g;
1.8 www 2443: my $transname="$filename.in.transfer";
1.828 www 2444: # FIXME: this should flock
1.607 raeburn 2445: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2446: my $remoteurl=subscribe($filename);
1.64 www 2447: if ($remoteurl =~ /^con_lost by/) {
2448: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2449: return 'unavailable';
1.8 www 2450: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2451: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2452: return 'not_found';
1.64 www 2453: } elsif ($remoteurl =~ /^rejected by/) {
2454: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2455: return 'forbidden';
1.20 www 2456: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2457: return 'ok';
1.8 www 2458: } else {
1.290 www 2459: my $author=$filename;
2460: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2461: my ($udom,$uname)=split(/\//,$author);
2462: my $home=homeserver($uname,$udom);
2463: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2464: my @parts=split(/\//,$filename);
2465: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2466: if ($path ne "$londocroot/res") {
1.8 www 2467: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2468: return 'bad_request';
1.8 www 2469: }
2470: my $count;
2471: for ($count=5;$count<$#parts;$count++) {
2472: $path.="/$parts[$count]";
2473: if ((-e $path)!=1) {
2474: mkdir($path,0777);
2475: }
2476: }
2477: my $ua=new LWP::UserAgent;
2478: my $request=new HTTP::Request('GET',"$remoteurl");
2479: my $response=$ua->request($request,$transname);
2480: if ($response->is_error()) {
2481: unlink($transname);
2482: my $message=$response->status_line;
1.672 albertel 2483: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2484: ." LWP get: $message: $filename</font>");
1.607 raeburn 2485: return 'unavailable';
1.8 www 2486: } else {
1.16 www 2487: if ($remoteurl!~/\.meta$/) {
2488: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2489: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2490: if ($mresponse->is_error()) {
2491: unlink($filename.'.meta');
2492: &logthis(
1.672 albertel 2493: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2494: }
2495: }
1.8 www 2496: rename($transname,$filename);
1.607 raeburn 2497: return 'ok';
1.8 www 2498: }
1.290 www 2499: }
1.8 www 2500: }
1.330 www 2501: }
2502:
2503: # ------------------------------------------------ Get server side include body
2504: sub ssi_body {
1.381 albertel 2505: my ($filelink,%form)=@_;
1.606 matthew 2506: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2507: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2508: }
1.953 www 2509: my $output='';
2510: my $response;
1.980 raeburn 2511: if ($filelink=~/^https?\:/) {
1.954 raeburn 2512: ($output,$response)=&externalssi($filelink);
1.953 www 2513: } else {
1.1004 droeschl 2514: $filelink .= $filelink=~/\?/ ? '&' : '?';
2515: $filelink .= 'inhibitmenu=yes';
1.953 www 2516: ($output,$response)=&ssi($filelink,%form);
2517: }
1.778 albertel 2518: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2519: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2520: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2521: if (wantarray) {
2522: return ($output, $response);
2523: } else {
2524: return $output;
2525: }
1.8 www 2526: }
2527:
1.15 www 2528: # --------------------------------------------------------- Server Side Include
2529:
1.782 albertel 2530: sub absolute_url {
2531: my ($host_name) = @_;
2532: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2533: if ($host_name eq '') {
2534: $host_name = $ENV{'SERVER_NAME'};
2535: }
2536: return $protocol.$host_name;
2537: }
2538:
1.942 foxr 2539: #
2540: # Server side include.
2541: # Parameters:
2542: # fn Possibly encrypted resource name/id.
2543: # form Hash that describes how the rendering should be done
2544: # and other things.
1.944 foxr 2545: # Returns:
1.950 raeburn 2546: # Scalar context: The content of the response.
2547: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2548: #
1.15 www 2549: sub ssi {
2550:
1.944 foxr 2551: my ($fn,%form)=@_;
1.15 www 2552: my $ua=new LWP::UserAgent;
1.23 www 2553: my $request;
1.711 albertel 2554:
2555: $form{'no_update_last_known'}=1;
1.895 albertel 2556: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2557: if (%form) {
1.782 albertel 2558: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2559: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2560: } else {
1.782 albertel 2561: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2562: }
2563:
1.15 www 2564: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2565: my $response=$ua->request($request);
2566:
1.944 foxr 2567: if (wantarray) {
2568: return ($response->content, $response);
2569: } else {
2570: return $response->content;
1.942 foxr 2571: }
1.324 www 2572: }
2573:
2574: sub externalssi {
2575: my ($url)=@_;
2576: my $ua=new LWP::UserAgent;
2577: my $request=new HTTP::Request('GET',$url);
2578: my $response=$ua->request($request);
1.954 raeburn 2579: if (wantarray) {
2580: return ($response->content, $response);
2581: } else {
2582: return $response->content;
2583: }
1.15 www 2584: }
1.254 www 2585:
1.492 albertel 2586: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2587:
2588: sub allowuploaded {
2589: my ($srcurl,$url)=@_;
2590: $url=&clutter(&declutter($url));
2591: my $dir=$url;
2592: $dir=~s/\/[^\/]+$//;
2593: my %httpref=();
2594: my $httpurl=&hreflocation('',$url);
2595: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2596: &Apache::lonnet::appenv(\%httpref);
1.254 www 2597: }
1.477 raeburn 2598:
1.478 albertel 2599: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2600: # input: action, courseID, current domain, intended
1.637 raeburn 2601: # path to file, source of file, instruction to parse file for objects,
2602: # ref to hash for embedded objects,
2603: # ref to hash for codebase of java objects.
1.1095 raeburn 2604: # reference to scalar to accommodate mime type determined
2605: # from File::MMagic if $parser = parse.
1.637 raeburn 2606: #
1.485 raeburn 2607: # output: url to file (if action was uploaddoc),
2608: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2609: #
1.478 albertel 2610: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2611: # course.
1.477 raeburn 2612: #
1.478 albertel 2613: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2614: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2615: # course's home server.
1.477 raeburn 2616: #
1.478 albertel 2617: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2618: # be copied from $source (current location) to
2619: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2620: # and will then be copied to
2621: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2622: # course's home server.
1.485 raeburn 2623: #
1.481 raeburn 2624: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2625: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2626: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2627: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2628: # in course's home server.
1.637 raeburn 2629: #
1.477 raeburn 2630:
2631: sub process_coursefile {
1.1095 raeburn 2632: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2633: $mimetype)=@_;
1.477 raeburn 2634: my $fetchresult;
1.638 albertel 2635: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2636: if ($action eq 'propagate') {
1.638 albertel 2637: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2638: $home);
1.481 raeburn 2639: } else {
1.477 raeburn 2640: my $fpath = '';
2641: my $fname = $file;
1.478 albertel 2642: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2643: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2644: my $filepath = &build_filepath($fpath);
1.481 raeburn 2645: if ($action eq 'copy') {
2646: if ($source eq '') {
2647: $fetchresult = 'no source file';
2648: return $fetchresult;
2649: } else {
2650: my $destination = $filepath.'/'.$fname;
2651: rename($source,$destination);
2652: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2653: $home);
1.481 raeburn 2654: }
2655: } elsif ($action eq 'uploaddoc') {
2656: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2657: print $fh $env{'form.'.$source};
1.481 raeburn 2658: close($fh);
1.637 raeburn 2659: if ($parser eq 'parse') {
1.1024 raeburn 2660: my $mm = new File::MMagic;
1.1095 raeburn 2661: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2662: if ($type eq 'text/html') {
1.1024 raeburn 2663: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2664: unless ($parse_result eq 'ok') {
2665: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2666: }
1.637 raeburn 2667: }
1.1095 raeburn 2668: if (ref($mimetype)) {
2669: $$mimetype = $type;
2670: }
1.637 raeburn 2671: }
1.477 raeburn 2672: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2673: $home);
1.481 raeburn 2674: if ($fetchresult eq 'ok') {
2675: return '/uploaded/'.$fpath.'/'.$fname;
2676: } else {
2677: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2678: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2679: return '/adm/notfound.html';
2680: }
1.477 raeburn 2681: }
2682: }
1.485 raeburn 2683: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2684: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2685: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2686: }
2687: return $fetchresult;
2688: }
2689:
1.637 raeburn 2690: sub build_filepath {
2691: my ($fpath) = @_;
2692: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2693: unless ($fpath eq '') {
2694: my @parts=split('/',$fpath);
2695: foreach my $part (@parts) {
2696: $filepath.= '/'.$part;
2697: if ((-e $filepath)!=1) {
2698: mkdir($filepath,0777);
2699: }
2700: }
2701: }
2702: return $filepath;
2703: }
2704:
2705: sub store_edited_file {
1.638 albertel 2706: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2707: my $file = $primary_url;
2708: $file =~ s#^/uploaded/$docudom/$docuname/##;
2709: my $fpath = '';
2710: my $fname = $file;
2711: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2712: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2713: my $filepath = &build_filepath($fpath);
2714: open(my $fh,'>'.$filepath.'/'.$fname);
2715: print $fh $content;
2716: close($fh);
1.638 albertel 2717: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2718: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2719: $home);
1.637 raeburn 2720: if ($$fetchresult eq 'ok') {
2721: return '/uploaded/'.$fpath.'/'.$fname;
2722: } else {
1.638 albertel 2723: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2724: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2725: return '/adm/notfound.html';
2726: }
2727: }
2728:
1.531 albertel 2729: sub clean_filename {
1.831 albertel 2730: my ($fname,$args)=@_;
1.315 www 2731: # Replace Windows backslashes by forward slashes
1.257 www 2732: $fname=~s/\\/\//g;
1.831 albertel 2733: if (!$args->{'keep_path'}) {
2734: # Get rid of everything but the actual filename
2735: $fname=~s/^.*\/([^\/]+)$/$1/;
2736: }
1.315 www 2737: # Replace spaces by underscores
2738: $fname=~s/\s+/\_/g;
2739: # Replace all other weird characters by nothing
1.831 albertel 2740: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2741: # Replace all .\d. sequences with _\d. so they no longer look like version
2742: # numbers
2743: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2744: return $fname;
2745: }
1.1051 raeburn 2746: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2747: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2748: # image with the same aspect ratio as the original, but with dimensions which do
2749: # not exceed $resizewidth and $resizeheight.
2750:
1.984 neumanie 2751: sub resizeImage {
1.1051 raeburn 2752: my ($img_path,$resizewidth,$resizeheight) = @_;
2753: my $ima = Image::Magick->new;
2754: my $resized;
2755: if (-e $img_path) {
2756: $ima->Read($img_path);
2757: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2758: my $width = $ima->Get('width');
2759: my $height = $ima->Get('height');
2760: if ($width > $resizewidth) {
2761: my $factor = $width/$resizewidth;
2762: my $newheight = $height/$factor;
2763: $ima->Scale(width=>$resizewidth,height=>$newheight);
2764: $resized = 1;
2765: }
2766: }
2767: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2768: my $width = $ima->Get('width');
2769: my $height = $ima->Get('height');
2770: if ($height > $resizeheight) {
2771: my $factor = $height/$resizeheight;
2772: my $newwidth = $width/$factor;
2773: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2774: $resized = 1;
2775: }
2776: }
2777: if ($resized) {
2778: $ima->Write($img_path);
2779: }
2780: }
2781: return;
1.977 amueller 2782: }
2783:
1.608 albertel 2784: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2785: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2786: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2787: # $context - possible values: coursedoc, existingfile, overwrite,
2788: # canceloverwrite, or ''.
2789: # if 'coursedoc': upload to the current course
2790: # if 'existingfile': write file to tmp/overwrites directory
2791: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2792: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2793: # $subdir - directory in userfile to store the file into
1.858 raeburn 2794: # $parser - instruction to parse file for objects ($parser = parse)
2795: # $allfiles - reference to hash for embedded objects
2796: # $codebase - reference to hash for codebase of java objects
2797: # $desuname - username for permanent storage of uploaded file
2798: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2799: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2800: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2801: # $resizewidth - width (pixels) to which to resize uploaded image
2802: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 2803: # $mimetype - reference to scalar to accommodate mime type determined
2804: # from File::MMagic if $parser = parse.
1.858 raeburn 2805: #
1.686 albertel 2806: # output: url of file in userspace, or error: <message>
2807: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2808:
1.531 albertel 2809: sub userfileupload {
1.1090 raeburn 2810: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 2811: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2812: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2813: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2814: $fname=&clean_filename($fname);
1.1090 raeburn 2815: # See if there is anything left
1.257 www 2816: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2817: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2818: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2819: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2820: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2821: my $now = time;
1.1090 raeburn 2822: my $filepath;
1.1095 raeburn 2823: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2824: $filepath = 'tmp/helprequests/'.$now;
2825: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2826: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2827: '_'.$env{'user.domain'}.'/pending';
2828: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2829: my ($docuname,$docudom);
2830: if ($destudom) {
2831: $docudom = $destudom;
2832: } else {
2833: $docudom = $env{'user.domain'};
2834: }
2835: if ($destuname) {
2836: $docuname = $destuname;
2837: } else {
2838: $docuname = $env{'user.name'};
2839: }
2840: if (exists($env{'form.group'})) {
2841: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2842: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2843: }
2844: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2845: if ($context eq 'canceloverwrite') {
2846: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2847: if (-e $tempfile) {
2848: my @info = stat($tempfile);
2849: if ($info[9] eq $env{'form.timestamp'}) {
2850: unlink($tempfile);
2851: }
2852: }
2853: return;
1.523 raeburn 2854: }
2855: }
1.1090 raeburn 2856: # Create the directory if not present
1.741 raeburn 2857: my @parts=split(/\//,$filepath);
2858: my $fullpath = $perlvar{'lonDaemons'};
2859: for (my $i=0;$i<@parts;$i++) {
2860: $fullpath .= '/'.$parts[$i];
2861: if ((-e $fullpath)!=1) {
2862: mkdir($fullpath,0777);
2863: }
2864: }
2865: open(my $fh,'>'.$fullpath.'/'.$fname);
2866: print $fh $env{'form.'.$formname};
2867: close($fh);
1.1090 raeburn 2868: if ($context eq 'existingfile') {
2869: my @info = stat($fullpath.'/'.$fname);
2870: return ($fullpath.'/'.$fname,$info[9]);
2871: } else {
2872: return $fullpath.'/'.$fname;
2873: }
1.523 raeburn 2874: }
1.995 raeburn 2875: if ($subdir eq 'scantron') {
2876: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2877: } else {
1.995 raeburn 2878: $fname="$subdir/$fname";
2879: }
1.1090 raeburn 2880: if ($context eq 'coursedoc') {
1.638 albertel 2881: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2882: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2883: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2884: return &finishuserfileupload($docuname,$docudom,
2885: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2886: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 2887: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2888: } else {
1.620 albertel 2889: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2890: return &process_coursefile('uploaddoc',$docuname,$docudom,
2891: $fname,$formname,$parser,
1.1095 raeburn 2892: $allfiles,$codebase,$mimetype);
1.481 raeburn 2893: }
1.719 banghart 2894: } elsif (defined($destuname)) {
2895: my $docuname=$destuname;
2896: my $docudom=$destudom;
1.860 raeburn 2897: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2898: $parser,$allfiles,$codebase,
1.1051 raeburn 2899: $thumbwidth,$thumbheight,
1.1095 raeburn 2900: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2901: } else {
1.638 albertel 2902: my $docuname=$env{'user.name'};
2903: my $docudom=$env{'user.domain'};
1.714 raeburn 2904: if (exists($env{'form.group'})) {
2905: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2906: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2907: }
1.860 raeburn 2908: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2909: $parser,$allfiles,$codebase,
1.1051 raeburn 2910: $thumbwidth,$thumbheight,
1.1095 raeburn 2911: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2912: }
1.271 www 2913: }
2914:
2915: sub finishuserfileupload {
1.860 raeburn 2916: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 2917: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2918: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2919: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2920:
1.860 raeburn 2921: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2922: $file=$fname;
2923: if ($fname=~m|/|) {
2924: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2925: $path.=$fnamepath.'/';
2926: }
1.259 www 2927: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2928: my $count;
2929: for ($count=4;$count<=$#parts;$count++) {
2930: $filepath.="/$parts[$count]";
2931: if ((-e $filepath)!=1) {
2932: mkdir($filepath,0777);
2933: }
2934: }
1.984 neumanie 2935:
1.258 www 2936: # Save the file
2937: {
1.701 albertel 2938: if (!open(FH,'>'.$filepath.'/'.$file)) {
2939: &logthis('Failed to create '.$filepath.'/'.$file);
2940: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2941: return '/adm/notfound.html';
2942: }
1.1090 raeburn 2943: if ($context eq 'overwrite') {
1.1117 foxr 2944: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 2945: my $target = $filepath.'/'.$file;
2946: if (-e $source) {
2947: my @info = stat($source);
2948: if ($info[9] eq $env{'form.timestamp'}) {
2949: unless (&File::Copy::move($source,$target)) {
2950: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2951: return "Moving from $source failed";
2952: }
2953: } else {
2954: return "Temporary file: $source had unexpected date/time for last modification";
2955: }
2956: } else {
2957: return "Temporary file: $source missing";
2958: }
2959: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2960: &logthis('Failed to write to '.$filepath.'/'.$file);
2961: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2962: return '/adm/notfound.html';
2963: }
1.570 albertel 2964: close(FH);
1.1051 raeburn 2965: if ($resizewidth && $resizeheight) {
2966: my $mm = new File::MMagic;
2967: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2968: if ($mime_type =~ m{^image/}) {
2969: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2970: }
1.977 amueller 2971: }
1.258 www 2972: }
1.637 raeburn 2973: if ($parser eq 'parse') {
1.1024 raeburn 2974: my $mm = new File::MMagic;
1.1095 raeburn 2975: my $type = $mm->checktype_filename($filepath.'/'.$file);
2976: if ($type eq 'text/html') {
1.1024 raeburn 2977: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2978: $allfiles,$codebase);
2979: unless ($parse_result eq 'ok') {
2980: &logthis('Failed to parse '.$filepath.$file.
2981: ' for embedded media: '.$parse_result);
2982: }
1.637 raeburn 2983: }
1.1095 raeburn 2984: if (ref($mimetype)) {
2985: $$mimetype = $type;
2986: }
1.637 raeburn 2987: }
1.860 raeburn 2988: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2989: my $input = $filepath.'/'.$file;
2990: my $output = $filepath.'/'.'tn-'.$file;
2991: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2992: system("convert -sample $thumbsize $input $output");
2993: if (-e $filepath.'/'.'tn-'.$file) {
2994: $fetchthumb = 1;
2995: }
2996: }
1.858 raeburn 2997:
1.259 www 2998: # Notify homeserver to grep it
2999: #
1.984 neumanie 3000: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3001: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3002: if ($fetchresult eq 'ok') {
1.860 raeburn 3003: if ($fetchthumb) {
3004: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3005: if ($thumbresult ne 'ok') {
3006: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3007: $docuhome.': '.$thumbresult);
3008: }
3009: }
1.259 www 3010: #
1.258 www 3011: # Return the URL to it
1.494 albertel 3012: return '/uploaded/'.$path.$file;
1.263 www 3013: } else {
1.494 albertel 3014: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3015: ': '.$fetchresult);
1.263 www 3016: return '/adm/notfound.html';
1.858 raeburn 3017: }
1.493 albertel 3018: }
3019:
1.637 raeburn 3020: sub extract_embedded_items {
1.961 raeburn 3021: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3022: my @state = ();
3023: my %javafiles = (
3024: codebase => '',
3025: code => '',
3026: archive => ''
3027: );
3028: my %mediafiles = (
3029: src => '',
3030: movie => '',
3031: );
1.648 raeburn 3032: my $p;
3033: if ($content) {
3034: $p = HTML::LCParser->new($content);
3035: } else {
1.961 raeburn 3036: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3037: }
1.641 albertel 3038: while (my $t=$p->get_token()) {
1.640 albertel 3039: if ($t->[0] eq 'S') {
3040: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3041: push(@state, $tagname);
1.648 raeburn 3042: if (lc($tagname) eq 'allow') {
3043: &add_filetype($allfiles,$attr->{'src'},'src');
3044: }
1.640 albertel 3045: if (lc($tagname) eq 'img') {
3046: &add_filetype($allfiles,$attr->{'src'},'src');
3047: }
1.886 albertel 3048: if (lc($tagname) eq 'a') {
3049: &add_filetype($allfiles,$attr->{'href'},'href');
3050: }
1.645 raeburn 3051: if (lc($tagname) eq 'script') {
3052: if ($attr->{'archive'} =~ /\.jar$/i) {
3053: &add_filetype($allfiles,$attr->{'archive'},'archive');
3054: } else {
3055: &add_filetype($allfiles,$attr->{'src'},'src');
3056: }
3057: }
3058: if (lc($tagname) eq 'link') {
3059: if (lc($attr->{'rel'}) eq 'stylesheet') {
3060: &add_filetype($allfiles,$attr->{'href'},'href');
3061: }
3062: }
1.640 albertel 3063: if (lc($tagname) eq 'object' ||
3064: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3065: foreach my $item (keys(%javafiles)) {
3066: $javafiles{$item} = '';
3067: }
3068: }
3069: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3070: my $name = lc($attr->{'name'});
3071: foreach my $item (keys(%javafiles)) {
3072: if ($name eq $item) {
3073: $javafiles{$item} = $attr->{'value'};
3074: last;
3075: }
3076: }
3077: foreach my $item (keys(%mediafiles)) {
3078: if ($name eq $item) {
3079: &add_filetype($allfiles, $attr->{'value'}, 'value');
3080: last;
3081: }
3082: }
3083: }
3084: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3085: foreach my $item (keys(%javafiles)) {
3086: if ($attr->{$item}) {
3087: $javafiles{$item} = $attr->{$item};
3088: last;
3089: }
3090: }
3091: foreach my $item (keys(%mediafiles)) {
3092: if ($attr->{$item}) {
3093: &add_filetype($allfiles,$attr->{$item},$item);
3094: last;
3095: }
3096: }
3097: }
3098: } elsif ($t->[0] eq 'E') {
3099: my ($tagname) = ($t->[1]);
3100: if ($javafiles{'codebase'} ne '') {
3101: $javafiles{'codebase'} .= '/';
3102: }
3103: if (lc($tagname) eq 'applet' ||
3104: lc($tagname) eq 'object' ||
3105: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3106: ) {
3107: foreach my $item (keys(%javafiles)) {
3108: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3109: my $file=$javafiles{'codebase'}.$javafiles{$item};
3110: &add_filetype($allfiles,$file,$item);
3111: }
3112: }
3113: }
3114: pop @state;
3115: }
3116: }
1.637 raeburn 3117: return 'ok';
3118: }
3119:
1.639 albertel 3120: sub add_filetype {
3121: my ($allfiles,$file,$type)=@_;
3122: if (exists($allfiles->{$file})) {
3123: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3124: push(@{$allfiles->{$file}}, &escape($type));
3125: }
3126: } else {
3127: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3128: }
3129: }
3130:
1.493 albertel 3131: sub removeuploadedurl {
1.984 neumanie 3132: my ($url)=@_;
3133: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3134: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3135: }
3136:
3137: sub removeuserfile {
3138: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3139: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3140: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3141: if ($result eq 'ok') {
1.798 raeburn 3142: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3143: my $metafile = $fname.'.meta';
3144: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3145: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3146: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3147: my $sqlresult =
1.823 albertel 3148: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3149: 'portfolio_metadata',$group,
3150: 'delete');
1.798 raeburn 3151: }
3152: }
3153: return $result;
1.257 www 3154: }
1.15 www 3155:
1.530 albertel 3156: sub mkdiruserfile {
3157: my ($docuname,$docudom,$dir)=@_;
3158: my $home=&homeserver($docuname,$docudom);
3159: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3160: }
3161:
1.531 albertel 3162: sub renameuserfile {
3163: my ($docuname,$docudom,$old,$new)=@_;
3164: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3165: my $result = &reply("renameuserfile:$docudom:$docuname:".
3166: &escape("$old").':'.&escape("$new"),$home);
3167: if ($result eq 'ok') {
3168: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3169: my $oldmeta = $old.'.meta';
3170: my $newmeta = $new.'.meta';
3171: my $metaresult =
3172: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3173: my $url = "/uploaded/$docudom/$docuname/$old";
3174: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3175: my $sqlresult =
1.823 albertel 3176: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3177: 'portfolio_metadata',$group,
3178: 'delete');
1.798 raeburn 3179: }
3180: }
3181: return $result;
1.531 albertel 3182: }
3183:
1.14 www 3184: # ------------------------------------------------------------------------- Log
3185:
3186: sub log {
3187: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3188: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3189: }
3190:
3191: # ------------------------------------------------------------------ Course Log
1.352 www 3192: #
3193: # This routine flushes several buffers of non-mission-critical nature
3194: #
1.157 www 3195:
3196: sub flushcourselogs {
1.352 www 3197: &logthis('Flushing log buffers');
3198: #
3199: # course logs
3200: # This is a log of all transactions in a course, which can be used
3201: # for data mining purposes
3202: #
3203: # It also collects the courseid database, which lists last transaction
3204: # times and course titles for all courseids
3205: #
3206: my %courseidbuffer=();
1.921 raeburn 3207: foreach my $crsid (keys(%courselogs)) {
1.352 www 3208: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3209: &escape($courselogs{$crsid}),
3210: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3211: delete $courselogs{$crsid};
3212: } else {
3213: &logthis('Failed to flush log buffer for '.$crsid);
3214: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3215: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3216: " exceeded maximum size, deleting.</font>");
3217: delete $courselogs{$crsid};
3218: }
1.352 www 3219: }
1.920 raeburn 3220: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3221: 'description' => $coursedescrbuf{$crsid},
3222: 'inst_code' => $courseinstcodebuf{$crsid},
3223: 'type' => $coursetypebuf{$crsid},
3224: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3225: };
1.191 harris41 3226: }
1.352 www 3227: #
3228: # Write course id database (reverse lookup) to homeserver of courses
3229: # Is used in pickcourse
3230: #
1.840 albertel 3231: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3232: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3233: $courseidbuffer{$crs_home},
3234: $crs_home,'timeonly');
1.352 www 3235: }
3236: #
3237: # File accesses
3238: # Writes to the dynamic metadata of resources to get hit counts, etc.
3239: #
1.449 matthew 3240: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3241: if ($entry =~ /___count$/) {
3242: my ($dom,$name);
1.807 albertel 3243: ($dom,$name,undef)=
1.811 albertel 3244: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3245: if (! defined($dom) || $dom eq '' ||
3246: ! defined($name) || $name eq '') {
1.620 albertel 3247: my $cid = $env{'request.course.id'};
3248: $dom = $env{'request.'.$cid.'.domain'};
3249: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3250: }
1.450 matthew 3251: my $value = $accesshash{$entry};
3252: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3253: my %temphash=($url => $value);
1.449 matthew 3254: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3255: if ($result eq 'ok') {
3256: delete $accesshash{$entry};
3257: } elsif ($result eq 'unknown_cmd') {
3258: # Target server has old code running on it.
1.450 matthew 3259: my %temphash=($entry => $value);
1.449 matthew 3260: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3261: delete $accesshash{$entry};
3262: }
3263: }
3264: } else {
1.811 albertel 3265: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 3266: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3267: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3268: delete $accesshash{$entry};
3269: }
1.185 www 3270: }
1.191 harris41 3271: }
1.352 www 3272: #
3273: # Roles
3274: # Reverse lookup of user roles for course faculty/staff and co-authorship
3275: #
1.800 albertel 3276: foreach my $entry (keys(%userrolehash)) {
1.351 www 3277: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3278: split(/\:/,$entry);
3279: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3280: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3281: $rudom,$runame) eq 'ok') {
3282: delete $userrolehash{$entry};
3283: }
3284: }
1.662 raeburn 3285: #
3286: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3287: #
3288: my %domrolebuffer = ();
1.1000 raeburn 3289: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3290: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3291: if ($domrolebuffer{$rudom}) {
3292: $domrolebuffer{$rudom}.='&'.&escape($entry).
3293: '='.&escape($domainrolehash{$entry});
3294: } else {
3295: $domrolebuffer{$rudom}.=&escape($entry).
3296: '='.&escape($domainrolehash{$entry});
3297: }
3298: delete $domainrolehash{$entry};
3299: }
3300: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3301: my %servers = &get_servers($dom,'library');
3302: foreach my $tryserver (keys(%servers)) {
3303: unless (&reply('domroleput:'.$dom.':'.
3304: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3305: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3306: }
1.662 raeburn 3307: }
3308: }
1.186 www 3309: $dumpcount++;
1.157 www 3310: }
3311:
3312: sub courselog {
3313: my $what=shift;
1.158 www 3314: $what=time.':'.$what;
1.620 albertel 3315: unless ($env{'request.course.id'}) { return ''; }
3316: $coursedombuf{$env{'request.course.id'}}=
3317: $env{'course.'.$env{'request.course.id'}.'.domain'};
3318: $coursenumbuf{$env{'request.course.id'}}=
3319: $env{'course.'.$env{'request.course.id'}.'.num'};
3320: $coursehombuf{$env{'request.course.id'}}=
3321: $env{'course.'.$env{'request.course.id'}.'.home'};
3322: $coursedescrbuf{$env{'request.course.id'}}=
3323: $env{'course.'.$env{'request.course.id'}.'.description'};
3324: $courseinstcodebuf{$env{'request.course.id'}}=
3325: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3326: $courseownerbuf{$env{'request.course.id'}}=
3327: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3328: $coursetypebuf{$env{'request.course.id'}}=
3329: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3330: if (defined $courselogs{$env{'request.course.id'}}) {
3331: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3332: } else {
1.620 albertel 3333: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3334: }
1.620 albertel 3335: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3336: &flushcourselogs();
3337: }
1.158 www 3338: }
3339:
3340: sub courseacclog {
3341: my $fnsymb=shift;
1.620 albertel 3342: unless ($env{'request.course.id'}) { return ''; }
3343: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3344: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3345: $what.=':POST';
1.583 matthew 3346: # FIXME: Probably ought to escape things....
1.800 albertel 3347: foreach my $key (keys(%env)) {
3348: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3349: my $formitem = $1;
3350: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3351: $what.=':'.$formitem.'='.$env{$key};
3352: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3353: $what.=':'.$formitem.'='.$env{$key};
3354: }
1.158 www 3355: }
1.191 harris41 3356: }
1.583 matthew 3357: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3358: # FIXME: We should not be depending on a form parameter that someone
3359: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3360: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3361: $what.= ':POST';
3362: # FIXME: Probably ought to escape things....
3363: foreach my $element ('courseexp','crsfulltext','crsrelated',
3364: 'crsdiscuss') {
1.620 albertel 3365: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3366: }
3367: }
1.158 www 3368: }
3369: &courselog($what);
1.149 www 3370: }
3371:
1.185 www 3372: sub countacc {
3373: my $url=&declutter(shift);
1.458 matthew 3374: return if (! defined($url) || $url eq '');
1.620 albertel 3375: unless ($env{'request.course.id'}) { return ''; }
3376: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 3377: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3378: $accesshash{$key}++;
1.185 www 3379: }
1.349 www 3380:
1.361 www 3381: sub linklog {
3382: my ($from,$to)=@_;
3383: $from=&declutter($from);
3384: $to=&declutter($to);
3385: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3386: $accesshash{$to.'___'.$from.'___goto'}=1;
3387: }
3388:
1.349 www 3389: sub userrolelog {
3390: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 3391: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 3392: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 3393: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 3394: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 3395: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3396: $userrolehash
3397: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3398: =$tend.':'.$tstart;
1.662 raeburn 3399: }
1.898 albertel 3400: if (($env{'request.role'} =~ /dc\./) &&
3401: (($trole=~/^au/) || ($trole=~/^in/) ||
3402: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 3403: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3404: ($trole=~/^co/))) {
1.898 albertel 3405: $userrolehash
3406: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3407: =$tend.':'.$tstart;
3408: }
1.662 raeburn 3409: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3410: ($trole=~/^li/) || ($trole=~/^li/) ||
3411: ($trole=~/^au/) || ($trole=~/^dg/) ||
3412: ($trole=~/^sc/)) {
3413: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3414: $domainrolehash
3415: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3416: = $tend.':'.$tstart;
3417: }
1.351 www 3418: }
3419:
1.957 raeburn 3420: sub courserolelog {
3421: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3422: if (($trole eq 'cc') || ($trole eq 'in') ||
3423: ($trole eq 'ep') || ($trole eq 'ad') ||
3424: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3425: ($trole=~/^cr/) || ($trole eq 'gr') ||
3426: ($trole eq 'co')) {
1.957 raeburn 3427: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3428: my $cdom = $1;
3429: my $cnum = $2;
3430: my $sec = $3;
3431: my $namespace = 'rolelog';
3432: my %storehash = (
3433: role => $trole,
3434: start => $tstart,
3435: end => $tend,
3436: selfenroll => $selfenroll,
3437: context => $context,
3438: );
3439: if ($trole eq 'gr') {
3440: $namespace = 'groupslog';
3441: $storehash{'group'} = $sec;
3442: } else {
3443: $storehash{'section'} = $sec;
3444: }
3445: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3446: if (($trole ne 'st') || ($sec ne '')) {
3447: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3448: }
1.957 raeburn 3449: }
3450: }
3451: return;
3452: }
3453:
1.351 www 3454: sub get_course_adv_roles {
1.948 raeburn 3455: my ($cid,$codes) = @_;
1.620 albertel 3456: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3457: my %coursehash=&coursedescription($cid);
1.988 raeburn 3458: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3459: my %nothide=();
1.800 albertel 3460: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3461: if ($user !~ /:/) {
3462: $nothide{join(':',split(/[\@]/,$user))}=1;
3463: } else {
3464: $nothide{$user}=1;
3465: }
1.470 www 3466: }
1.351 www 3467: my %returnhash=();
3468: my %dumphash=
3469: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3470: my $now=time;
1.997 raeburn 3471: my %privileged;
1.1000 raeburn 3472: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3473: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3474: if (($tstart) && ($tstart<0)) { next; }
3475: if (($tend) && ($tend<$now)) { next; }
3476: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3477: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3478: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3479: unless (ref($privileged{$domain}) eq 'HASH') {
3480: my %dompersonnel =
1.998 raeburn 3481: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3482: $privileged{$domain} = {};
3483: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3484: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3485: foreach my $user (keys(%{$dompersonnel{$server}})) {
3486: my ($trole,$uname,$udom) = split(/:/,$user);
3487: $privileged{$udom}{$uname} = 1;
3488: }
3489: }
3490: }
3491: }
3492: if ((exists($privileged{$domain}{$username})) &&
3493: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3494: if ($role eq 'cr') { next; }
1.948 raeburn 3495: if ($codes) {
3496: if ($section) { $role .= ':'.$section; }
3497: if ($returnhash{$role}) {
3498: $returnhash{$role}.=','.$username.':'.$domain;
3499: } else {
3500: $returnhash{$role}=$username.':'.$domain;
3501: }
1.351 www 3502: } else {
1.988 raeburn 3503: my $key=&plaintext($role,$crstype);
1.973 bisitz 3504: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3505: if ($returnhash{$key}) {
3506: $returnhash{$key}.=','.$username.':'.$domain;
3507: } else {
3508: $returnhash{$key}=$username.':'.$domain;
3509: }
1.351 www 3510: }
1.948 raeburn 3511: }
1.400 www 3512: return %returnhash;
3513: }
3514:
3515: sub get_my_roles {
1.937 raeburn 3516: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3517: unless (defined($uname)) { $uname=$env{'user.name'}; }
3518: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3519: my (%dumphash,%nothide);
1.1086 raeburn 3520: if ($context eq 'userroles') {
3521: my $extra = &freeze_escape({'skipcheck' => 1});
3522: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3523: } else {
3524: %dumphash=
1.400 www 3525: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3526: if ($hidepriv) {
3527: my %coursehash=&coursedescription($udom.'_'.$uname);
3528: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3529: if ($user !~ /:/) {
3530: $nothide{join(':',split(/[\@]/,$user))} = 1;
3531: } else {
3532: $nothide{$user} = 1;
3533: }
3534: }
3535: }
1.858 raeburn 3536: }
1.400 www 3537: my %returnhash=();
3538: my $now=time;
1.999 raeburn 3539: my %privileged;
1.800 albertel 3540: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3541: my ($role,$tend,$tstart);
3542: if ($context eq 'userroles') {
1.1149 raeburn 3543: next if ($entry =~ /^rolesdef/);
1.867 raeburn 3544: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3545: } else {
3546: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3547: }
1.400 www 3548: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3549: my $status = 'active';
1.939 raeburn 3550: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3551: $status = 'previous';
3552: }
3553: if (($tstart) && ($now<$tstart)) {
3554: $status = 'future';
3555: }
3556: if (ref($types) eq 'ARRAY') {
3557: if (!grep(/^\Q$status\E$/,@{$types})) {
3558: next;
3559: }
3560: } else {
3561: if ($status ne 'active') {
3562: next;
3563: }
3564: }
1.867 raeburn 3565: my ($rolecode,$username,$domain,$section,$area);
3566: if ($context eq 'userroles') {
3567: ($area,$rolecode) = split(/_/,$entry);
3568: (undef,$domain,$username,$section) = split(/\//,$area);
3569: } else {
3570: ($role,$username,$domain,$section) = split(/\:/,$entry);
3571: }
1.832 raeburn 3572: if (ref($roledoms) eq 'ARRAY') {
3573: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3574: next;
3575: }
3576: }
3577: if (ref($roles) eq 'ARRAY') {
3578: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3579: if ($role =~ /^cr\//) {
3580: if (!grep(/^cr$/,@{$roles})) {
3581: next;
3582: }
1.1104 raeburn 3583: } elsif ($role =~ /^gr\//) {
3584: if (!grep(/^gr$/,@{$roles})) {
3585: next;
3586: }
1.922 raeburn 3587: } else {
3588: next;
3589: }
1.832 raeburn 3590: }
1.867 raeburn 3591: }
1.937 raeburn 3592: if ($hidepriv) {
1.999 raeburn 3593: if ($context eq 'userroles') {
3594: if ((&privileged($username,$domain)) &&
3595: (!$nothide{$username.':'.$domain})) {
3596: next;
3597: }
3598: } else {
3599: unless (ref($privileged{$domain}) eq 'HASH') {
3600: my %dompersonnel =
3601: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3602: $privileged{$domain} = {};
3603: if (keys(%dompersonnel)) {
3604: foreach my $server (keys(%dompersonnel)) {
3605: if (ref($dompersonnel{$server}) eq 'HASH') {
3606: foreach my $user (keys(%{$dompersonnel{$server}})) {
3607: my ($trole,$uname,$udom) = split(/:/,$user);
3608: $privileged{$udom}{$uname} = $trole;
3609: }
3610: }
3611: }
3612: }
3613: }
3614: if (exists($privileged{$domain}{$username})) {
3615: if (!$nothide{$username.':'.$domain}) {
3616: next;
3617: }
3618: }
1.937 raeburn 3619: }
3620: }
1.933 raeburn 3621: if ($withsec) {
3622: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3623: $tstart.':'.$tend;
3624: } else {
3625: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3626: }
1.832 raeburn 3627: }
1.373 www 3628: return %returnhash;
1.399 www 3629: }
3630:
3631: # ----------------------------------------------------- Frontpage Announcements
3632: #
3633: #
3634:
3635: sub postannounce {
3636: my ($server,$text)=@_;
1.844 albertel 3637: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3638: unless ($text=~/\w/) { $text=''; }
3639: return &reply('setannounce:'.&escape($text),$server);
3640: }
3641:
3642: sub getannounce {
1.448 albertel 3643:
3644: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3645: my $announcement='';
1.800 albertel 3646: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3647: close($fh);
1.399 www 3648: if ($announcement=~/\w/) {
3649: return
3650: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3651: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3652: } else {
3653: return '';
3654: }
3655: } else {
3656: return '';
3657: }
1.351 www 3658: }
1.353 www 3659:
3660: # ---------------------------------------------------------- Course ID routines
3661: # Deal with domain's nohist_courseid.db files
3662: #
3663:
3664: sub courseidput {
1.921 raeburn 3665: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3666: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3667: my $outcome;
3668: if ($caller eq 'timeonly') {
3669: my $cids = '';
3670: foreach my $item (keys(%$storehash)) {
3671: $cids.=&escape($item).'&';
3672: }
3673: $cids=~s/\&$//;
3674: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3675: $coursehome);
3676: } else {
3677: my $items = '';
3678: foreach my $item (keys(%$storehash)) {
3679: $items.= &escape($item).'='.
3680: &freeze_escape($$storehash{$item}).'&';
3681: }
3682: $items=~s/\&$//;
3683: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3684: $coursehome);
1.918 raeburn 3685: }
3686: if ($outcome eq 'unknown_cmd') {
3687: my $what;
3688: foreach my $cid (keys(%$storehash)) {
3689: $what .= &escape($cid).'=';
1.921 raeburn 3690: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3691: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3692: }
3693: $what =~ s/\:$/&/;
3694: }
3695: $what =~ s/\&$//;
3696: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3697: } else {
3698: return $outcome;
3699: }
1.353 www 3700: }
3701:
3702: sub courseiddump {
1.921 raeburn 3703: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3704: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3705: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3706: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3707: my $as_hash = 1;
3708: my %returnhash;
3709: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3710: my %libserv = &all_library();
3711: foreach my $tryserver (keys(%libserv)) {
3712: if ( ( $hostidflag == 1
3713: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3714: || (!defined($hostidflag)) ) {
3715:
1.918 raeburn 3716: if (($domfilter eq '') ||
3717: (&host_domain($tryserver) eq $domfilter)) {
3718: my $rep =
3719: &reply('courseiddump:'.&host_domain($tryserver).':'.
3720: $sincefilter.':'.&escape($descfilter).':'.
3721: &escape($instcodefilter).':'.&escape($ownerfilter).
3722: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3723: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3724: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3725: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3726: &escape($cc_clone).':'.$cloneonly.':'.
3727: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3728: &escape($creationcontext).':'.$domcloner,
3729: $tryserver);
1.918 raeburn 3730: my @pairs=split(/\&/,$rep);
3731: foreach my $item (@pairs) {
3732: my ($key,$value)=split(/\=/,$item,2);
3733: $key = &unescape($key);
3734: next if ($key =~ /^error: 2 /);
3735: my $result = &thaw_unescape($value);
3736: if (ref($result) eq 'HASH') {
3737: $returnhash{$key}=$result;
3738: } else {
1.921 raeburn 3739: my @responses = split(/:/,$value);
3740: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3741: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3742: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3743: }
1.1008 raeburn 3744: }
1.353 www 3745: }
3746: }
3747: }
3748: }
3749: return %returnhash;
3750: }
3751:
1.1055 raeburn 3752: sub courselastaccess {
3753: my ($cdom,$cnum,$hostidref) = @_;
3754: my %returnhash;
3755: if ($cdom && $cnum) {
3756: my $chome = &homeserver($cnum,$cdom);
3757: if ($chome ne 'no_host') {
3758: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3759: &extract_lastaccess(\%returnhash,$rep);
3760: }
3761: } else {
3762: if (!$cdom) { $cdom=''; }
3763: my %libserv = &all_library();
3764: foreach my $tryserver (keys(%libserv)) {
3765: if (ref($hostidref) eq 'ARRAY') {
3766: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3767: }
3768: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3769: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3770: &extract_lastaccess(\%returnhash,$rep);
3771: }
3772: }
3773: }
3774: return %returnhash;
3775: }
3776:
3777: sub extract_lastaccess {
3778: my ($returnhash,$rep) = @_;
3779: if (ref($returnhash) eq 'HASH') {
3780: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3781: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3782: $rep eq '') {
3783: my @pairs=split(/\&/,$rep);
3784: foreach my $item (@pairs) {
3785: my ($key,$value)=split(/\=/,$item,2);
3786: $key = &unescape($key);
3787: next if ($key =~ /^error: 2 /);
3788: $returnhash->{$key} = &thaw_unescape($value);
3789: }
3790: }
3791: }
3792: return;
3793: }
3794:
1.658 raeburn 3795: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3796:
3797: sub dcmailput {
1.685 raeburn 3798: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3799: my $status = &Apache::lonnet::critical(
1.740 www 3800: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3801: &escape($message),$server);
1.662 raeburn 3802: return $status;
3803: }
3804:
1.658 raeburn 3805: sub dcmaildump {
3806: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3807: my %returnhash=();
1.846 albertel 3808:
3809: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3810: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3811: &escape($enddate).':';
3812: my @esc_senders=map { &escape($_)} @$senders;
3813: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3814: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3815: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3816: if (($key) && ($value)) {
3817: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3818: }
3819: }
3820: }
3821: return %returnhash;
3822: }
1.662 raeburn 3823: # ---------------------------------------------------------- Domain roles
3824:
3825: sub get_domain_roles {
3826: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3827: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3828: $startdate = '.';
3829: }
1.1018 raeburn 3830: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3831: $enddate = '.';
3832: }
1.922 raeburn 3833: my $rolelist;
3834: if (ref($roles) eq 'ARRAY') {
3835: $rolelist = join(':',@{$roles});
3836: }
1.662 raeburn 3837: my %personnel = ();
1.841 albertel 3838:
3839: my %servers = &get_servers($dom,'library');
3840: foreach my $tryserver (keys(%servers)) {
3841: %{$personnel{$tryserver}}=();
3842: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3843: &escape($startdate).':'.
3844: &escape($enddate).':'.
3845: &escape($rolelist), $tryserver))) {
3846: my ($key,$value) = split(/\=/,$line,2);
3847: if (($key) && ($value)) {
3848: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3849: }
3850: }
1.662 raeburn 3851: }
3852: return %personnel;
3853: }
1.658 raeburn 3854:
1.1057 www 3855: # ----------------------------------------------------------- Interval timing
1.149 www 3856:
1.504 albertel 3857: sub get_first_access {
3858: my ($type,$argsymb)=@_;
1.790 albertel 3859: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3860: if ($argsymb) { $symb=$argsymb; }
3861: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3862: if ($type eq 'course') {
3863: $res='course';
3864: } elsif ($type eq 'map') {
1.588 albertel 3865: $res=&symbread($map);
3866: } else {
3867: $res=$symb;
3868: }
3869: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3870: return $times{"$courseid\0$res"};
1.504 albertel 3871: }
3872:
3873: sub set_first_access {
3874: my ($type)=@_;
1.790 albertel 3875: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3876: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3877: if ($type eq 'course') {
3878: $res='course';
3879: } elsif ($type eq 'map') {
1.588 albertel 3880: $res=&symbread($map);
3881: } else {
3882: $res=$symb;
3883: }
3884: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3885: if (!$firstaccess) {
1.588 albertel 3886: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3887: }
3888: return 'already_set';
1.504 albertel 3889: }
3890:
1.110 www 3891: # --------------------------------------------- Set Expire Date for Spreadsheet
3892:
3893: sub expirespread {
3894: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3895: my $cid=$env{'request.course.id'};
1.110 www 3896: if ($cid) {
3897: my $now=time;
3898: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3899: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3900: $env{'course.'.$cid.'.num'}.
1.110 www 3901: ':nohist_expirationdates:'.
3902: &escape($key).'='.$now,
1.620 albertel 3903: $env{'course.'.$cid.'.home'})
1.110 www 3904: }
3905: return 'ok';
1.14 www 3906: }
3907:
1.109 www 3908: # ----------------------------------------------------- Devalidate Spreadsheets
3909:
3910: sub devalidate {
1.325 www 3911: my ($symb,$uname,$udom)=@_;
1.620 albertel 3912: my $cid=$env{'request.course.id'};
1.109 www 3913: if ($cid) {
1.391 matthew 3914: # delete the stored spreadsheets for
3915: # - the student level sheet of this user in course's homespace
3916: # - the assessment level sheet for this resource
3917: # for this user in user's homespace
1.553 albertel 3918: # - current conditional state info
1.325 www 3919: my $key=$uname.':'.$udom.':';
1.109 www 3920: my $status=
1.299 matthew 3921: &del('nohist_calculatedsheets',
1.391 matthew 3922: [$key.'studentcalc:'],
1.620 albertel 3923: $env{'course.'.$cid.'.domain'},
3924: $env{'course.'.$cid.'.num'})
1.133 albertel 3925: .' '.
3926: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3927: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3928: unless ($status eq 'ok ok') {
3929: &logthis('Could not devalidate spreadsheet '.
1.325 www 3930: $uname.' at '.$udom.' for '.
1.109 www 3931: $symb.': '.$status);
1.133 albertel 3932: }
1.553 albertel 3933: &delenv('user.state.'.$cid);
1.109 www 3934: }
3935: }
3936:
1.265 albertel 3937: sub get_scalar {
3938: my ($string,$end) = @_;
3939: my $value;
3940: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3941: $value = $1;
3942: } elsif ($$string =~ s/^([^&]*?)&//) {
3943: $value = $1;
3944: }
3945: return &unescape($value);
3946: }
3947:
3948: sub array2str {
3949: my (@array) = @_;
3950: my $result=&arrayref2str(\@array);
3951: $result=~s/^__ARRAY_REF__//;
3952: $result=~s/__END_ARRAY_REF__$//;
3953: return $result;
3954: }
3955:
1.204 albertel 3956: sub arrayref2str {
3957: my ($arrayref) = @_;
1.265 albertel 3958: my $result='__ARRAY_REF__';
1.204 albertel 3959: foreach my $elem (@$arrayref) {
1.265 albertel 3960: if(ref($elem) eq 'ARRAY') {
3961: $result.=&arrayref2str($elem).'&';
3962: } elsif(ref($elem) eq 'HASH') {
3963: $result.=&hashref2str($elem).'&';
3964: } elsif(ref($elem)) {
3965: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3966: } else {
3967: $result.=&escape($elem).'&';
3968: }
3969: }
3970: $result=~s/\&$//;
1.265 albertel 3971: $result .= '__END_ARRAY_REF__';
1.204 albertel 3972: return $result;
3973: }
3974:
1.168 albertel 3975: sub hash2str {
1.204 albertel 3976: my (%hash) = @_;
3977: my $result=&hashref2str(\%hash);
1.265 albertel 3978: $result=~s/^__HASH_REF__//;
3979: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3980: return $result;
3981: }
3982:
3983: sub hashref2str {
3984: my ($hashref)=@_;
1.265 albertel 3985: my $result='__HASH_REF__';
1.800 albertel 3986: foreach my $key (sort(keys(%$hashref))) {
3987: if (ref($key) eq 'ARRAY') {
3988: $result.=&arrayref2str($key).'=';
3989: } elsif (ref($key) eq 'HASH') {
3990: $result.=&hashref2str($key).'=';
3991: } elsif (ref($key)) {
1.265 albertel 3992: $result.='=';
1.800 albertel 3993: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3994: } else {
1.1132 raeburn 3995: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3996: }
3997:
1.800 albertel 3998: if(ref($hashref->{$key}) eq 'ARRAY') {
3999: $result.=&arrayref2str($hashref->{$key}).'&';
4000: } elsif(ref($hashref->{$key}) eq 'HASH') {
4001: $result.=&hashref2str($hashref->{$key}).'&';
4002: } elsif(ref($hashref->{$key})) {
1.265 albertel 4003: $result.='&';
1.800 albertel 4004: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4005: } else {
1.800 albertel 4006: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4007: }
4008: }
1.168 albertel 4009: $result=~s/\&$//;
1.265 albertel 4010: $result .= '__END_HASH_REF__';
1.168 albertel 4011: return $result;
4012: }
4013:
4014: sub str2hash {
1.265 albertel 4015: my ($string)=@_;
4016: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4017: return %$hash;
4018: }
4019:
4020: sub str2hashref {
1.168 albertel 4021: my ($string) = @_;
1.265 albertel 4022:
4023: my %hash;
4024:
4025: if($string !~ /^__HASH_REF__/) {
4026: if (! ($string eq '' || !defined($string))) {
4027: $hash{'error'}='Not hash reference';
4028: }
4029: return (\%hash, $string);
4030: }
4031:
4032: $string =~ s/^__HASH_REF__//;
4033:
4034: while($string !~ /^__END_HASH_REF__/) {
4035: #key
4036: my $key='';
4037: if($string =~ /^__HASH_REF__/) {
4038: ($key, $string)=&str2hashref($string);
4039: if(defined($key->{'error'})) {
4040: $hash{'error'}='Bad data';
4041: return (\%hash, $string);
4042: }
4043: } elsif($string =~ /^__ARRAY_REF__/) {
4044: ($key, $string)=&str2arrayref($string);
4045: if($key->[0] eq 'Array reference error') {
4046: $hash{'error'}='Bad data';
4047: return (\%hash, $string);
4048: }
4049: } else {
4050: $string =~ s/^(.*?)=//;
1.267 albertel 4051: $key=&unescape($1);
1.265 albertel 4052: }
4053: $string =~ s/^=//;
4054:
4055: #value
4056: my $value='';
4057: if($string =~ /^__HASH_REF__/) {
4058: ($value, $string)=&str2hashref($string);
4059: if(defined($value->{'error'})) {
4060: $hash{'error'}='Bad data';
4061: return (\%hash, $string);
4062: }
4063: } elsif($string =~ /^__ARRAY_REF__/) {
4064: ($value, $string)=&str2arrayref($string);
4065: if($value->[0] eq 'Array reference error') {
4066: $hash{'error'}='Bad data';
4067: return (\%hash, $string);
4068: }
4069: } else {
4070: $value=&get_scalar(\$string,'__END_HASH_REF__');
4071: }
4072: $string =~ s/^&//;
4073:
4074: $hash{$key}=$value;
1.204 albertel 4075: }
1.265 albertel 4076:
4077: $string =~ s/^__END_HASH_REF__//;
4078:
4079: return (\%hash, $string);
1.204 albertel 4080: }
4081:
4082: sub str2array {
1.265 albertel 4083: my ($string)=@_;
4084: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4085: return @$array;
4086: }
4087:
4088: sub str2arrayref {
1.204 albertel 4089: my ($string) = @_;
1.265 albertel 4090: my @array;
4091:
4092: if($string !~ /^__ARRAY_REF__/) {
4093: if (! ($string eq '' || !defined($string))) {
4094: $array[0]='Array reference error';
4095: }
4096: return (\@array, $string);
4097: }
4098:
4099: $string =~ s/^__ARRAY_REF__//;
4100:
4101: while($string !~ /^__END_ARRAY_REF__/) {
4102: my $value='';
4103: if($string =~ /^__HASH_REF__/) {
4104: ($value, $string)=&str2hashref($string);
4105: if(defined($value->{'error'})) {
4106: $array[0] ='Array reference error';
4107: return (\@array, $string);
4108: }
4109: } elsif($string =~ /^__ARRAY_REF__/) {
4110: ($value, $string)=&str2arrayref($string);
4111: if($value->[0] eq 'Array reference error') {
4112: $array[0] ='Array reference error';
4113: return (\@array, $string);
4114: }
4115: } else {
4116: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4117: }
4118: $string =~ s/^&//;
4119:
4120: push(@array, $value);
1.191 harris41 4121: }
1.265 albertel 4122:
4123: $string =~ s/^__END_ARRAY_REF__//;
4124:
4125: return (\@array, $string);
1.168 albertel 4126: }
4127:
1.167 albertel 4128: # -------------------------------------------------------------------Temp Store
4129:
1.168 albertel 4130: sub tmpreset {
4131: my ($symb,$namespace,$domain,$stuname) = @_;
4132: if (!$symb) {
4133: $symb=&symbread();
1.620 albertel 4134: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4135: }
4136: $symb=escape($symb);
4137:
1.620 albertel 4138: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4139: $namespace=~s/\//\_/g;
4140: $namespace=~s/\W//g;
4141:
1.620 albertel 4142: if (!$domain) { $domain=$env{'user.domain'}; }
4143: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4144: if ($domain eq 'public' && $stuname eq 'public') {
4145: $stuname=$ENV{'REMOTE_ADDR'};
4146: }
1.1117 foxr 4147: my $path=LONCAPA::tempdir();
1.168 albertel 4148: my %hash;
4149: if (tie(%hash,'GDBM_File',
4150: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4151: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4152: foreach my $key (keys(%hash)) {
1.180 albertel 4153: if ($key=~ /:$symb/) {
1.168 albertel 4154: delete($hash{$key});
4155: }
4156: }
4157: }
4158: }
4159:
1.167 albertel 4160: sub tmpstore {
1.168 albertel 4161: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4162:
4163: if (!$symb) {
4164: $symb=&symbread();
1.620 albertel 4165: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4166: }
4167: $symb=escape($symb);
4168:
4169: if (!$namespace) {
4170: # I don't think we would ever want to store this for a course.
4171: # it seems this will only be used if we don't have a course.
1.620 albertel 4172: #$namespace=$env{'request.course.id'};
1.168 albertel 4173: #if (!$namespace) {
1.620 albertel 4174: $namespace=$env{'request.state'};
1.168 albertel 4175: #}
4176: }
4177: $namespace=~s/\//\_/g;
4178: $namespace=~s/\W//g;
1.620 albertel 4179: if (!$domain) { $domain=$env{'user.domain'}; }
4180: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4181: if ($domain eq 'public' && $stuname eq 'public') {
4182: $stuname=$ENV{'REMOTE_ADDR'};
4183: }
1.168 albertel 4184: my $now=time;
4185: my %hash;
1.1117 foxr 4186: my $path=LONCAPA::tempdir();
1.168 albertel 4187: if (tie(%hash,'GDBM_File',
4188: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4189: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4190: $hash{"version:$symb"}++;
4191: my $version=$hash{"version:$symb"};
4192: my $allkeys='';
4193: foreach my $key (keys(%$storehash)) {
4194: $allkeys.=$key.':';
1.591 albertel 4195: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4196: }
4197: $hash{"$version:$symb:timestamp"}=$now;
4198: $allkeys.='timestamp';
4199: $hash{"$version:keys:$symb"}=$allkeys;
4200: if (untie(%hash)) {
4201: return 'ok';
4202: } else {
4203: return "error:$!";
4204: }
4205: } else {
4206: return "error:$!";
4207: }
4208: }
1.167 albertel 4209:
1.168 albertel 4210: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4211:
1.168 albertel 4212: sub tmprestore {
4213: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4214:
1.168 albertel 4215: if (!$symb) {
4216: $symb=&symbread();
1.620 albertel 4217: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4218: }
4219: $symb=escape($symb);
4220:
1.620 albertel 4221: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4222:
1.620 albertel 4223: if (!$domain) { $domain=$env{'user.domain'}; }
4224: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4225: if ($domain eq 'public' && $stuname eq 'public') {
4226: $stuname=$ENV{'REMOTE_ADDR'};
4227: }
1.168 albertel 4228: my %returnhash;
4229: $namespace=~s/\//\_/g;
4230: $namespace=~s/\W//g;
4231: my %hash;
1.1117 foxr 4232: my $path=LONCAPA::tempdir();
1.168 albertel 4233: if (tie(%hash,'GDBM_File',
4234: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4235: &GDBM_READER(),0640)) {
1.168 albertel 4236: my $version=$hash{"version:$symb"};
4237: $returnhash{'version'}=$version;
4238: my $scope;
4239: for ($scope=1;$scope<=$version;$scope++) {
4240: my $vkeys=$hash{"$scope:keys:$symb"};
4241: my @keys=split(/:/,$vkeys);
4242: my $key;
4243: $returnhash{"$scope:keys"}=$vkeys;
4244: foreach $key (@keys) {
1.591 albertel 4245: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4246: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4247: }
4248: }
1.168 albertel 4249: if (!(untie(%hash))) {
4250: return "error:$!";
4251: }
4252: } else {
4253: return "error:$!";
4254: }
4255: return %returnhash;
1.167 albertel 4256: }
4257:
1.9 www 4258: # ----------------------------------------------------------------------- Store
4259:
4260: sub store {
1.124 www 4261: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4262: my $home='';
4263:
1.168 albertel 4264: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4265:
1.213 www 4266: $symb=&symbclean($symb);
1.122 albertel 4267: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4268:
1.620 albertel 4269: if (!$domain) { $domain=$env{'user.domain'}; }
4270: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4271:
4272: &devalidate($symb,$stuname,$domain);
1.109 www 4273:
4274: $symb=escape($symb);
1.187 www 4275: if (!$namespace) {
1.620 albertel 4276: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4277: return '';
4278: }
4279: }
1.620 albertel 4280: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4281:
4282: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4283: $$storehash{'host'}=$perlvar{'lonHostID'};
4284:
1.12 www 4285: my $namevalue='';
1.800 albertel 4286: foreach my $key (keys(%$storehash)) {
4287: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4288: }
1.12 www 4289: $namevalue=~s/\&$//;
1.187 www 4290: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4291: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4292: }
4293:
1.47 www 4294: # -------------------------------------------------------------- Critical Store
4295:
4296: sub cstore {
1.124 www 4297: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4298: my $home='';
4299:
1.168 albertel 4300: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4301:
1.213 www 4302: $symb=&symbclean($symb);
1.122 albertel 4303: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4304:
1.620 albertel 4305: if (!$domain) { $domain=$env{'user.domain'}; }
4306: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4307:
4308: &devalidate($symb,$stuname,$domain);
1.109 www 4309:
4310: $symb=escape($symb);
1.187 www 4311: if (!$namespace) {
1.620 albertel 4312: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4313: return '';
4314: }
4315: }
1.620 albertel 4316: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4317:
4318: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4319: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4320:
1.47 www 4321: my $namevalue='';
1.800 albertel 4322: foreach my $key (keys(%$storehash)) {
4323: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4324: }
1.47 www 4325: $namevalue=~s/\&$//;
1.187 www 4326: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4327: return critical
4328: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4329: }
4330:
1.9 www 4331: # --------------------------------------------------------------------- Restore
4332:
4333: sub restore {
1.124 www 4334: my ($symb,$namespace,$domain,$stuname) = @_;
4335: my $home='';
4336:
1.168 albertel 4337: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4338:
1.122 albertel 4339: if (!$symb) {
4340: unless ($symb=escape(&symbread())) { return ''; }
4341: } else {
1.213 www 4342: $symb=&escape(&symbclean($symb));
1.122 albertel 4343: }
1.188 www 4344: if (!$namespace) {
1.620 albertel 4345: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4346: return '';
4347: }
4348: }
1.620 albertel 4349: if (!$domain) { $domain=$env{'user.domain'}; }
4350: if (!$stuname) { $stuname=$env{'user.name'}; }
4351: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4352: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4353:
1.12 www 4354: my %returnhash=();
1.800 albertel 4355: foreach my $line (split(/\&/,$answer)) {
4356: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4357: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4358: }
1.75 www 4359: my $version;
4360: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4361: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4362: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4363: }
1.75 www 4364: }
1.13 www 4365: return %returnhash;
1.34 www 4366: }
4367:
4368: # ---------------------------------------------------------- Course Description
1.1118 foxr 4369: #
4370: #
1.34 www 4371:
4372: sub coursedescription {
1.731 albertel 4373: my ($courseid,$args)=@_;
1.34 www 4374: $courseid=~s/^\///;
1.49 www 4375: $courseid=~s/\_/\//g;
1.34 www 4376: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4377: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4378: my $normalid=$cdomain.'_'.$cnum;
4379: # need to always cache even if we get errors otherwise we keep
4380: # trying and trying and trying to get the course description.
4381: my %envhash=();
4382: my %returnhash=();
1.731 albertel 4383:
4384: my $expiretime=600;
4385: if ($env{'request.course.id'} eq $normalid) {
4386: $expiretime=120;
4387: }
4388:
4389: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4390: if (!$args->{'freshen_cache'}
4391: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4392: foreach my $key (keys(%env)) {
4393: next if ($key !~ /^\Q$prefix\E(.*)/);
4394: my ($setting) = $1;
4395: $returnhash{$setting} = $env{$key};
4396: }
4397: return %returnhash;
4398: }
4399:
1.1118 foxr 4400: # get the data again
4401:
1.731 albertel 4402: if (!$args->{'one_time'}) {
4403: $envhash{'course.'.$normalid.'.last_cache'}=time;
4404: }
1.811 albertel 4405:
1.34 www 4406: if ($chome ne 'no_host') {
1.302 albertel 4407: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4408: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4409: my $username = $env{'user.name'}; # Defult username
4410: if(defined $args->{'user'}) {
4411: $username = $args->{'user'};
4412: }
1.129 albertel 4413: $returnhash{'home'}= $chome;
4414: $returnhash{'domain'} = $cdomain;
4415: $returnhash{'num'} = $cnum;
1.741 raeburn 4416: if (!defined($returnhash{'type'})) {
4417: $returnhash{'type'} = 'Course';
4418: }
1.130 albertel 4419: while (my ($name,$value) = each %returnhash) {
1.53 www 4420: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4421: }
1.270 www 4422: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4423: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4424: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4425: $envhash{'course.'.$normalid.'.home'}=$chome;
4426: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4427: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4428: }
4429: }
1.731 albertel 4430: if (!$args->{'one_time'}) {
1.949 raeburn 4431: &appenv(\%envhash);
1.731 albertel 4432: }
1.302 albertel 4433: return %returnhash;
1.461 www 4434: }
4435:
1.1080 raeburn 4436: sub update_released_required {
4437: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4438: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4439: $cid = $env{'request.course.id'};
4440: $cdom = $env{'course.'.$cid.'.domain'};
4441: $cnum = $env{'course.'.$cid.'.num'};
4442: $chome = $env{'course.'.$cid.'.home'};
4443: }
4444: if ($needsrelease) {
4445: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4446: my $needsupdate;
4447: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4448: $needsupdate = 1;
4449: } else {
4450: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4451: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4452: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4453: $needsupdate = 1;
4454: }
4455: }
4456: if ($needsupdate) {
4457: my %needshash = (
4458: 'internal.releaserequired' => $needsrelease,
4459: );
4460: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4461: if ($putresult eq 'ok') {
4462: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4463: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4464: if (ref($crsinfo{$cid}) eq 'HASH') {
4465: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4466: &courseidput($cdom,\%crsinfo,$chome,'notime');
4467: }
4468: }
4469: }
4470: }
4471: return;
4472: }
4473:
1.461 www 4474: # -------------------------------------------------See if a user is privileged
4475:
4476: sub privileged {
4477: my ($username,$domain)=@_;
4478: my $rolesdump=&reply("dump:$domain:$username:roles",
4479: &homeserver($username,$domain));
1.1033 raeburn 4480: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4481: ($rolesdump =~ /^error:/)) {
4482: return 0;
4483: }
1.461 www 4484: my $now=time;
4485: if ($rolesdump ne '') {
1.800 albertel 4486: foreach my $entry (split(/&/,$rolesdump)) {
4487: if ($entry!~/^rolesdef_/) {
4488: my ($area,$role)=split(/=/,$entry);
1.461 www 4489: $area=~s/\_\w\w$//;
4490: my ($trole,$tend,$tstart)=split(/_/,$role);
4491: if (($trole eq 'dc') || ($trole eq 'su')) {
4492: my $active=1;
4493: if ($tend) {
4494: if ($tend<$now) { $active=0; }
4495: }
4496: if ($tstart) {
4497: if ($tstart>$now) { $active=0; }
4498: }
4499: if ($active) { return 1; }
4500: }
4501: }
4502: }
4503: }
4504: return 0;
1.9 www 4505: }
1.1 albertel 4506:
1.103 harris41 4507: # -------------------------------------------------------- Get user privileges
1.11 www 4508:
4509: sub rolesinit {
4510: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4511: my $now=time;
4512: my %userroles = ('user.login.time' => $now);
1.1086 raeburn 4513: my $extra = &freeze_escape({'skipcheck' => 1});
1.1078 raeburn 4514: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4515: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1078 raeburn 4516: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4517: return \%userroles;
4518: }
1.11 www 4519: my %allroles=();
1.678 raeburn 4520: my %allgroups=();
1.11 www 4521:
4522: if ($rolesdump ne '') {
1.800 albertel 4523: foreach my $entry (split(/&/,$rolesdump)) {
4524: if ($entry!~/^rolesdef_/) {
4525: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4526: $area=~s/\_\w\w$//;
1.678 raeburn 4527: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4528: if ($role=~/^cr/) {
1.807 albertel 4529: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4530: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4531: ($tend,$tstart)=split('_',$trest);
4532: } else {
4533: $trole=$role;
4534: }
1.678 raeburn 4535: } elsif ($role =~ m|^gr/|) {
4536: ($trole,$tend,$tstart) = split(/_/,$role);
1.1104 raeburn 4537: next if ($tstart eq '-1');
1.678 raeburn 4538: ($trole,$group_privs) = split(/\//,$trole);
4539: $group_privs = &unescape($group_privs);
1.587 albertel 4540: } else {
4541: ($trole,$tend,$tstart)=split(/_/,$role);
4542: }
1.743 albertel 4543: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4544: $username);
4545: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4546: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4547: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4548: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4549: my $spec=$trole.'.'.$area;
4550: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4551: if ($trole =~ /^cr\//) {
1.567 raeburn 4552: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4553: } elsif ($trole eq 'gr') {
4554: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4555: } else {
1.567 raeburn 4556: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4557: }
1.12 www 4558: }
1.662 raeburn 4559: }
1.191 harris41 4560: }
1.743 albertel 4561: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4562: $userroles{'user.adv'} = $adv;
4563: $userroles{'user.author'} = $author;
1.620 albertel 4564: $env{'user.adv'}=$adv;
1.11 www 4565: }
1.743 albertel 4566: return \%userroles;
1.11 www 4567: }
4568:
1.567 raeburn 4569: sub set_arearole {
4570: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4571: # log the associated role with the area
4572: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4573: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4574: }
4575:
4576: sub custom_roleprivs {
4577: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4578: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4579: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4580: if (&hostname($homsvr) ne '') {
1.567 raeburn 4581: my ($rdummy,$roledef)=
4582: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4583: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4584: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4585: if (defined($syspriv)) {
1.1043 raeburn 4586: if ($trest =~ /^$match_community$/) {
4587: $syspriv =~ s/bre\&S//;
4588: }
1.567 raeburn 4589: $$allroles{'cm./'}.=':'.$syspriv;
4590: $$allroles{$spec.'./'}.=':'.$syspriv;
4591: }
4592: if ($tdomain ne '') {
4593: if (defined($dompriv)) {
4594: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4595: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4596: }
4597: if (($trest ne '') && (defined($coursepriv))) {
4598: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4599: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4600: }
4601: }
4602: }
4603: }
4604: }
4605:
1.678 raeburn 4606: sub group_roleprivs {
4607: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4608: my $access = 1;
4609: my $now = time;
4610: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4611: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4612: if ($access) {
1.811 albertel 4613: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4614: $$allgroups{$course}{$group} .=':'.$group_privs;
4615: }
4616: }
1.567 raeburn 4617:
4618: sub standard_roleprivs {
4619: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4620: if (defined($pr{$trole.':s'})) {
4621: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4622: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4623: }
4624: if ($tdomain ne '') {
4625: if (defined($pr{$trole.':d'})) {
4626: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4627: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4628: }
4629: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4630: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4631: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4632: }
4633: }
4634: }
4635:
4636: sub set_userprivs {
1.1064 raeburn 4637: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4638: my $author=0;
4639: my $adv=0;
1.678 raeburn 4640: my %grouproles = ();
4641: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4642: my @groupkeys;
1.1000 raeburn 4643: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4644: push(@groupkeys,$role);
4645: }
4646: if (ref($groups_roles) eq 'HASH') {
4647: foreach my $key (keys(%{$groups_roles})) {
4648: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4649: push(@groupkeys,$key);
4650: }
4651: }
4652: }
4653: if (@groupkeys > 0) {
4654: foreach my $role (@groupkeys) {
4655: my ($trole,$area,$sec,$extendedarea);
4656: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4657: $trole = $1;
4658: $area = $2;
4659: $sec = $3;
4660: $extendedarea = $area.$sec;
4661: if (exists($$allgroups{$area})) {
4662: foreach my $group (keys(%{$$allgroups{$area}})) {
4663: my $spec = $trole.'.'.$extendedarea;
4664: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4665: $$allgroups{$area}{$group};
1.1064 raeburn 4666: }
1.678 raeburn 4667: }
4668: }
4669: }
4670: }
4671: }
1.800 albertel 4672: foreach my $group (keys(%grouproles)) {
4673: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4674: }
1.800 albertel 4675: foreach my $role (keys(%{$allroles})) {
4676: my %thesepriv;
1.941 raeburn 4677: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4678: foreach my $item (split(/:/,$$allroles{$role})) {
4679: if ($item ne '') {
4680: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4681: if ($restrictions eq '') {
4682: $thesepriv{$privilege}='F';
4683: } elsif ($thesepriv{$privilege} ne 'F') {
4684: $thesepriv{$privilege}.=$restrictions;
4685: }
4686: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4687: }
4688: }
4689: my $thesestr='';
1.1104 raeburn 4690: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 4691: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4692: }
4693: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4694: }
4695: return ($author,$adv);
4696: }
4697:
1.994 raeburn 4698: sub role_status {
1.1104 raeburn 4699: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4700: my @pwhere = ();
4701: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4702: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4703: unless (!defined($$role) || $$role eq '') {
4704: $$where=join('.',@pwhere);
4705: $$trolecode=$$role.'.'.$$where;
4706: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4707: $$tstatus='is';
1.1104 raeburn 4708: if ($$tstart && $$tstart>$update) {
1.994 raeburn 4709: $$tstatus='future';
1.1034 raeburn 4710: if ($$tstart<$now) {
4711: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4712: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4713: my (%allroles,%allgroups,$group_privs,
4714: %groups_roles,@rolecodes);
1.1002 raeburn 4715: my %userroles = (
4716: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4717: );
1.1064 raeburn 4718: @rolecodes = ('cm');
1.1002 raeburn 4719: my $spec=$$role.'.'.$$where;
4720: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4721: if ($$role =~ /^cr\//) {
4722: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4723: push(@rolecodes,'cr');
1.1002 raeburn 4724: } elsif ($$role eq 'gr') {
1.1064 raeburn 4725: push(@rolecodes,$$role);
1.1002 raeburn 4726: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4727: $env{'user.name'});
1.1064 raeburn 4728: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4729: (undef,my $group_privs) = split(/\//,$trole);
4730: $group_privs = &unescape($group_privs);
4731: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4732: 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 4733: &get_groups_roles($tdomain,$trest,
4734: \%course_roles,\@rolecodes,
4735: \%groups_roles);
1.1002 raeburn 4736: } else {
1.1064 raeburn 4737: push(@rolecodes,$$role);
1.1002 raeburn 4738: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4739: }
1.1064 raeburn 4740: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4741: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4742: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4743: }
4744: }
1.1034 raeburn 4745: $$tstatus = 'is';
1.1002 raeburn 4746: }
1.994 raeburn 4747: }
4748: if ($$tend) {
1.1104 raeburn 4749: if ($$tend<$update) {
1.994 raeburn 4750: $$tstatus='expired';
4751: } elsif ($$tend<$now) {
4752: $$tstatus='will_not';
4753: }
4754: }
4755: }
4756: }
4757: }
4758:
1.1104 raeburn 4759: sub get_groups_roles {
4760: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4761: return unless((ref($cdom_courseroles) eq 'HASH') &&
4762: (ref($rolecodes) eq 'ARRAY') &&
4763: (ref($groups_roles) eq 'HASH'));
4764: if (keys(%{$cdom_courseroles}) > 0) {
4765: my ($cnum) = ($rest =~ /^($match_courseid)/);
4766: if ($cdom ne '' && $cnum ne '') {
4767: foreach my $key (keys(%{$cdom_courseroles})) {
4768: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4769: my $crsrole = $1;
4770: my $crssec = $2;
4771: if ($crsrole =~ /^cr/) {
4772: unless (grep(/^cr$/,@{$rolecodes})) {
4773: push(@{$rolecodes},'cr');
4774: }
4775: } else {
4776: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4777: push(@{$rolecodes},$crsrole);
4778: }
4779: }
4780: my $rolekey = "$crsrole./$cdom/$cnum";
4781: if ($crssec ne '') {
4782: $rolekey .= "/$crssec";
4783: }
4784: $rolekey .= './';
4785: $groups_roles->{$rolekey} = $rolecodes;
4786: }
4787: }
4788: }
4789: }
4790: return;
4791: }
4792:
4793: sub delete_env_groupprivs {
4794: my ($where,$courseroles,$possroles) = @_;
4795: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4796: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4797: unless (ref($courseroles->{$udom}) eq 'HASH') {
4798: %{$courseroles->{$udom}} =
4799: &get_my_roles('','','userroles',['active'],
4800: $possroles,[$udom],1);
4801: }
4802: if (ref($courseroles->{$udom}) eq 'HASH') {
4803: foreach my $item (keys(%{$courseroles->{$udom}})) {
4804: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4805: my $area = '/'.$cdom.'/'.$cnum;
4806: my $privkey = "user.priv.$crsrole.$area";
4807: if ($crssec ne '') {
4808: $privkey .= '/'.$crssec;
4809: }
4810: $privkey .= ".$area/$group";
4811: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4812: }
4813: }
4814: return;
4815: }
4816:
1.994 raeburn 4817: sub check_adhoc_privs {
1.1104 raeburn 4818: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4819: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4820: if ($env{$cckey}) {
4821: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 4822: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4823: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 4824: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4825: }
4826: } else {
1.1088 raeburn 4827: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4828: }
4829: }
4830:
4831: sub set_adhoc_privileges {
4832: # role can be cc or ca
1.1088 raeburn 4833: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4834: my $area = '/'.$dcdom.'/'.$pickedcourse;
4835: my $spec = $role.'.'.$area;
4836: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4837: $env{'user.name'});
4838: my %ccrole = ();
4839: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4840: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4841: &appenv(\%userroles,[$role,'cm']);
4842: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 4843: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4844: &appenv( {'request.role' => $spec,
4845: 'request.role.domain' => $dcdom,
4846: 'request.course.sec' => ''
4847: }
4848: );
4849: my $tadv=0;
4850: if (&allowed('adv') eq 'F') { $tadv=1; }
4851: &appenv({'request.role.adv' => $tadv});
4852: }
1.994 raeburn 4853: }
4854:
1.12 www 4855: # --------------------------------------------------------------- get interface
4856:
4857: sub get {
1.131 albertel 4858: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4859: my $items='';
1.800 albertel 4860: foreach my $item (@$storearr) {
4861: $items.=&escape($item).'&';
1.191 harris41 4862: }
1.12 www 4863: $items=~s/\&$//;
1.620 albertel 4864: if (!$udomain) { $udomain=$env{'user.domain'}; }
4865: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4866: my $uhome=&homeserver($uname,$udomain);
4867:
1.133 albertel 4868: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4869: my @pairs=split(/\&/,$rep);
1.273 albertel 4870: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4871: return @pairs;
4872: }
1.15 www 4873: my %returnhash=();
1.42 www 4874: my $i=0;
1.800 albertel 4875: foreach my $item (@$storearr) {
4876: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4877: $i++;
1.191 harris41 4878: }
1.15 www 4879: return %returnhash;
1.27 www 4880: }
4881:
4882: # --------------------------------------------------------------- del interface
4883:
4884: sub del {
1.133 albertel 4885: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4886: my $items='';
1.800 albertel 4887: foreach my $item (@$storearr) {
4888: $items.=&escape($item).'&';
1.191 harris41 4889: }
1.984 neumanie 4890:
1.27 www 4891: $items=~s/\&$//;
1.620 albertel 4892: if (!$udomain) { $udomain=$env{'user.domain'}; }
4893: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4894: my $uhome=&homeserver($uname,$udomain);
4895: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4896: }
4897:
4898: # -------------------------------------------------------------- dump interface
4899:
4900: sub dump {
1.1086 raeburn 4901: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4902: if (!$udomain) { $udomain=$env{'user.domain'}; }
4903: if (!$uname) { $uname=$env{'user.name'}; }
4904: my $uhome=&homeserver($uname,$udomain);
4905: if ($regexp) {
4906: $regexp=&escape($regexp);
4907: } else {
4908: $regexp='.';
4909: }
1.1086 raeburn 4910: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4911: my @pairs=split(/\&/,$rep);
4912: my %returnhash=();
1.1098 foxr 4913: if (!($rep =~ /^error/ )) {
4914: foreach my $item (@pairs) {
4915: my ($key,$value)=split(/=/,$item,2);
4916: $key = &unescape($key);
4917: next if ($key =~ /^error: 2 /);
4918: $returnhash{$key}=&thaw_unescape($value);
4919: }
1.755 albertel 4920: }
4921: return %returnhash;
1.407 www 4922: }
4923:
1.1098 foxr 4924:
1.717 albertel 4925: # --------------------------------------------------------- dumpstore interface
4926:
4927: sub dumpstore {
4928: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4929: if (!$udomain) { $udomain=$env{'user.domain'}; }
4930: if (!$uname) { $uname=$env{'user.name'}; }
4931: my $uhome=&homeserver($uname,$udomain);
4932: if ($regexp) {
4933: $regexp=&escape($regexp);
4934: } else {
4935: $regexp='.';
4936: }
4937: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4938: my @pairs=split(/\&/,$rep);
4939: my %returnhash=();
4940: foreach my $item (@pairs) {
4941: my ($key,$value)=split(/=/,$item,2);
4942: next if ($key =~ /^error: 2 /);
4943: $returnhash{$key}=&thaw_unescape($value);
4944: }
4945: return %returnhash;
1.717 albertel 4946: }
4947:
1.407 www 4948: # -------------------------------------------------------------- keys interface
4949:
4950: sub getkeys {
4951: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4952: if (!$udomain) { $udomain=$env{'user.domain'}; }
4953: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4954: my $uhome=&homeserver($uname,$udomain);
4955: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4956: my @keyarray=();
1.800 albertel 4957: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4958: next if ($key =~ /^error: 2 /);
1.800 albertel 4959: push(@keyarray,&unescape($key));
1.407 www 4960: }
4961: return @keyarray;
1.318 matthew 4962: }
4963:
1.319 matthew 4964: # --------------------------------------------------------------- currentdump
4965: sub currentdump {
1.328 matthew 4966: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4967: $courseid = $env{'request.course.id'} if (! defined($courseid));
4968: $sdom = $env{'user.domain'} if (! defined($sdom));
4969: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4970: my $uhome = &homeserver($sname,$sdom);
4971: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4972: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4973: #
1.318 matthew 4974: my %returnhash=();
1.319 matthew 4975: #
4976: if ($rep eq "unknown_cmd") {
4977: # an old lond will not know currentdump
4978: # Do a dump and make it look like a currentdump
1.822 albertel 4979: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4980: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4981: my %hash = @tmp;
4982: @tmp=();
1.424 matthew 4983: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4984: } else {
4985: my @pairs=split(/\&/,$rep);
1.800 albertel 4986: foreach my $pair (@pairs) {
4987: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4988: my ($symb,$param) = split(/:/,$key);
4989: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4990: &thaw_unescape($value);
1.319 matthew 4991: }
1.191 harris41 4992: }
1.12 www 4993: return %returnhash;
1.424 matthew 4994: }
4995:
4996: sub convert_dump_to_currentdump{
4997: my %hash = %{shift()};
4998: my %returnhash;
4999: # Code ripped from lond, essentially. The only difference
5000: # here is the unescaping done by lonnet::dump(). Conceivably
5001: # we might run in to problems with parameter names =~ /^v\./
5002: while (my ($key,$value) = each(%hash)) {
5003: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5004: $symb = &unescape($symb);
5005: $param = &unescape($param);
1.424 matthew 5006: next if ($v eq 'version' || $symb eq 'keys');
5007: next if (exists($returnhash{$symb}) &&
5008: exists($returnhash{$symb}->{$param}) &&
5009: $returnhash{$symb}->{'v.'.$param} > $v);
5010: $returnhash{$symb}->{$param}=$value;
5011: $returnhash{$symb}->{'v.'.$param}=$v;
5012: }
5013: #
5014: # Remove all of the keys in the hashes which keep track of
5015: # the version of the parameter.
5016: while (my ($symb,$param_hash) = each(%returnhash)) {
5017: # use a foreach because we are going to delete from the hash.
5018: foreach my $key (keys(%$param_hash)) {
5019: delete($param_hash->{$key}) if ($key =~ /^v\./);
5020: }
5021: }
5022: return \%returnhash;
1.12 www 5023: }
5024:
1.627 albertel 5025: # ------------------------------------------------------ critical inc interface
5026:
5027: sub cinc {
5028: return &inc(@_,'critical');
5029: }
5030:
1.449 matthew 5031: # --------------------------------------------------------------- inc interface
5032:
5033: sub inc {
1.627 albertel 5034: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5035: if (!$udomain) { $udomain=$env{'user.domain'}; }
5036: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5037: my $uhome=&homeserver($uname,$udomain);
5038: my $items='';
5039: if (! ref($store)) {
5040: # got a single value, so use that instead
5041: $items = &escape($store).'=&';
5042: } elsif (ref($store) eq 'SCALAR') {
5043: $items = &escape($$store).'=&';
5044: } elsif (ref($store) eq 'ARRAY') {
5045: $items = join('=&',map {&escape($_);} @{$store});
5046: } elsif (ref($store) eq 'HASH') {
5047: while (my($key,$value) = each(%{$store})) {
5048: $items.= &escape($key).'='.&escape($value).'&';
5049: }
5050: }
5051: $items=~s/\&$//;
1.627 albertel 5052: if ($critical) {
5053: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5054: } else {
5055: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5056: }
1.449 matthew 5057: }
5058:
1.12 www 5059: # --------------------------------------------------------------- put interface
5060:
5061: sub put {
1.134 albertel 5062: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5063: if (!$udomain) { $udomain=$env{'user.domain'}; }
5064: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5065: my $uhome=&homeserver($uname,$udomain);
1.12 www 5066: my $items='';
1.800 albertel 5067: foreach my $item (keys(%$storehash)) {
5068: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5069: }
1.12 www 5070: $items=~s/\&$//;
1.134 albertel 5071: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5072: }
5073:
1.631 albertel 5074: # ------------------------------------------------------------ newput interface
5075:
5076: sub newput {
5077: my ($namespace,$storehash,$udomain,$uname)=@_;
5078: if (!$udomain) { $udomain=$env{'user.domain'}; }
5079: if (!$uname) { $uname=$env{'user.name'}; }
5080: my $uhome=&homeserver($uname,$udomain);
5081: my $items='';
5082: foreach my $key (keys(%$storehash)) {
5083: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5084: }
5085: $items=~s/\&$//;
5086: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5087: }
5088:
5089: # --------------------------------------------------------- putstore interface
5090:
1.524 raeburn 5091: sub putstore {
1.715 albertel 5092: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5093: if (!$udomain) { $udomain=$env{'user.domain'}; }
5094: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5095: my $uhome=&homeserver($uname,$udomain);
5096: my $items='';
1.715 albertel 5097: foreach my $key (keys(%$storehash)) {
5098: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5099: }
1.715 albertel 5100: $items=~s/\&$//;
1.716 albertel 5101: my $esc_symb=&escape($symb);
5102: my $esc_v=&escape($version);
1.715 albertel 5103: my $reply =
1.716 albertel 5104: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5105: $uhome);
5106: if ($reply eq 'unknown_cmd') {
1.716 albertel 5107: # gfall back to way things use to be done
1.715 albertel 5108: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5109: $uname);
1.524 raeburn 5110: }
1.715 albertel 5111: return $reply;
5112: }
5113:
5114: sub old_putstore {
1.716 albertel 5115: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5116: if (!$udomain) { $udomain=$env{'user.domain'}; }
5117: if (!$uname) { $uname=$env{'user.name'}; }
5118: my $uhome=&homeserver($uname,$udomain);
5119: my %newstorehash;
1.800 albertel 5120: foreach my $item (keys(%$storehash)) {
5121: my $key = $version.':'.&escape($symb).':'.$item;
5122: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5123: }
5124: my $items='';
5125: my %allitems = ();
1.800 albertel 5126: foreach my $item (keys(%newstorehash)) {
5127: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5128: my $key = $1.':keys:'.$2;
5129: $allitems{$key} .= $3.':';
5130: }
1.800 albertel 5131: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5132: }
1.800 albertel 5133: foreach my $item (keys(%allitems)) {
5134: $allitems{$item} =~ s/\:$//;
5135: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5136: }
5137: $items=~s/\&$//;
5138: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5139: }
5140:
1.47 www 5141: # ------------------------------------------------------ critical put interface
5142:
5143: sub cput {
1.134 albertel 5144: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5145: if (!$udomain) { $udomain=$env{'user.domain'}; }
5146: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5147: my $uhome=&homeserver($uname,$udomain);
1.47 www 5148: my $items='';
1.800 albertel 5149: foreach my $item (keys(%$storehash)) {
5150: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5151: }
1.47 www 5152: $items=~s/\&$//;
1.134 albertel 5153: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5154: }
5155:
5156: # -------------------------------------------------------------- eget interface
5157:
5158: sub eget {
1.133 albertel 5159: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5160: my $items='';
1.800 albertel 5161: foreach my $item (@$storearr) {
5162: $items.=&escape($item).'&';
1.191 harris41 5163: }
1.12 www 5164: $items=~s/\&$//;
1.620 albertel 5165: if (!$udomain) { $udomain=$env{'user.domain'}; }
5166: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5167: my $uhome=&homeserver($uname,$udomain);
5168: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5169: my @pairs=split(/\&/,$rep);
5170: my %returnhash=();
1.42 www 5171: my $i=0;
1.800 albertel 5172: foreach my $item (@$storearr) {
5173: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5174: $i++;
1.191 harris41 5175: }
1.12 www 5176: return %returnhash;
5177: }
5178:
1.667 albertel 5179: # ------------------------------------------------------------ tmpput interface
5180: sub tmpput {
1.802 raeburn 5181: my ($storehash,$server,$context)=@_;
1.667 albertel 5182: my $items='';
1.800 albertel 5183: foreach my $item (keys(%$storehash)) {
5184: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5185: }
5186: $items=~s/\&$//;
1.802 raeburn 5187: if (defined($context)) {
5188: $items .= ':'.&escape($context);
5189: }
1.667 albertel 5190: return &reply("tmpput:$items",$server);
5191: }
5192:
5193: # ------------------------------------------------------------ tmpget interface
5194: sub tmpget {
1.688 albertel 5195: my ($token,$server)=@_;
5196: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5197: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5198: my %returnhash;
5199: foreach my $item (split(/\&/,$rep)) {
5200: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5201: next if ($key =~ /^error: 2 /);
1.667 albertel 5202: $returnhash{&unescape($key)}=&thaw_unescape($value);
5203: }
5204: return %returnhash;
5205: }
5206:
1.1113 raeburn 5207: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5208: sub tmpdel {
5209: my ($token,$server)=@_;
5210: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5211: return &reply("tmpdel:$token",$server);
5212: }
5213:
1.765 albertel 5214: # -------------------------------------------------- portfolio access checking
5215:
5216: sub portfolio_access {
1.766 albertel 5217: my ($requrl) = @_;
1.765 albertel 5218: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5219: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5220: if ($result) {
5221: my %setters;
5222: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5223: my ($startblock,$endblock) =
5224: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5225: if ($startblock && $endblock) {
5226: return 'B';
5227: }
5228: } else {
5229: my ($startblock,$endblock) =
5230: &Apache::loncommon::blockcheck(\%setters,'port');
5231: if ($startblock && $endblock) {
5232: return 'B';
5233: }
5234: }
5235: }
1.765 albertel 5236: if ($result eq 'ok') {
1.766 albertel 5237: return 'F';
1.765 albertel 5238: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5239: return 'A';
1.765 albertel 5240: }
1.766 albertel 5241: return '';
1.765 albertel 5242: }
5243:
5244: sub get_portfolio_access {
1.767 albertel 5245: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5246:
5247: if (!ref($access_hash)) {
5248: my $current_perms = &get_portfile_permissions($udom,$unum);
5249: my %access_controls = &get_access_controls($current_perms,$group,
5250: $file_name);
5251: $access_hash = $access_controls{$file_name};
5252: }
5253:
1.765 albertel 5254: my ($public,$guest,@domains,@users,@courses,@groups);
5255: my $now = time;
5256: if (ref($access_hash) eq 'HASH') {
5257: foreach my $key (keys(%{$access_hash})) {
5258: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5259: if ($start > $now) {
5260: next;
5261: }
5262: if ($end && $end<$now) {
5263: next;
5264: }
5265: if ($scope eq 'public') {
5266: $public = $key;
5267: last;
5268: } elsif ($scope eq 'guest') {
5269: $guest = $key;
5270: } elsif ($scope eq 'domains') {
5271: push(@domains,$key);
5272: } elsif ($scope eq 'users') {
5273: push(@users,$key);
5274: } elsif ($scope eq 'course') {
5275: push(@courses,$key);
5276: } elsif ($scope eq 'group') {
5277: push(@groups,$key);
5278: }
5279: }
5280: if ($public) {
5281: return 'ok';
5282: }
5283: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5284: if ($guest) {
5285: return $guest;
5286: }
5287: } else {
5288: if (@domains > 0) {
5289: foreach my $domkey (@domains) {
5290: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5291: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5292: return 'ok';
5293: }
5294: }
5295: }
5296: }
5297: if (@users > 0) {
5298: foreach my $userkey (@users) {
1.865 raeburn 5299: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5300: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5301: if (ref($item) eq 'HASH') {
5302: if (($item->{'uname'} eq $env{'user.name'}) &&
5303: ($item->{'udom'} eq $env{'user.domain'})) {
5304: return 'ok';
5305: }
5306: }
5307: }
5308: }
1.765 albertel 5309: }
5310: }
5311: my %roleshash;
5312: my @courses_and_groups = @courses;
5313: push(@courses_and_groups,@groups);
5314: if (@courses_and_groups > 0) {
5315: my (%allgroups,%allroles);
5316: my ($start,$end,$role,$sec,$group);
5317: foreach my $envkey (%env) {
1.1060 raeburn 5318: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5319: my $cid = $2.'_'.$3;
5320: if ($1 eq 'gr') {
5321: $group = $4;
5322: $allgroups{$cid}{$group} = $env{$envkey};
5323: } else {
5324: if ($4 eq '') {
5325: $sec = 'none';
5326: } else {
5327: $sec = $4;
5328: }
5329: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5330: }
1.811 albertel 5331: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5332: my $cid = $2.'_'.$3;
5333: if ($4 eq '') {
5334: $sec = 'none';
5335: } else {
5336: $sec = $4;
5337: }
5338: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5339: }
5340: }
5341: if (keys(%allroles) == 0) {
5342: return;
5343: }
5344: foreach my $key (@courses_and_groups) {
5345: my %content = %{$$access_hash{$key}};
5346: my $cnum = $content{'number'};
5347: my $cdom = $content{'domain'};
5348: my $cid = $cdom.'_'.$cnum;
5349: if (!exists($allroles{$cid})) {
5350: next;
5351: }
5352: foreach my $role_id (keys(%{$content{'roles'}})) {
5353: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5354: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5355: my @status = @{$content{'roles'}{$role_id}{'access'}};
5356: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5357: foreach my $role (keys(%{$allroles{$cid}})) {
5358: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5359: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5360: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5361: if (grep/^all$/,@sections) {
5362: return 'ok';
5363: } else {
5364: if (grep/^$sec$/,@sections) {
5365: return 'ok';
5366: }
5367: }
5368: }
5369: }
5370: if (keys(%{$allgroups{$cid}}) == 0) {
5371: if (grep/^none$/,@groups) {
5372: return 'ok';
5373: }
5374: } else {
5375: if (grep/^all$/,@groups) {
5376: return 'ok';
5377: }
5378: foreach my $group (keys(%{$allgroups{$cid}})) {
5379: if (grep/^$group$/,@groups) {
5380: return 'ok';
5381: }
5382: }
5383: }
5384: }
5385: }
5386: }
5387: }
5388: }
5389: if ($guest) {
5390: return $guest;
5391: }
5392: }
5393: }
5394: return;
5395: }
5396:
5397: sub course_group_datechecker {
5398: my ($dates,$now,$status) = @_;
5399: my ($start,$end) = split(/\./,$dates);
5400: if (!$start && !$end) {
5401: return 'ok';
5402: }
5403: if (grep/^active$/,@{$status}) {
5404: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5405: return 'ok';
5406: }
5407: }
5408: if (grep/^previous$/,@{$status}) {
5409: if ($end > $now ) {
5410: return 'ok';
5411: }
5412: }
5413: if (grep/^future$/,@{$status}) {
5414: if ($start > $now) {
5415: return 'ok';
5416: }
5417: }
5418: return;
5419: }
5420:
5421: sub parse_portfolio_url {
5422: my ($url) = @_;
5423:
5424: my ($type,$udom,$unum,$group,$file_name);
5425:
1.823 albertel 5426: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5427: $type = 1;
5428: $udom = $1;
5429: $unum = $2;
5430: $file_name = $3;
1.823 albertel 5431: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5432: $type = 2;
5433: $udom = $1;
5434: $unum = $2;
5435: $group = $3;
5436: $file_name = $3.'/'.$4;
5437: }
5438: if (wantarray) {
5439: return ($type,$udom,$unum,$file_name,$group);
5440: }
5441: return $type;
5442: }
5443:
5444: sub is_portfolio_url {
5445: my ($url) = @_;
5446: return scalar(&parse_portfolio_url($url));
5447: }
5448:
1.798 raeburn 5449: sub is_portfolio_file {
5450: my ($file) = @_;
1.820 raeburn 5451: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5452: return 1;
5453: }
5454: return;
5455: }
5456:
1.976 raeburn 5457: sub usertools_access {
1.1084 raeburn 5458: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 5459: my ($access,%tools);
5460: if ($context eq '') {
5461: $context = 'tools';
5462: }
5463: if ($context eq 'requestcourses') {
5464: %tools = (
5465: official => 1,
5466: unofficial => 1,
1.1006 raeburn 5467: community => 1,
1.985 raeburn 5468: );
5469: } else {
5470: %tools = (
5471: aboutme => 1,
5472: blog => 1,
5473: portfolio => 1,
5474: );
5475: }
1.976 raeburn 5476: return if (!defined($tools{$tool}));
5477:
5478: if ((!defined($udom)) || (!defined($uname))) {
5479: $udom = $env{'user.domain'};
5480: $uname = $env{'user.name'};
5481: }
5482:
1.978 raeburn 5483: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5484: if ($action ne 'reload') {
1.985 raeburn 5485: if ($context eq 'requestcourses') {
5486: return $env{'environment.canrequest.'.$tool};
5487: } else {
5488: return $env{'environment.availabletools.'.$tool};
5489: }
5490: }
1.976 raeburn 5491: }
5492:
5493: my ($toolstatus,$inststatus);
5494:
1.985 raeburn 5495: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5496: ($action ne 'reload')) {
5497: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5498: $inststatus = $env{'environment.inststatus'};
5499: } else {
1.1084 raeburn 5500: if (ref($userenvref) eq 'HASH') {
5501: $toolstatus = $userenvref->{$context.'.'.$tool};
5502: $inststatus = $userenvref->{'inststatus'};
5503: } else {
5504: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5505: $toolstatus = $userenv{$context.'.'.$tool};
5506: $inststatus = $userenv{'inststatus'};
5507: }
1.976 raeburn 5508: }
5509:
5510: if ($toolstatus ne '') {
5511: if ($toolstatus) {
5512: $access = 1;
5513: } else {
5514: $access = 0;
5515: }
5516: return $access;
5517: }
5518:
1.1084 raeburn 5519: my ($is_adv,%domdef);
5520: if (ref($is_advref) eq 'HASH') {
5521: $is_adv = $is_advref->{'is_adv'};
5522: } else {
5523: $is_adv = &is_advanced_user($udom,$uname);
5524: }
5525: if (ref($domdefref) eq 'HASH') {
5526: %domdef = %{$domdefref};
5527: } else {
5528: %domdef = &get_domain_defaults($udom);
5529: }
1.976 raeburn 5530: if (ref($domdef{$tool}) eq 'HASH') {
5531: if ($is_adv) {
5532: if ($domdef{$tool}{'_LC_adv'} ne '') {
5533: if ($domdef{$tool}{'_LC_adv'}) {
5534: $access = 1;
5535: } else {
5536: $access = 0;
5537: }
5538: return $access;
5539: }
5540: }
5541: if ($inststatus ne '') {
5542: my ($hasaccess,$hasnoaccess);
5543: foreach my $affiliation (split(/:/,$inststatus)) {
5544: if ($domdef{$tool}{$affiliation} ne '') {
5545: if ($domdef{$tool}{$affiliation}) {
5546: $hasaccess = 1;
5547: } else {
5548: $hasnoaccess = 1;
5549: }
5550: }
5551: }
5552: if ($hasaccess || $hasnoaccess) {
5553: if ($hasaccess) {
5554: $access = 1;
5555: } elsif ($hasnoaccess) {
5556: $access = 0;
5557: }
5558: return $access;
5559: }
5560: } else {
5561: if ($domdef{$tool}{'default'} ne '') {
5562: if ($domdef{$tool}{'default'}) {
5563: $access = 1;
5564: } elsif ($domdef{$tool}{'default'} == 0) {
5565: $access = 0;
5566: }
5567: return $access;
5568: }
5569: }
5570: } else {
1.985 raeburn 5571: if ($context eq 'tools') {
5572: $access = 1;
5573: } else {
5574: $access = 0;
5575: }
1.976 raeburn 5576: return $access;
5577: }
5578: }
5579:
1.1050 raeburn 5580: sub is_course_owner {
5581: my ($cdom,$cnum,$udom,$uname) = @_;
5582: if (($udom eq '') || ($uname eq '')) {
5583: $udom = $env{'user.domain'};
5584: $uname = $env{'user.name'};
5585: }
5586: unless (($udom eq '') || ($uname eq '')) {
5587: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5588: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5589: return 1;
5590: } else {
5591: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5592: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5593: return 1;
5594: }
5595: }
5596: }
5597: }
5598: return;
5599: }
5600:
1.976 raeburn 5601: sub is_advanced_user {
5602: my ($udom,$uname) = @_;
1.1085 raeburn 5603: if ($udom ne '' && $uname ne '') {
5604: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 5605: if (wantarray) {
5606: return ($env{'user.adv'},$env{'user.author'});
5607: } else {
5608: return $env{'user.adv'};
5609: }
1.1085 raeburn 5610: }
5611: }
1.976 raeburn 5612: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5613: my %allroles;
1.1128 raeburn 5614: my ($is_adv,$is_author);
1.976 raeburn 5615: foreach my $role (keys(%roleshash)) {
5616: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5617: my $area = '/'.$tdomain.'/'.$trest;
5618: if ($sec ne '') {
5619: $area .= '/'.$sec;
5620: }
5621: if (($area ne '') && ($trole ne '')) {
5622: my $spec=$trole.'.'.$area;
5623: if ($trole =~ /^cr\//) {
5624: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5625: } elsif ($trole ne 'gr') {
5626: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5627: }
1.1128 raeburn 5628: if ($trole eq 'au') {
5629: $is_author = 1;
5630: }
1.976 raeburn 5631: }
5632: }
5633: foreach my $role (keys(%allroles)) {
5634: last if ($is_adv);
5635: foreach my $item (split(/:/,$allroles{$role})) {
5636: if ($item ne '') {
5637: my ($privilege,$restrictions)=split(/&/,$item);
5638: if ($privilege eq 'adv') {
5639: $is_adv = 1;
5640: last;
5641: }
5642: }
5643: }
5644: }
1.1128 raeburn 5645: if (wantarray) {
5646: return ($is_adv,$is_author);
5647: }
1.976 raeburn 5648: return $is_adv;
5649: }
1.798 raeburn 5650:
1.1035 raeburn 5651: sub check_can_request {
1.1036 raeburn 5652: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5653: my $canreq = 0;
5654: my ($types,$typename) = &Apache::loncommon::course_types();
5655: my @options = ('approval','validate','autolimit');
5656: my $optregex = join('|',@options);
5657: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5658: foreach my $type (@{$types}) {
5659: if (&usertools_access($env{'user.name'},
5660: $env{'user.domain'},
5661: $type,undef,'requestcourses')) {
5662: $canreq ++;
1.1036 raeburn 5663: if (ref($request_domains) eq 'HASH') {
5664: push(@{$request_domains->{$type}},$env{'user.domain'});
5665: }
1.1035 raeburn 5666: if ($dom eq $env{'user.domain'}) {
5667: $can_request->{$type} = 1;
5668: }
5669: }
5670: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5671: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5672: if (@curr > 0) {
1.1036 raeburn 5673: foreach my $item (@curr) {
5674: if (ref($request_domains) eq 'HASH') {
5675: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5676: if ($otherdom ne '') {
5677: if (ref($request_domains->{$type}) eq 'ARRAY') {
5678: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5679: push(@{$request_domains->{$type}},$otherdom);
5680: }
5681: } else {
5682: push(@{$request_domains->{$type}},$otherdom);
5683: }
5684: }
5685: }
5686: }
5687: unless($dom eq $env{'user.domain'}) {
5688: $canreq ++;
1.1035 raeburn 5689: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5690: $can_request->{$type} = 1;
5691: }
5692: }
5693: }
5694: }
5695: }
5696: }
5697: return $canreq;
5698: }
5699:
1.341 www 5700: # ---------------------------------------------- Custom access rule evaluation
5701:
5702: sub customaccess {
5703: my ($priv,$uri)=@_;
1.807 albertel 5704: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5705: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5706: $udom = &LONCAPA::clean_domain($udom);
5707: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5708: my $access=0;
1.800 albertel 5709: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5710: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5711: if ($type eq 'user') {
5712: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5713: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5714: if ($tdom) {
5715: if ($tdom ne $env{'user.domain'}) { next; }
5716: }
1.896 albertel 5717: if ($tuname) {
5718: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5719: }
5720: $access=($effect eq 'allow');
5721: last;
5722: }
5723: } else {
5724: if ($role) {
5725: if ($role ne $urole) { next; }
5726: }
5727: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5728: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5729: if ($tdom) {
5730: if ($tdom ne $udom) { next; }
5731: }
5732: if ($tcrs) {
5733: if ($tcrs ne $ucrs) { next; }
5734: }
5735: if ($tsec) {
5736: if ($tsec ne $usec) { next; }
5737: }
5738: $access=($effect eq 'allow');
5739: last;
5740: }
5741: if ($realm eq '' && $role eq '') {
5742: $access=($effect eq 'allow');
5743: }
1.402 bowersj2 5744: }
1.341 www 5745: }
5746: return $access;
5747: }
5748:
1.103 harris41 5749: # ------------------------------------------------- Check for a user privilege
1.12 www 5750:
5751: sub allowed {
1.810 raeburn 5752: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5753: my $ver_orguri=$uri;
1.439 www 5754: $uri=&deversion($uri);
1.152 www 5755: my $orguri=$uri;
1.52 www 5756: $uri=&declutter($uri);
1.809 raeburn 5757:
1.810 raeburn 5758: if ($priv eq 'evb') {
5759: # Evade communication block restrictions for specified role in a course
5760: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5761: return $1;
5762: } else {
5763: return;
5764: }
5765: }
5766:
1.620 albertel 5767: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5768: # Free bre access to adm and meta resources
1.775 albertel 5769: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5770: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5771: && ($priv eq 'bre')) {
1.14 www 5772: return 'F';
1.159 www 5773: }
5774:
1.545 banghart 5775: # Free bre access to user's own portfolio contents
1.714 raeburn 5776: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5777: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5778: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5779: my %setters;
5780: my ($startblock,$endblock) =
5781: &Apache::loncommon::blockcheck(\%setters,'port');
5782: if ($startblock && $endblock) {
5783: return 'B';
5784: } else {
5785: return 'F';
5786: }
1.545 banghart 5787: }
5788:
1.762 raeburn 5789: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5790: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5791: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5792: if (exists($env{'request.course.id'})) {
5793: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5794: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5795: if (($domain eq $cdom) && ($name eq $cnum)) {
5796: my $courseprivid=$env{'request.course.id'};
5797: $courseprivid=~s/\_/\//;
5798: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5799: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5800: return $1;
1.762 raeburn 5801: } else {
5802: if ($env{'request.course.sec'}) {
5803: $courseprivid.='/'.$env{'request.course.sec'};
5804: }
5805: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5806: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5807: return $2;
5808: }
1.714 raeburn 5809: }
5810: }
5811: }
5812: }
5813:
1.159 www 5814: # Free bre to public access
5815:
5816: if ($priv eq 'bre') {
1.238 www 5817: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5818: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5819: return 'F';
5820: }
1.238 www 5821: if ($copyright eq 'priv') {
5822: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5823: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5824: return '';
5825: }
5826: }
5827: if ($copyright eq 'domain') {
5828: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5829: unless (($env{'user.domain'} eq $1) ||
5830: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5831: return '';
5832: }
1.262 matthew 5833: }
1.620 albertel 5834: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5835: # Library role, so allow browsing of resources in this domain.
5836: return 'F';
1.238 www 5837: }
1.341 www 5838: if ($copyright eq 'custom') {
5839: unless (&customaccess($priv,$uri)) { return ''; }
5840: }
1.14 www 5841: }
1.264 matthew 5842: # Domain coordinator is trying to create a course
1.620 albertel 5843: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5844: # uri is the requested domain in this case.
5845: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5846: # a role of dc for the domain in question.
1.620 albertel 5847: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5848: }
1.29 www 5849:
1.52 www 5850: my $thisallowed='';
5851: my $statecond=0;
5852: my $courseprivid='';
5853:
1.1039 raeburn 5854: my $ownaccess;
1.1043 raeburn 5855: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5856: if (($priv eq 'bro') && ($env{'user.author'})) {
5857: if ($uri eq '') {
5858: $ownaccess = 1;
5859: } else {
5860: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5861: my $udom = $env{'user.domain'};
5862: my $uname = $env{'user.name'};
5863: if ($uri =~ m{^\Q$udom\E/?$}) {
5864: $ownaccess = 1;
1.1040 raeburn 5865: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5866: unless ($uri =~ m{\.\./}) {
5867: $ownaccess = 1;
5868: }
5869: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5870: my $now = time;
5871: if ($uri =~ m{^([^/]+)/?$}) {
5872: my $adom = $1;
5873: foreach my $key (keys(%env)) {
1.1042 raeburn 5874: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5875: my ($start,$end) = split('.',$env{$key});
5876: if (($now >= $start) && (!$end || $end < $now)) {
5877: $ownaccess = 1;
5878: last;
5879: }
5880: }
5881: }
5882: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5883: my $adom = $1;
5884: my $aname = $2;
1.1042 raeburn 5885: foreach my $role ('ca','aa') {
5886: if ($env{"user.role.$role./$adom/$aname"}) {
5887: my ($start,$end) =
5888: split('.',$env{"user.role.$role./$adom/$aname"});
5889: if (($now >= $start) && (!$end || $end < $now)) {
5890: $ownaccess = 1;
5891: last;
5892: }
1.1039 raeburn 5893: }
5894: }
5895: }
5896: }
5897: }
5898: }
5899: }
5900:
1.52 www 5901: # Course
5902:
1.620 albertel 5903: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5904: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5905: $thisallowed.=$1;
5906: }
1.52 www 5907: }
1.29 www 5908:
1.52 www 5909: # Domain
5910:
1.620 albertel 5911: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5912: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5913: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5914: $thisallowed.=$1;
5915: }
1.12 www 5916: }
1.52 www 5917:
1.1141 raeburn 5918: # User who is not author or co-author might still be able to edit
5919: # resource of an author in the domain (e.g., if Domain Coordinator).
5920: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
5921: (&allowed('mdc',$env{'request.course.id'}))) {
5922: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
5923: $thisallowed.=$1;
5924: }
5925: }
5926:
1.52 www 5927: # Course: uri itself is a course
1.66 www 5928: my $courseuri=$uri;
5929: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5930: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5931:
1.620 albertel 5932: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5933: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5934: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5935: $thisallowed.=$1;
5936: }
1.12 www 5937: }
1.29 www 5938:
1.665 albertel 5939: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5940: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5941: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5942: $thisallowed='';
1.671 raeburn 5943: my ($match)=&is_on_map($uri);
5944: if ($match) {
5945: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5946: =~/\Q$priv\E\&([^\:]*)/) {
5947: $thisallowed.=$1;
5948: }
5949: } else {
1.705 albertel 5950: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5951: if ($refuri) {
5952: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5953: $thisallowed='F';
1.671 raeburn 5954: } else {
5955: $refuri=&declutter($refuri);
5956: my ($match) = &is_on_map($refuri);
5957: if ($match) {
5958: $thisallowed='F';
5959: }
1.669 raeburn 5960: }
1.671 raeburn 5961: }
5962: }
1.314 www 5963: }
1.492 albertel 5964:
1.766 albertel 5965: if ($priv eq 'bre'
5966: && $thisallowed ne 'F'
5967: && $thisallowed ne '2'
5968: && &is_portfolio_url($uri)) {
5969: $thisallowed = &portfolio_access($uri);
5970: }
5971:
1.52 www 5972: # Full access at system, domain or course-wide level? Exit.
1.29 www 5973: if ($thisallowed=~/F/) {
5974: return 'F';
5975: }
5976:
1.52 www 5977: # If this is generating or modifying users, exit with special codes
1.29 www 5978:
1.643 www 5979: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5980: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5981: my ($audom,$auname)=split('/',$uri);
1.643 www 5982: # no author name given, so this just checks on the general right to make a co-author in this domain
5983: unless ($auname) { return $thisallowed; }
5984: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5985: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5986: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5987: ($audom ne $env{'request.role.domain'}))) { return ''; }
5988: }
1.52 www 5989: return $thisallowed;
5990: }
5991: #
1.103 harris41 5992: # Gathered so far: system, domain and course wide privileges
1.52 www 5993: #
5994: # Course: See if uri or referer is an individual resource that is part of
5995: # the course
5996:
1.620 albertel 5997: if ($env{'request.course.id'}) {
1.232 www 5998:
1.620 albertel 5999: $courseprivid=$env{'request.course.id'};
6000: if ($env{'request.course.sec'}) {
6001: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6002: }
6003: $courseprivid=~s/\_/\//;
6004: my $checkreferer=1;
1.232 www 6005: my ($match,$cond)=&is_on_map($uri);
6006: if ($match) {
6007: $statecond=$cond;
1.620 albertel 6008: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6009: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 6010: $thisallowed.=$1;
6011: $checkreferer=0;
6012: }
1.29 www 6013: }
1.83 www 6014:
1.148 www 6015: if ($checkreferer) {
1.620 albertel 6016: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6017: unless ($refuri) {
1.800 albertel 6018: foreach my $key (keys(%env)) {
6019: if ($key=~/^httpref\..*\*/) {
6020: my $pattern=$key;
1.156 www 6021: $pattern=~s/^httpref\.\/res\///;
1.148 www 6022: $pattern=~s/\*/\[\^\/\]\+/g;
6023: $pattern=~s/\//\\\//g;
1.152 www 6024: if ($orguri=~/$pattern/) {
1.800 albertel 6025: $refuri=$env{$key};
1.148 www 6026: }
6027: }
1.191 harris41 6028: }
1.148 www 6029: }
1.232 www 6030:
1.148 www 6031: if ($refuri) {
1.152 www 6032: $refuri=&declutter($refuri);
1.232 www 6033: my ($match,$cond)=&is_on_map($refuri);
6034: if ($match) {
6035: my $refstatecond=$cond;
1.620 albertel 6036: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6037: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 6038: $thisallowed.=$1;
1.53 www 6039: $uri=$refuri;
6040: $statecond=$refstatecond;
1.52 www 6041: }
6042: }
1.148 www 6043: }
1.29 www 6044: }
1.52 www 6045: }
1.29 www 6046:
1.52 www 6047: #
1.103 harris41 6048: # Gathered now: all privileges that could apply, and condition number
1.52 www 6049: #
6050: #
6051: # Full or no access?
6052: #
1.29 www 6053:
1.52 www 6054: if ($thisallowed=~/F/) {
6055: return 'F';
6056: }
1.29 www 6057:
1.52 www 6058: unless ($thisallowed) {
6059: return '';
6060: }
1.29 www 6061:
1.52 www 6062: # Restrictions exist, deal with them
6063: #
6064: # C:according to course preferences
6065: # R:according to resource settings
6066: # L:unless locked
6067: # X:according to user session state
6068: #
6069:
6070: # Possibly locked functionality, check all courses
1.54 www 6071: # Locks might take effect only after 10 minutes cache expiration for other
6072: # courses, and 2 minutes for current course
1.52 www 6073:
6074: my $envkey;
6075: if ($thisallowed=~/L/) {
1.1000 raeburn 6076: foreach $envkey (keys(%env)) {
1.54 www 6077: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6078: my $courseid=$2;
6079: my $roleid=$1.'.'.$2;
1.92 www 6080: $courseid=~s/^\///;
1.54 www 6081: my $expiretime=600;
1.620 albertel 6082: if ($env{'request.role'} eq $roleid) {
1.54 www 6083: $expiretime=120;
6084: }
6085: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6086: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6087: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6088: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6089: }
1.620 albertel 6090: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6091: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6092: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6093: &log($env{'user.domain'},$env{'user.name'},
6094: $env{'user.home'},
1.57 www 6095: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6096: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6097: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6098: return '';
6099: }
6100: }
1.620 albertel 6101: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6102: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6103: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6104: &log($env{'user.domain'},$env{'user.name'},
6105: $env{'user.home'},
1.57 www 6106: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6107: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6108: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6109: return '';
6110: }
6111: }
6112: }
1.29 www 6113: }
1.52 www 6114: }
6115:
6116: #
6117: # Rest of the restrictions depend on selected course
6118: #
6119:
1.620 albertel 6120: unless ($env{'request.course.id'}) {
1.766 albertel 6121: if ($thisallowed eq 'A') {
6122: return 'A';
1.814 raeburn 6123: } elsif ($thisallowed eq 'B') {
6124: return 'B';
1.766 albertel 6125: } else {
6126: return '1';
6127: }
1.52 www 6128: }
1.29 www 6129:
1.52 www 6130: #
6131: # Now user is definitely in a course
6132: #
1.53 www 6133:
6134:
6135: # Course preferences
6136:
6137: if ($thisallowed=~/C/) {
1.620 albertel 6138: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6139: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6140: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6141: =~/\Q$rolecode\E/) {
1.1103 raeburn 6142: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6143: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6144: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6145: $env{'request.course.id'});
6146: }
1.237 www 6147: return '';
6148: }
6149:
1.620 albertel 6150: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6151: =~/\Q$unamedom\E/) {
1.1103 raeburn 6152: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6153: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6154: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6155: $env{'request.course.id'});
6156: }
1.54 www 6157: return '';
6158: }
1.53 www 6159: }
6160:
6161: # Resource preferences
6162:
6163: if ($thisallowed=~/R/) {
1.620 albertel 6164: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6165: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6166: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6167: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6168: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6169: }
6170: return '';
1.54 www 6171: }
1.53 www 6172: }
1.30 www 6173:
1.246 www 6174: # Restricted by state or randomout?
1.30 www 6175:
1.52 www 6176: if ($thisallowed=~/X/) {
1.620 albertel 6177: if ($env{'acc.randomout'}) {
1.579 albertel 6178: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6179: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6180: return '';
6181: }
1.247 www 6182: }
6183: if (&condval($statecond)) {
1.52 www 6184: return '2';
6185: } else {
6186: return '';
6187: }
6188: }
1.30 www 6189:
1.766 albertel 6190: if ($thisallowed eq 'A') {
6191: return 'A';
1.814 raeburn 6192: } elsif ($thisallowed eq 'B') {
6193: return 'B';
1.766 albertel 6194: }
1.52 www 6195: return 'F';
1.232 www 6196: }
1.1133 foxr 6197: #
6198: # Removes the versino from a URI and
6199: # splits it in to its filename and path to the filename.
6200: # Seems like File::Basename could have done this more clearly.
6201: # Parameters:
6202: # $uri - input URI
6203: # Returns:
6204: # Two element list consisting of
6205: # $pathname - the URI up to and excluding the trailing /
6206: # $filename - The part of the URI following the last /
6207: # NOTE:
6208: # Another realization of this is simply:
6209: # use File::Basename;
6210: # ...
6211: # $uri = shift;
6212: # $filename = basename($uri);
6213: # $path = dirname($uri);
6214: # return ($filename, $path);
6215: #
6216: # The implementation below is probably faster however.
6217: #
1.710 albertel 6218: sub split_uri_for_cond {
6219: my $uri=&deversion(&declutter(shift));
6220: my @uriparts=split(/\//,$uri);
6221: my $filename=pop(@uriparts);
6222: my $pathname=join('/',@uriparts);
6223: return ($pathname,$filename);
6224: }
1.232 www 6225: # --------------------------------------------------- Is a resource on the map?
6226:
6227: sub is_on_map {
1.710 albertel 6228: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 6229: #Trying to find the conditional for the file
1.620 albertel 6230: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 6231: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 6232: if ($match) {
1.289 bowersj2 6233: return (1,$1);
6234: } else {
1.434 www 6235: return (0,0);
1.289 bowersj2 6236: }
1.12 www 6237: }
6238:
1.427 www 6239: # --------------------------------------------------------- Get symb from alias
6240:
6241: sub get_symb_from_alias {
6242: my $symb=shift;
6243: my ($map,$resid,$url)=&decode_symb($symb);
6244: # Already is a symb
6245: if ($url) { return $symb; }
6246: # Must be an alias
6247: my $aliassymb='';
6248: my %bighash;
1.620 albertel 6249: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 6250: &GDBM_READER(),0640)) {
6251: my $rid=$bighash{'mapalias_'.$symb};
6252: if ($rid) {
6253: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 6254: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6255: $resid,$bighash{'src_'.$rid});
1.427 www 6256: }
6257: untie %bighash;
6258: }
6259: return $aliassymb;
6260: }
6261:
1.12 www 6262: # ----------------------------------------------------------------- Define Role
6263:
6264: sub definerole {
6265: if (allowed('mcr','/')) {
6266: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 6267: foreach my $role (split(':',$sysrole)) {
6268: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6269: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6270: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6271: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6272: return "refused:s:$crole&$cqual";
6273: }
6274: }
1.191 harris41 6275: }
1.800 albertel 6276: foreach my $role (split(':',$domrole)) {
6277: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6278: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6279: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6280: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 6281: return "refused:d:$crole&$cqual";
6282: }
6283: }
1.191 harris41 6284: }
1.800 albertel 6285: foreach my $role (split(':',$courole)) {
6286: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6287: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6288: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6289: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6290: return "refused:c:$crole&$cqual";
6291: }
6292: }
1.191 harris41 6293: }
1.620 albertel 6294: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6295: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6296: "rolesdef_$rolename=".
6297: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 6298: return reply($command,$env{'user.home'});
1.12 www 6299: } else {
6300: return 'refused';
6301: }
1.105 harris41 6302: }
6303:
6304: # ---------------- Make a metadata query against the network of library servers
6305:
6306: sub metadata_query {
1.244 matthew 6307: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 6308: my %rhash;
1.845 albertel 6309: my %libserv = &all_library();
1.244 matthew 6310: my @server_list = (defined($server_array) ? @$server_array
6311: : keys(%libserv) );
6312: for my $server (@server_list) {
1.118 harris41 6313: unless ($custom or $customshow) {
6314: my $reply=&reply("querysend:".&escape($query),$server);
6315: $rhash{$server}=$reply;
6316: }
6317: else {
6318: my $reply=&reply("querysend:".&escape($query).':'.
6319: &escape($custom).':'.&escape($customshow),
6320: $server);
6321: $rhash{$server}=$reply;
6322: }
1.112 harris41 6323: }
1.118 harris41 6324: return \%rhash;
1.240 www 6325: }
6326:
6327: # ----------------------------------------- Send log queries and wait for reply
6328:
6329: sub log_query {
6330: my ($uname,$udom,$query,%filters)=@_;
6331: my $uhome=&homeserver($uname,$udom);
6332: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 6333: my $uhost=&hostname($uhome);
1.800 albertel 6334: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 6335: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6336: $uhome);
1.479 albertel 6337: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 6338: return get_query_reply($queryid);
6339: }
6340:
1.818 raeburn 6341: # -------------------------- Update MySQL table for portfolio file
6342:
6343: sub update_portfolio_table {
1.821 raeburn 6344: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 6345: if ($group ne '') {
6346: $file_name =~s /^\Q$group\E//;
6347: }
1.818 raeburn 6348: my $homeserver = &homeserver($uname,$udom);
6349: my $queryid=
1.821 raeburn 6350: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6351: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 6352: my $reply = &get_query_reply($queryid);
6353: return $reply;
6354: }
6355:
1.899 raeburn 6356: # -------------------------- Update MySQL allusers table
6357:
6358: sub update_allusers_table {
6359: my ($uname,$udom,$names) = @_;
6360: my $homeserver = &homeserver($uname,$udom);
6361: my $queryid=
6362: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6363: 'lastname='.&escape($names->{'lastname'}).'%%'.
6364: 'firstname='.&escape($names->{'firstname'}).'%%'.
6365: 'middlename='.&escape($names->{'middlename'}).'%%'.
6366: 'generation='.&escape($names->{'generation'}).'%%'.
6367: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6368: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 6369: return;
1.899 raeburn 6370: }
6371:
1.508 raeburn 6372: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 6373:
6374: sub fetch_enrollment_query {
1.511 raeburn 6375: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 6376: my $homeserver;
1.547 raeburn 6377: my $maxtries = 1;
1.508 raeburn 6378: if ($context eq 'automated') {
6379: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 6380: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 6381: } else {
6382: $homeserver = &homeserver($cnum,$dom);
6383: }
1.838 albertel 6384: my $host=&hostname($homeserver);
1.506 raeburn 6385: my $cmd = '';
1.1000 raeburn 6386: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6387: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6388: }
6389: $cmd =~ s/%%$//;
6390: $cmd = &escape($cmd);
6391: my $query = 'fetchenrollment';
1.620 albertel 6392: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6393: unless ($queryid=~/^\Q$host\E\_/) {
6394: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6395: return 'error: '.$queryid;
6396: }
1.506 raeburn 6397: my $reply = &get_query_reply($queryid);
1.547 raeburn 6398: my $tries = 1;
6399: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6400: $reply = &get_query_reply($queryid);
6401: $tries ++;
6402: }
1.526 raeburn 6403: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6404: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6405: } else {
1.901 albertel 6406: my @responses = split(/:/,$reply);
1.515 raeburn 6407: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6408: foreach my $line (@responses) {
6409: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6410: $$replyref{$key} = $value;
6411: }
6412: } else {
1.1117 foxr 6413: my $pathname = LONCAPA::tempdir();
1.800 albertel 6414: foreach my $line (@responses) {
6415: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6416: $$replyref{$key} = $value;
6417: if ($value > 0) {
1.800 albertel 6418: foreach my $item (@{$$affiliatesref{$key}}) {
6419: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6420: my $destname = $pathname.'/'.$filename;
6421: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6422: if ($xml_classlist =~ /^error/) {
6423: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6424: } else {
1.506 raeburn 6425: if ( open(FILE,">$destname") ) {
6426: print FILE &unescape($xml_classlist);
6427: close(FILE);
1.526 raeburn 6428: } else {
6429: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6430: }
6431: }
6432: }
6433: }
6434: }
6435: }
6436: return 'ok';
6437: }
6438: return 'error';
6439: }
6440:
1.242 www 6441: sub get_query_reply {
6442: my $queryid=shift;
1.1117 foxr 6443: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 6444: my $reply='';
6445: for (1..100) {
6446: sleep 2;
6447: if (-e $replyfile.'.end') {
1.448 albertel 6448: if (open(my $fh,$replyfile)) {
1.904 albertel 6449: $reply = join('',<$fh>);
6450: close($fh);
1.240 www 6451: } else { return 'error: reply_file_error'; }
1.242 www 6452: return &unescape($reply);
6453: }
1.240 www 6454: }
1.242 www 6455: return 'timeout:'.$queryid;
1.240 www 6456: }
6457:
6458: sub courselog_query {
1.241 www 6459: #
6460: # possible filters:
6461: # url: url or symb
6462: # username
6463: # domain
6464: # action: view, submit, grade
6465: # start: timestamp
6466: # end: timestamp
6467: #
1.240 www 6468: my (%filters)=@_;
1.620 albertel 6469: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6470: if ($filters{'url'}) {
6471: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6472: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6473: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6474: }
1.620 albertel 6475: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6476: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6477: return &log_query($cname,$cdom,'courselog',%filters);
6478: }
6479:
6480: sub userlog_query {
1.858 raeburn 6481: #
6482: # possible filters:
6483: # action: log check role
6484: # start: timestamp
6485: # end: timestamp
6486: #
1.240 www 6487: my ($uname,$udom,%filters)=@_;
6488: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6489: }
6490:
1.506 raeburn 6491: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6492:
6493: sub auto_run {
1.508 raeburn 6494: my ($cnum,$cdom) = @_;
1.876 raeburn 6495: my $response = 0;
6496: my $settings;
6497: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6498: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6499: $settings = $domconfig{'autoenroll'};
6500: if ($settings->{'run'} eq '1') {
6501: $response = 1;
6502: }
6503: } else {
1.934 raeburn 6504: my $homeserver;
6505: if (&is_course($cdom,$cnum)) {
6506: $homeserver = &homeserver($cnum,$cdom);
6507: } else {
6508: $homeserver = &domain($cdom,'primary');
6509: }
6510: if ($homeserver ne 'no_host') {
6511: $response = &reply('autorun:'.$cdom,$homeserver);
6512: }
1.876 raeburn 6513: }
1.506 raeburn 6514: return $response;
6515: }
1.776 albertel 6516:
1.506 raeburn 6517: sub auto_get_sections {
1.508 raeburn 6518: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6519: my $homeserver;
6520: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6521: $homeserver = &homeserver($cnum,$cdom);
6522: }
6523: if (!defined($homeserver)) {
6524: if ($cdom =~ /^$match_domain$/) {
6525: $homeserver = &domain($cdom,'primary');
6526: }
6527: }
6528: my @secs;
6529: if (defined($homeserver)) {
6530: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6531: unless ($response eq 'refused') {
6532: @secs = split(/:/,$response);
6533: }
1.506 raeburn 6534: }
6535: return @secs;
6536: }
1.776 albertel 6537:
1.506 raeburn 6538: sub auto_new_course {
1.1099 raeburn 6539: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6540: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6541: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6542: return $response;
6543: }
1.776 albertel 6544:
1.506 raeburn 6545: sub auto_validate_courseID {
1.508 raeburn 6546: my ($cnum,$cdom,$inst_course_id) = @_;
6547: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6548: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6549: return $response;
6550: }
1.776 albertel 6551:
1.1007 raeburn 6552: sub auto_validate_instcode {
1.1020 raeburn 6553: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6554: my ($homeserver,$response);
6555: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6556: $homeserver = &homeserver($cnum,$cdom);
6557: }
6558: if (!defined($homeserver)) {
6559: if ($cdom =~ /^$match_domain$/) {
6560: $homeserver = &domain($cdom,'primary');
6561: }
6562: }
1.1065 raeburn 6563: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6564: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6565: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6566: return ($outcome,$description);
1.1007 raeburn 6567: }
6568:
1.506 raeburn 6569: sub auto_create_password {
1.873 raeburn 6570: my ($cnum,$cdom,$authparam,$udom) = @_;
6571: my ($homeserver,$response);
1.506 raeburn 6572: my $create_passwd = 0;
6573: my $authchk = '';
1.873 raeburn 6574: if ($udom =~ /^$match_domain$/) {
6575: $homeserver = &domain($udom,'primary');
6576: }
6577: if ($homeserver eq '') {
6578: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6579: $homeserver = &homeserver($cnum,$cdom);
6580: }
6581: }
6582: if ($homeserver eq '') {
6583: $authchk = 'nodomain';
1.506 raeburn 6584: } else {
1.873 raeburn 6585: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6586: if ($response eq 'refused') {
6587: $authchk = 'refused';
6588: } else {
1.901 albertel 6589: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6590: }
1.506 raeburn 6591: }
6592: return ($authparam,$create_passwd,$authchk);
6593: }
6594:
1.706 raeburn 6595: sub auto_photo_permission {
6596: my ($cnum,$cdom,$students) = @_;
6597: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6598: my ($outcome,$perm_reqd,$conditions) =
6599: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6600: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6601: return (undef,undef);
6602: }
1.706 raeburn 6603: return ($outcome,$perm_reqd,$conditions);
6604: }
6605:
6606: sub auto_checkphotos {
6607: my ($uname,$udom,$pid) = @_;
6608: my $homeserver = &homeserver($uname,$udom);
6609: my ($result,$resulttype);
6610: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6611: &escape($uname).':'.&escape($pid),
6612: $homeserver));
1.709 albertel 6613: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6614: return (undef,undef);
6615: }
1.706 raeburn 6616: if ($outcome) {
6617: ($result,$resulttype) = split(/:/,$outcome);
6618: }
6619: return ($result,$resulttype);
6620: }
6621:
6622: sub auto_photochoice {
6623: my ($cnum,$cdom) = @_;
6624: my $homeserver = &homeserver($cnum,$cdom);
6625: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6626: &escape($cdom),
6627: $homeserver)));
1.709 albertel 6628: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6629: return (undef,undef);
6630: }
1.706 raeburn 6631: return ($update,$comment);
6632: }
6633:
6634: sub auto_photoupdate {
6635: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6636: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6637: my $host=&hostname($homeserver);
1.706 raeburn 6638: my $cmd = '';
6639: my $maxtries = 1;
1.800 albertel 6640: foreach my $affiliate (keys(%{$affiliatesref})) {
6641: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6642: }
6643: $cmd =~ s/%%$//;
6644: $cmd = &escape($cmd);
6645: my $query = 'institutionalphotos';
6646: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6647: unless ($queryid=~/^\Q$host\E\_/) {
6648: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6649: return 'error: '.$queryid;
6650: }
6651: my $reply = &get_query_reply($queryid);
6652: my $tries = 1;
6653: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6654: $reply = &get_query_reply($queryid);
6655: $tries ++;
6656: }
6657: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6658: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6659: } else {
6660: my @responses = split(/:/,$reply);
6661: my $outcome = shift(@responses);
6662: foreach my $item (@responses) {
6663: my ($key,$value) = split(/=/,$item);
6664: $$photo{$key} = $value;
6665: }
6666: return $outcome;
6667: }
6668: return 'error';
6669: }
6670:
1.521 raeburn 6671: sub auto_instcode_format {
1.793 albertel 6672: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6673: $cat_order) = @_;
1.521 raeburn 6674: my $courses = '';
1.772 raeburn 6675: my @homeservers;
1.521 raeburn 6676: if ($caller eq 'global') {
1.841 albertel 6677: my %servers = &get_servers($codedom,'library');
6678: foreach my $tryserver (keys(%servers)) {
6679: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6680: push(@homeservers,$tryserver);
6681: }
1.584 raeburn 6682: }
1.1022 raeburn 6683: } elsif ($caller eq 'requests') {
6684: if ($codedom =~ /^$match_domain$/) {
6685: my $chome = &domain($codedom,'primary');
6686: unless ($chome eq 'no_host') {
6687: push(@homeservers,$chome);
6688: }
6689: }
1.521 raeburn 6690: } else {
1.772 raeburn 6691: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6692: }
1.793 albertel 6693: foreach my $code (keys(%{$instcodes})) {
6694: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6695: }
6696: chop($courses);
1.772 raeburn 6697: my $ok_response = 0;
6698: my $response;
6699: while (@homeservers > 0 && $ok_response == 0) {
6700: my $server = shift(@homeservers);
6701: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6702: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6703: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6704: split(/:/,$response);
1.772 raeburn 6705: %{$codes} = (%{$codes},&str2hash($codes_str));
6706: push(@{$codetitles},&str2array($codetitles_str));
6707: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6708: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6709: $ok_response = 1;
6710: }
6711: }
6712: if ($ok_response) {
1.521 raeburn 6713: return 'ok';
1.772 raeburn 6714: } else {
6715: return $response;
1.521 raeburn 6716: }
6717: }
6718:
1.792 raeburn 6719: sub auto_instcode_defaults {
6720: my ($domain,$returnhash,$code_order) = @_;
6721: my @homeservers;
1.841 albertel 6722:
6723: my %servers = &get_servers($domain,'library');
6724: foreach my $tryserver (keys(%servers)) {
6725: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6726: push(@homeservers,$tryserver);
6727: }
1.792 raeburn 6728: }
1.841 albertel 6729:
1.792 raeburn 6730: my $response;
1.841 albertel 6731: foreach my $server (@homeservers) {
1.792 raeburn 6732: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6733: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6734:
6735: foreach my $pair (split(/\&/,$response)) {
6736: my ($name,$value)=split(/\=/,$pair);
6737: if ($name eq 'code_order') {
6738: @{$code_order} = split(/\&/,&unescape($value));
6739: } else {
6740: $returnhash->{&unescape($name)}=&unescape($value);
6741: }
6742: }
6743: return 'ok';
1.792 raeburn 6744: }
1.841 albertel 6745:
6746: return $response;
1.1003 raeburn 6747: }
6748:
6749: sub auto_possible_instcodes {
1.1007 raeburn 6750: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6751: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6752: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6753: return;
6754: }
1.1003 raeburn 6755: my (@homeservers,$uhome);
6756: if (defined(&domain($domain,'primary'))) {
6757: $uhome=&domain($domain,'primary');
6758: push(@homeservers,&domain($domain,'primary'));
6759: } else {
6760: my %servers = &get_servers($domain,'library');
6761: foreach my $tryserver (keys(%servers)) {
6762: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6763: push(@homeservers,$tryserver);
6764: }
6765: }
6766: }
6767: my $response;
6768: foreach my $server (@homeservers) {
6769: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6770: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6771: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6772: split(':',$response);
6773: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6774: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6775: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6776: my ($name,$value)=split('=',$item);
6777: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6778: }
6779: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6780: my ($name,$value)=split('=',$item);
6781: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6782: }
6783: return 'ok';
6784: }
6785: return $response;
6786: }
1.792 raeburn 6787:
1.1010 raeburn 6788: sub auto_courserequest_checks {
6789: my ($dom) = @_;
1.1020 raeburn 6790: my ($homeserver,%validations);
6791: if ($dom =~ /^$match_domain$/) {
6792: $homeserver = &domain($dom,'primary');
6793: }
6794: unless ($homeserver eq 'no_host') {
6795: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6796: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6797: my @items = split(/&/,$response);
6798: foreach my $item (@items) {
6799: my ($key,$value) = split('=',$item);
6800: $validations{&unescape($key)} = &thaw_unescape($value);
6801: }
6802: }
6803: }
1.1010 raeburn 6804: return %validations;
6805: }
6806:
1.1020 raeburn 6807: sub auto_courserequest_validation {
6808: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6809: my ($homeserver,$response);
6810: if ($dom =~ /^$match_domain$/) {
6811: $homeserver = &domain($dom,'primary');
6812: }
6813: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6814:
1.1020 raeburn 6815: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6816: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6817: ':'.&escape($instcode).':'.&escape($instseclist),
6818: $homeserver));
6819: }
6820: return $response;
6821: }
6822:
1.777 albertel 6823: sub auto_validate_class_sec {
1.918 raeburn 6824: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6825: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6826: my $ownerlist;
6827: if (ref($owners) eq 'ARRAY') {
6828: $ownerlist = join(',',@{$owners});
6829: } else {
6830: $ownerlist = $owners;
6831: }
1.773 raeburn 6832: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6833: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6834: return $response;
6835: }
6836:
1.679 raeburn 6837: # ------------------------------------------------------- Course Group routines
6838:
6839: sub get_coursegroups {
1.809 raeburn 6840: my ($cdom,$cnum,$group,$namespace) = @_;
6841: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6842: }
6843:
1.679 raeburn 6844: sub modify_coursegroup {
6845: my ($cdom,$cnum,$groupsettings) = @_;
6846: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6847: }
6848:
1.809 raeburn 6849: sub toggle_coursegroup_status {
6850: my ($cdom,$cnum,$group,$action) = @_;
6851: my ($from_namespace,$to_namespace);
6852: if ($action eq 'delete') {
6853: $from_namespace = 'coursegroups';
6854: $to_namespace = 'deleted_groups';
6855: } else {
6856: $from_namespace = 'deleted_groups';
6857: $to_namespace = 'coursegroups';
6858: }
6859: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6860: if (my $tmp = &error(%curr_group)) {
6861: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6862: return ('read error',$tmp);
6863: } else {
6864: my %savedsettings = %curr_group;
1.809 raeburn 6865: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6866: my $deloutcome;
6867: if ($result eq 'ok') {
1.809 raeburn 6868: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6869: } else {
6870: return ('write error',$result);
6871: }
6872: if ($deloutcome eq 'ok') {
6873: return 'ok';
6874: } else {
6875: return ('delete error',$deloutcome);
6876: }
6877: }
6878: }
6879:
1.679 raeburn 6880: sub modify_group_roles {
1.957 raeburn 6881: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6882: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6883: my $role = 'gr/'.&escape($userprivs);
6884: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6885: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6886: if ($result eq 'ok') {
6887: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6888: }
1.679 raeburn 6889: return $result;
6890: }
6891:
6892: sub modify_coursegroup_membership {
6893: my ($cdom,$cnum,$membership) = @_;
6894: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6895: return $result;
6896: }
6897:
1.682 raeburn 6898: sub get_active_groups {
6899: my ($udom,$uname,$cdom,$cnum) = @_;
6900: my $now = time;
6901: my %groups = ();
6902: foreach my $key (keys(%env)) {
1.811 albertel 6903: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6904: my ($start,$end) = split(/\./,$env{$key});
6905: if (($end!=0) && ($end<$now)) { next; }
6906: if (($start!=0) && ($start>$now)) { next; }
6907: if ($1 eq $cdom && $2 eq $cnum) {
6908: $groups{$3} = $env{$key} ;
6909: }
6910: }
6911: }
6912: return %groups;
6913: }
6914:
1.683 raeburn 6915: sub get_group_membership {
6916: my ($cdom,$cnum,$group) = @_;
6917: return(&dump('groupmembership',$cdom,$cnum,$group));
6918: }
6919:
6920: sub get_users_groups {
6921: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6922: my @usersgroups;
1.683 raeburn 6923: my $cachetime=1800;
6924:
6925: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6926: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6927: if (defined($cached)) {
1.734 albertel 6928: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6929: } else {
6930: $grouplist = '';
1.816 raeburn 6931: my $courseurl = &courseid_to_courseurl($courseid);
1.1086 raeburn 6932: my $extra = &freeze_escape({'skipcheck' => 1});
6933: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6934: my $access_end = $env{'course.'.$courseid.
6935: '.default_enrollment_end_date'};
6936: my $now = time;
6937: foreach my $key (keys(%roleshash)) {
6938: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6939: my $group = $1;
6940: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6941: my $start = $2;
6942: my $end = $1;
6943: if ($start == -1) { next; } # deleted from group
6944: if (($start!=0) && ($start>$now)) { next; }
6945: if (($end!=0) && ($end<$now)) {
6946: if ($access_end && $access_end < $now) {
6947: if ($access_end - $end < 86400) {
6948: push(@usersgroups,$group);
1.733 raeburn 6949: }
6950: }
1.817 raeburn 6951: next;
1.733 raeburn 6952: }
1.817 raeburn 6953: push(@usersgroups,$group);
1.683 raeburn 6954: }
6955: }
6956: }
1.817 raeburn 6957: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6958: $grouplist = join(':',@usersgroups);
6959: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6960: }
1.733 raeburn 6961: return @usersgroups;
1.683 raeburn 6962: }
6963:
6964: sub devalidate_getgroups_cache {
6965: my ($udom,$uname,$cdom,$cnum)=@_;
6966: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6967:
1.683 raeburn 6968: my $hashid="$udom:$uname:$courseid";
6969: &devalidate_cache_new('getgroups',$hashid);
6970: }
6971:
1.12 www 6972: # ------------------------------------------------------------------ Plain Text
6973:
6974: sub plaintext {
1.988 raeburn 6975: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6976: if ($short =~ m{^cr/}) {
1.758 albertel 6977: return (split('/',$short))[-1];
6978: }
1.742 raeburn 6979: if (!defined($cid)) {
6980: $cid = $env{'request.course.id'};
6981: }
6982: my %rolenames = (
1.1008 raeburn 6983: Course => 'std',
6984: Community => 'alt1',
1.742 raeburn 6985: );
1.1037 raeburn 6986: if ($cid ne '') {
6987: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6988: unless ($forcedefault) {
6989: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6990: &Apache::lonlocal::mt_escape(\$roletext);
6991: return &Apache::lonlocal::mt($roletext);
6992: }
6993: }
6994: }
6995: if ((defined($type)) && (defined($rolenames{$type})) &&
6996: (defined($rolenames{$type})) &&
6997: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6998: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6999: } elsif ($cid ne '') {
7000: my $crstype = $env{'course.'.$cid.'.type'};
7001: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7002: (defined($prp{$short}{$rolenames{$crstype}}))) {
7003: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7004: }
1.742 raeburn 7005: }
1.1037 raeburn 7006: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 7007: }
7008:
7009: # ----------------------------------------------------------------- Assign Role
7010:
7011: sub assignrole {
1.957 raeburn 7012: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7013: $context)=@_;
1.21 www 7014: my $mrole;
7015: if ($role =~ /^cr\//) {
1.393 www 7016: my $cwosec=$url;
1.811 albertel 7017: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 7018: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 7019: my $refused = 1;
7020: if ($context eq 'requestcourses') {
7021: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7022: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7023: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7024: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7025: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7026: if ($crsenv{'internal.courseowner'} eq
7027: $env{'user.name'}.':'.$env{'user.domain'}) {
7028: $refused = '';
7029: }
7030: }
7031: }
7032: }
7033: }
7034: if ($refused) {
7035: &logthis('Refused custom assignrole: '.
7036: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7037: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7038: return 'refused';
7039: }
1.104 www 7040: }
1.21 www 7041: $mrole='cr';
1.678 raeburn 7042: } elsif ($role =~ /^gr\//) {
7043: my $cwogrp=$url;
1.811 albertel 7044: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 7045: unless (&allowed('mdg',$cwogrp)) {
7046: &logthis('Refused group assignrole: '.
7047: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7048: $env{'user.name'}.' at '.$env{'user.domain'});
7049: return 'refused';
7050: }
7051: $mrole='gr';
1.21 www 7052: } else {
1.82 www 7053: my $cwosec=$url;
1.811 albertel 7054: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 7055: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7056: my $refused;
7057: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7058: if (!(&allowed('c'.$role,$url))) {
7059: $refused = 1;
7060: }
7061: } else {
7062: $refused = 1;
7063: }
1.947 raeburn 7064: if ($refused) {
1.1045 raeburn 7065: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7066: if (!$selfenroll && $context eq 'course') {
7067: my %crsenv;
7068: if ($role eq 'cc' || $role eq 'co') {
7069: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7070: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7071: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7072: if ($crsenv{'internal.courseowner'} eq
7073: $env{'user.name'}.':'.$env{'user.domain'}) {
7074: $refused = '';
7075: }
7076: }
7077: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7078: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7079: if ($crsenv{'internal.courseowner'} eq
7080: $env{'user.name'}.':'.$env{'user.domain'}) {
7081: $refused = '';
7082: }
7083: }
7084: }
7085: }
7086: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 7087: $refused = '';
1.1017 raeburn 7088: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 7089: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 7090: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 7091: my $wrongcc;
7092: if ($cnum =~ /^$match_community$/) {
7093: $wrongcc = 1 if ($role eq 'cc');
7094: } else {
7095: $wrongcc = 1 if ($role eq 'co');
7096: }
7097: unless ($wrongcc) {
7098: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7099: if ($crsenv{'internal.courseowner'} eq
7100: $env{'user.name'}.':'.$env{'user.domain'}) {
7101: $refused = '';
7102: }
1.1017 raeburn 7103: }
7104: }
7105: }
7106: if ($refused) {
1.947 raeburn 7107: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7108: ' '.$role.' '.$end.' '.$start.' by '.
7109: $env{'user.name'}.' at '.$env{'user.domain'});
7110: return 'refused';
7111: }
1.932 raeburn 7112: }
1.1131 raeburn 7113: } elsif ($role eq 'au') {
7114: if ($url ne '/'.$udom.'/') {
7115: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7116: ' to assign author role for '.$uname.':'.$udom.
7117: ' in domain: '.$url.' refused (wrong domain).');
7118: return 'refused';
7119: }
1.104 www 7120: }
1.21 www 7121: $mrole=$role;
7122: }
1.620 albertel 7123: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7124: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 7125: if ($end) { $command.='_'.$end; }
1.21 www 7126: if ($start) {
7127: if ($end) {
1.81 www 7128: $command.='_'.$start;
1.21 www 7129: } else {
1.81 www 7130: $command.='_0_'.$start;
1.21 www 7131: }
7132: }
1.739 raeburn 7133: my $origstart = $start;
7134: my $origend = $end;
1.957 raeburn 7135: my $delflag;
1.357 www 7136: # actually delete
7137: if ($deleteflag) {
1.373 www 7138: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 7139: # modify command to delete the role
1.620 albertel 7140: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 7141: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 7142: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 7143: # set start and finish to negative values for userrolelog
7144: $start=-1;
7145: $end=-1;
1.957 raeburn 7146: $delflag = 1;
1.357 www 7147: }
7148: }
7149: # send command
1.349 www 7150: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 7151: # log new user role if status is ok
1.349 www 7152: if ($answer eq 'ok') {
1.663 raeburn 7153: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 7154: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 7155: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 7156: unless ($role =~ /^gr/) {
7157: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 7158: $origstart,$selfenroll,$context);
1.739 raeburn 7159: }
1.1053 raeburn 7160: if ($role eq 'cc') {
7161: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7162: }
1.349 www 7163: }
7164: return $answer;
1.169 harris41 7165: }
7166:
1.1053 raeburn 7167: sub autoupdate_coowners {
7168: my ($url,$end,$start,$uname,$udom) = @_;
7169: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7170: if (($cdom ne '') && ($cnum ne '')) {
7171: my $now = time;
7172: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7173: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7174: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7175: my $instcode = $coursehash{'internal.coursecode'};
7176: if ($instcode ne '') {
1.1056 raeburn 7177: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7178: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 7179: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 7180: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7181: if ($result eq 'valid') {
7182: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 7183: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7184: push(@newcoowners,$coowner);
7185: }
7186: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7187: push(@newcoowners,$uname.':'.$udom);
7188: }
7189: @newcoowners = sort(@newcoowners);
7190: } else {
7191: push(@newcoowners,$uname.':'.$udom);
7192: }
7193: } else {
7194: if ($coursehash{'internal.co-owners'}) {
7195: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7196: unless ($coowner eq $uname.':'.$udom) {
7197: push(@newcoowners,$coowner);
7198: }
7199: }
7200: unless (@newcoowners > 0) {
7201: $delcoowners = 1;
7202: $coowners = '';
7203: }
7204: }
7205: }
7206: if (@newcoowners || $delcoowners) {
7207: &store_coowners($cdom,$cnum,$coursehash{'home'},
7208: $delcoowners,@newcoowners);
7209: }
7210: }
7211: }
7212: }
7213: }
7214: }
7215: }
7216:
7217: sub store_coowners {
7218: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7219: my $cid = $cdom.'_'.$cnum;
7220: my ($coowners,$delresult,$putresult);
7221: if (@newcoowners) {
7222: $coowners = join(',',@newcoowners);
7223: my %coownershash = (
7224: 'internal.co-owners' => $coowners,
7225: );
7226: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7227: if ($putresult eq 'ok') {
7228: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7229: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7230: }
7231: }
7232: }
7233: if ($delcoowners) {
7234: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7235: if ($delresult eq 'ok') {
7236: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7237: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7238: }
7239: }
7240: }
7241: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7242: my %crsinfo =
7243: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7244: if (ref($crsinfo{$cid}) eq 'HASH') {
7245: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7246: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7247: }
7248: }
7249: }
7250:
1.169 harris41 7251: # -------------------------------------------------- Modify user authentication
1.197 www 7252: # Overrides without validation
7253:
1.169 harris41 7254: sub modifyuserauth {
7255: my ($udom,$uname,$umode,$upass)=@_;
7256: my $uhome=&homeserver($uname,$udom);
1.197 www 7257: unless (&allowed('mau',$udom)) { return 'refused'; }
7258: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 7259: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7260: ' in domain '.$env{'request.role.domain'});
1.169 harris41 7261: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7262: &escape($upass),$uhome);
1.620 albertel 7263: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 7264: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7265: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7266: &log($udom,,$uname,$uhome,
1.620 albertel 7267: 'Authentication changed by '.$env{'user.domain'}.', '.
7268: $env{'user.name'}.', '.$umode.
1.197 www 7269: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 7270: unless ($reply eq 'ok') {
1.197 www 7271: &logthis('Authentication mode error: '.$reply);
1.169 harris41 7272: return 'error: '.$reply;
7273: }
1.170 harris41 7274: return 'ok';
1.80 www 7275: }
7276:
1.81 www 7277: # --------------------------------------------------------------- Modify a user
1.80 www 7278:
1.81 www 7279: sub modifyuser {
1.206 matthew 7280: my ($udom, $uname, $uid,
7281: $umode, $upass, $first,
7282: $middle, $last, $gene,
1.1058 raeburn 7283: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 7284: $udom= &LONCAPA::clean_domain($udom);
7285: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 7286: my $showcandelete = 'none';
7287: if (ref($candelete) eq 'ARRAY') {
7288: if (@{$candelete} > 0) {
7289: $showcandelete = join(', ',@{$candelete});
7290: }
7291: }
1.81 www 7292: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 7293: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 7294: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 7295: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7296: ' desiredhome not specified').
1.620 albertel 7297: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7298: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 7299: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 7300: my $newuser;
7301: if ($uhome eq 'no_host') {
7302: $newuser = 1;
7303: }
1.80 www 7304: # ----------------------------------------------------------------- Create User
1.406 albertel 7305: if (($uhome eq 'no_host') &&
7306: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 7307: my $unhome='';
1.844 albertel 7308: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 7309: $unhome = $desiredhome;
1.620 albertel 7310: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7311: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 7312: } else { # load balancing routine for determining $unhome
1.81 www 7313: my $loadm=10000000;
1.841 albertel 7314: my %servers = &get_servers($udom,'library');
7315: foreach my $tryserver (keys(%servers)) {
7316: my $answer=reply('load',$tryserver);
7317: if (($answer=~/\d+/) && ($answer<$loadm)) {
7318: $loadm=$answer;
7319: $unhome=$tryserver;
7320: }
1.80 www 7321: }
7322: }
7323: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 7324: return 'error: unable to find a home server for '.$uname.
7325: ' in domain '.$udom;
1.80 www 7326: }
7327: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7328: &escape($upass),$unhome);
7329: unless ($reply eq 'ok') {
7330: return 'error: '.$reply;
7331: }
1.230 stredwic 7332: $uhome=&homeserver($uname,$udom,'true');
1.80 www 7333: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 7334: return 'error: unable verify users home machine.';
1.80 www 7335: }
1.209 matthew 7336: } # End of creation of new user
1.80 www 7337: # ---------------------------------------------------------------------- Add ID
7338: if ($uid) {
7339: $uid=~tr/A-Z/a-z/;
7340: my %uidhash=&idrget($udom,$uname);
1.196 www 7341: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7342: && (!$forceid)) {
1.80 www 7343: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 7344: return 'error: user id "'.$uid.'" does not match '.
7345: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 7346: }
7347: } else {
7348: &idput($udom,($uname => $uid));
7349: }
7350: }
7351: # -------------------------------------------------------------- Add names, etc
1.313 matthew 7352: my @tmp=&get('environment',
1.899 raeburn 7353: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 7354: 'permanentemail','inststatus'],
1.134 albertel 7355: $udom,$uname);
1.1075 raeburn 7356: my (%names,%oldnames);
1.313 matthew 7357: if ($tmp[0] =~ m/^error:.*/) {
7358: %names=();
7359: } else {
7360: %names = @tmp;
1.1075 raeburn 7361: %oldnames = %names;
1.313 matthew 7362: }
1.388 www 7363: #
1.1058 raeburn 7364: # If name, email and/or uid are blank (e.g., because an uploaded file
7365: # of users did not contain them), do not overwrite existing values
7366: # unless field is in $candelete array ref.
7367: #
7368:
7369: my @fields = ('firstname','middlename','lastname','generation',
7370: 'permanentemail','id');
7371: my %newvalues;
7372: if (ref($candelete) eq 'ARRAY') {
7373: foreach my $field (@fields) {
7374: if (grep(/^\Q$field\E$/,@{$candelete})) {
7375: if ($field eq 'firstname') {
7376: $names{$field} = $first;
7377: } elsif ($field eq 'middlename') {
7378: $names{$field} = $middle;
7379: } elsif ($field eq 'lastname') {
7380: $names{$field} = $last;
7381: } elsif ($field eq 'generation') {
7382: $names{$field} = $gene;
7383: } elsif ($field eq 'permanentemail') {
7384: $names{$field} = $email;
7385: } elsif ($field eq 'id') {
7386: $names{$field} = $uid;
7387: }
7388: }
7389: }
7390: }
1.388 www 7391: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7392: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7393: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7394: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7395: if ($email) {
7396: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7397: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7398: }
1.899 raeburn 7399: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7400: if (defined($inststatus)) {
7401: $names{'inststatus'} = '';
7402: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7403: if (ref($usertypes) eq 'HASH') {
7404: my @okstatuses;
7405: foreach my $item (split(/:/,$inststatus)) {
7406: if (defined($usertypes->{$item})) {
7407: push(@okstatuses,$item);
7408: }
7409: }
7410: if (@okstatuses) {
7411: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7412: }
7413: }
7414: }
1.1075 raeburn 7415: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7416: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 7417: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7418: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7419: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7420: } else {
7421: $logmsg .= ' during self creation';
7422: }
1.1075 raeburn 7423: my $changed;
7424: if ($newuser) {
7425: $changed = 1;
7426: } else {
7427: foreach my $field (@fields) {
7428: if ($names{$field} ne $oldnames{$field}) {
7429: $changed = 1;
7430: last;
7431: }
7432: }
7433: }
7434: unless ($changed) {
7435: $logmsg = 'No changes in user information needed for: '.$logmsg;
7436: &logthis($logmsg);
7437: return 'ok';
7438: }
7439: my $reply = &put('environment', \%names, $udom,$uname);
7440: if ($reply ne 'ok') {
7441: return 'error: '.$reply;
7442: }
1.1087 raeburn 7443: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7444: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7445: }
1.1075 raeburn 7446: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7447: &devalidate_cache_new('namescache',$uname.':'.$udom);
7448: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7449: &logthis($logmsg);
1.134 albertel 7450: return 'ok';
1.80 www 7451: }
7452:
1.81 www 7453: # -------------------------------------------------------------- Modify student
1.80 www 7454:
1.81 www 7455: sub modifystudent {
7456: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7457: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7458: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7459: if (!$cid) {
1.620 albertel 7460: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7461: return 'not_in_class';
7462: }
1.80 www 7463: }
7464: # --------------------------------------------------------------- Make the user
1.81 www 7465: my $reply=&modifyuser
1.209 matthew 7466: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7467: $desiredhome,$email,$inststatus);
1.80 www 7468: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7469: # This will cause &modify_student_enrollment to get the uid from the
7470: # students environment
7471: $uid = undef if (!$forceid);
1.455 albertel 7472: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7473: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7474: return $reply;
7475: }
7476:
7477: sub modify_student_enrollment {
1.957 raeburn 7478: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7479: my ($cdom,$cnum,$chome);
7480: if (!$cid) {
1.620 albertel 7481: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7482: return 'not_in_class';
7483: }
1.620 albertel 7484: $cdom=$env{'course.'.$cid.'.domain'};
7485: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7486: } else {
7487: ($cdom,$cnum)=split(/_/,$cid);
7488: }
1.620 albertel 7489: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7490: if (!$chome) {
1.457 raeburn 7491: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7492: }
1.455 albertel 7493: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7494: # Make sure the user exists
1.81 www 7495: my $uhome=&homeserver($uname,$udom);
7496: if (($uhome eq '') || ($uhome eq 'no_host')) {
7497: return 'error: no such user';
7498: }
1.297 matthew 7499: # Get student data if we were not given enough information
7500: if (!defined($first) || $first eq '' ||
7501: !defined($last) || $last eq '' ||
7502: !defined($uid) || $uid eq '' ||
7503: !defined($middle) || $middle eq '' ||
7504: !defined($gene) || $gene eq '') {
1.294 matthew 7505: # They did not supply us with enough data to enroll the student, so
7506: # we need to pick up more information.
1.297 matthew 7507: my %tmp = &get('environment',
1.294 matthew 7508: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7509: ,$udom,$uname);
7510:
1.800 albertel 7511: #foreach my $key (keys(%tmp)) {
7512: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7513: #}
1.294 matthew 7514: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7515: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7516: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7517: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7518: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7519: }
1.556 albertel 7520: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 7521: my $user = "$uname:$udom";
7522: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 7523: my $reply=cput('classlist',
1.1148 raeburn 7524: {$user =>
1.515 raeburn 7525: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7526: $cdom,$cnum);
1.1148 raeburn 7527: if (($reply eq 'ok') || ($reply eq 'delayed')) {
7528: &devalidate_getsection_cache($udom,$uname,$cid);
7529: } else {
1.81 www 7530: return 'error: '.$reply;
7531: }
1.297 matthew 7532: # Add student role to user
1.83 www 7533: my $uurl='/'.$cid;
1.81 www 7534: $uurl=~s/\_/\//g;
7535: if ($usec) {
7536: $uurl.='/'.$usec;
7537: }
1.1148 raeburn 7538: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
7539: $selfenroll,$context);
7540: if ($result ne 'ok') {
7541: if ($old_entry{$user} ne '') {
7542: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
7543: } else {
7544: $reply = &del('classlist',[$user],$cdom,$cnum);
7545: }
7546: }
7547: return $result;
1.21 www 7548: }
7549:
1.556 albertel 7550: sub format_name {
7551: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7552: my $name;
7553: if ($first ne 'lastname') {
7554: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7555: } else {
7556: if ($lastname=~/\S/) {
7557: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7558: $name=~s/\s+,/,/;
7559: } else {
7560: $name.= $firstname.' '.$middlename.' '.$generation;
7561: }
7562: }
7563: $name=~s/^\s+//;
7564: $name=~s/\s+$//;
7565: $name=~s/\s+/ /g;
7566: return $name;
7567: }
7568:
1.84 www 7569: # ------------------------------------------------- Write to course preferences
7570:
7571: sub writecoursepref {
7572: my ($courseid,%prefs)=@_;
7573: $courseid=~s/^\///;
7574: $courseid=~s/\_/\//g;
7575: my ($cdomain,$cnum)=split(/\//,$courseid);
7576: my $chome=homeserver($cnum,$cdomain);
7577: if (($chome eq '') || ($chome eq 'no_host')) {
7578: return 'error: no such course';
7579: }
7580: my $cstring='';
1.800 albertel 7581: foreach my $pref (keys(%prefs)) {
7582: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7583: }
1.84 www 7584: $cstring=~s/\&$//;
7585: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7586: }
7587:
7588: # ---------------------------------------------------------- Make/modify course
7589:
7590: sub createcourse {
1.741 raeburn 7591: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7592: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7593: $url=&declutter($url);
7594: my $cid='';
1.1028 raeburn 7595: if ($context eq 'requestcourses') {
7596: my $can_create = 0;
7597: my ($ownername,$ownerdom) = split(':',$course_owner);
7598: if ($udom eq $ownerdom) {
7599: if (&usertools_access($ownername,$ownerdom,$category,undef,
7600: $context)) {
7601: $can_create = 1;
7602: }
7603: } else {
7604: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7605: $category);
7606: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7607: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7608: if (@curr > 0) {
7609: my @options = qw(approval validate autolimit);
7610: my $optregex = join('|',@options);
7611: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7612: $can_create = 1;
7613: }
7614: }
7615: }
7616: }
7617: if ($can_create) {
7618: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7619: unless (&allowed('ccc',$udom)) {
7620: return 'refused';
7621: }
1.1017 raeburn 7622: }
7623: } else {
7624: return 'refused';
7625: }
1.1028 raeburn 7626: } elsif (!&allowed('ccc',$udom)) {
7627: return 'refused';
1.84 www 7628: }
1.1011 raeburn 7629: # --------------------------------------------------------------- Get Unique ID
7630: my $uname;
7631: if ($cnum =~ /^$match_courseid$/) {
7632: my $chome=&homeserver($cnum,$udom,'true');
7633: if (($chome eq '') || ($chome eq 'no_host')) {
7634: $uname = $cnum;
7635: } else {
1.1038 raeburn 7636: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7637: }
7638: } else {
1.1038 raeburn 7639: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7640: }
7641: return $uname if ($uname =~ /^error/);
7642: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7643: if (!defined($course_server)) {
7644: if (defined(&domain($udom,'primary'))) {
7645: $course_server = &domain($udom,'primary');
7646: } else {
7647: $course_server = $env{'user.home'};
7648: }
7649: }
7650: my %host_servers =
7651: &Apache::lonnet::get_servers($udom,'library');
7652: unless ($host_servers{$course_server}) {
7653: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7654: }
1.84 www 7655: # ------------------------------------------------------------- Make the course
7656: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7657: $course_server);
1.84 www 7658: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7659: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7660: if (($uhome eq '') || ($uhome eq 'no_host')) {
7661: return 'error: no such course';
7662: }
1.271 www 7663: # ----------------------------------------------------------------- Course made
1.516 raeburn 7664: # log existence
1.1029 raeburn 7665: my $now = time;
1.918 raeburn 7666: my $newcourse = {
7667: $udom.'_'.$uname => {
1.921 raeburn 7668: description => $description,
7669: inst_code => $inst_code,
7670: owner => $course_owner,
7671: type => $crstype,
1.1029 raeburn 7672: creator => $env{'user.name'}.':'.
7673: $env{'user.domain'},
7674: created => $now,
7675: context => $context,
1.918 raeburn 7676: },
7677: };
1.921 raeburn 7678: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7679: # set toplevel url
1.271 www 7680: my $topurl=$url;
7681: unless ($nonstandard) {
7682: # ------------------------------------------ For standard courses, make top url
7683: my $mapurl=&clutter($url);
1.278 www 7684: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7685: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7686: <map>
7687: <resource id="1" type="start"></resource>
7688: <resource id="2" src="$mapurl"></resource>
7689: <resource id="3" type="finish"></resource>
7690: <link index="1" from="1" to="2"></link>
7691: <link index="2" from="2" to="3"></link>
7692: </map>
7693: ENDINITMAP
7694: $topurl=&declutter(
1.638 albertel 7695: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7696: );
7697: }
7698: # ----------------------------------------------------------- Write preferences
1.84 www 7699: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7700: ('description' => $description,
7701: 'url' => $topurl,
7702: 'internal.creator' => $env{'user.name'}.':'.
7703: $env{'user.domain'},
7704: 'internal.created' => $now,
7705: 'internal.creationcontext' => $context)
7706: );
1.84 www 7707: return '/'.$udom.'/'.$uname;
7708: }
7709:
1.1011 raeburn 7710: # ------------------------------------------------------------------- Create ID
7711: sub generate_coursenum {
1.1038 raeburn 7712: my ($udom,$crstype) = @_;
1.1011 raeburn 7713: my $domdesc = &domain($udom);
7714: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7715: my $first;
7716: if ($crstype eq 'Community') {
7717: $first = '0';
7718: } else {
7719: $first = int(1+rand(9));
7720: }
7721: my $uname=$first.
1.1011 raeburn 7722: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7723: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7724: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7725: # ----------------------------------------------- Make sure that does not exist
7726: my $uhome=&homeserver($uname,$udom,'true');
7727: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7728: if ($crstype eq 'Community') {
7729: $first = '0';
7730: } else {
7731: $first = int(1+rand(9));
7732: }
7733: $uname=$first.
1.1011 raeburn 7734: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7735: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7736: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7737: $uhome=&homeserver($uname,$udom,'true');
7738: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7739: return 'error: unable to generate unique course-ID';
7740: }
7741: }
7742: return $uname;
7743: }
7744:
1.813 albertel 7745: sub is_course {
7746: my ($cdom,$cnum) = @_;
7747: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7748: undef,'.');
1.813 albertel 7749: if (exists($courses{$cdom.'_'.$cnum})) {
7750: return 1;
7751: }
7752: return 0;
7753: }
7754:
1.1015 raeburn 7755: sub store_userdata {
7756: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7757: my $result;
1.1016 raeburn 7758: if ($datakey ne '') {
1.1013 raeburn 7759: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7760: if ($udom eq '' || $uname eq '') {
7761: $udom = $env{'user.domain'};
7762: $uname = $env{'user.name'};
7763: }
7764: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7765: if (($uhome eq '') || ($uhome eq 'no_host')) {
7766: $result = 'error: no_host';
7767: } else {
7768: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7769: $storehash->{'host'} = $perlvar{'lonHostID'};
7770:
7771: my $namevalue='';
7772: foreach my $key (keys(%{$storehash})) {
7773: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7774: }
7775: $namevalue=~s/\&$//;
1.1105 raeburn 7776: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7777: $namevalue,$uhome);
1.1013 raeburn 7778: }
7779: } else {
7780: $result = 'error: data to store was not a hash reference';
7781: }
7782: } else {
7783: $result= 'error: invalid requestkey';
7784: }
7785: return $result;
7786: }
7787:
1.21 www 7788: # ---------------------------------------------------------- Assign Custom Role
7789:
7790: sub assigncustomrole {
1.957 raeburn 7791: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7792: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7793: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7794: }
7795:
7796: # ----------------------------------------------------------------- Revoke Role
7797:
7798: sub revokerole {
1.957 raeburn 7799: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7800: my $now=time;
1.965 raeburn 7801: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7802: }
7803:
7804: # ---------------------------------------------------------- Revoke Custom Role
7805:
7806: sub revokecustomrole {
1.957 raeburn 7807: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7808: my $now=time;
1.357 www 7809: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7810: $deleteflag,$selfenroll,$context);
1.17 www 7811: }
7812:
1.533 banghart 7813: # ------------------------------------------------------------ Disk usage
1.535 albertel 7814: sub diskusage {
1.955 raeburn 7815: my ($udom,$uname,$directorypath,$getpropath)=@_;
7816: $directorypath =~ s/\/$//;
7817: my $listing=&reply('du2:'.&escape($directorypath).':'
7818: .&escape($getpropath).':'.&escape($uname).':'
7819: .&escape($udom),homeserver($uname,$udom));
7820: if ($listing eq 'unknown_cmd') {
7821: if ($getpropath) {
7822: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7823: }
7824: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7825: }
1.514 albertel 7826: return $listing;
1.512 banghart 7827: }
7828:
1.566 banghart 7829: sub is_locked {
1.1096 raeburn 7830: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 7831: my @check;
7832: my $is_locked;
1.1093 raeburn 7833: push (@check,$file_name);
1.613 albertel 7834: my %locked = &get('file_permissions',\@check,
1.620 albertel 7835: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7836: my ($tmp)=keys(%locked);
7837: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7838:
1.566 banghart 7839: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7840: $is_locked = 'false';
7841: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 7842: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7843: $is_locked = 'true';
1.1096 raeburn 7844: if (ref($which) eq 'ARRAY') {
7845: push(@{$which},$entry);
7846: } else {
7847: last;
7848: }
1.745 raeburn 7849: }
7850: }
1.566 banghart 7851: } else {
7852: $is_locked = 'false';
7853: }
1.1093 raeburn 7854: return $is_locked;
1.566 banghart 7855: }
7856:
1.759 albertel 7857: sub declutter_portfile {
7858: my ($file) = @_;
1.833 albertel 7859: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7860: return $file;
7861: }
7862:
1.559 banghart 7863: # ------------------------------------------------------------- Mark as Read Only
7864:
7865: sub mark_as_readonly {
7866: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7867: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7868: my ($tmp)=keys(%current_permissions);
7869: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7870: foreach my $file (@{$files}) {
1.759 albertel 7871: $file = &declutter_portfile($file);
1.561 banghart 7872: push(@{$current_permissions{$file}},$what);
1.559 banghart 7873: }
1.613 albertel 7874: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7875: return;
7876: }
7877:
1.572 banghart 7878: # ------------------------------------------------------------Save Selected Files
7879:
7880: sub save_selected_files {
7881: my ($user, $path, @files) = @_;
7882: my $filename = $user."savedfiles";
1.573 banghart 7883: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7884: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7885: foreach my $file (@files) {
1.620 albertel 7886: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7887: }
7888: foreach my $file (@other_files) {
1.574 banghart 7889: print (OUT $file."\n");
1.572 banghart 7890: }
1.574 banghart 7891: close (OUT);
1.572 banghart 7892: return 'ok';
7893: }
7894:
1.574 banghart 7895: sub clear_selected_files {
7896: my ($user) = @_;
7897: my $filename = $user."savedfiles";
1.1117 foxr 7898: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 7899: print (OUT undef);
7900: close (OUT);
7901: return ("ok");
7902: }
7903:
1.572 banghart 7904: sub files_in_path {
7905: my ($user, $path) = @_;
7906: my $filename = $user."savedfiles";
7907: my %return_files;
1.1117 foxr 7908: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 7909: while (my $line_in = <IN>) {
1.574 banghart 7910: chomp ($line_in);
7911: my @paths_and_file = split (m!/!, $line_in);
7912: my $file_part = pop (@paths_and_file);
7913: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7914: $path_part.='/';
7915: my $path_and_file = $path_part.$file_part;
7916: if ($path_part eq $path) {
7917: $return_files{$file_part}= 'selected';
7918: }
7919: }
1.574 banghart 7920: close (IN);
7921: return (\%return_files);
1.572 banghart 7922: }
7923:
7924: # called in portfolio select mode, to show files selected NOT in current directory
7925: sub files_not_in_path {
7926: my ($user, $path) = @_;
7927: my $filename = $user."savedfiles";
7928: my @return_files;
7929: my $path_part;
1.1117 foxr 7930: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 7931: while (my $line = <IN>) {
1.572 banghart 7932: #ok, I know it's clunky, but I want it to work
1.800 albertel 7933: my @paths_and_file = split(m|/|, $line);
7934: my $file_part = pop(@paths_and_file);
7935: chomp($file_part);
7936: my $path_part = join('/', @paths_and_file);
1.572 banghart 7937: $path_part .= '/';
7938: my $path_and_file = $path_part.$file_part;
7939: if ($path_part ne $path) {
1.800 albertel 7940: push(@return_files, ($path_and_file));
1.572 banghart 7941: }
7942: }
1.800 albertel 7943: close(OUT);
1.574 banghart 7944: return (@return_files);
1.572 banghart 7945: }
7946:
1.745 raeburn 7947: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7948:
1.745 raeburn 7949: sub get_portfile_permissions {
7950: my ($domain,$user) = @_;
1.613 albertel 7951: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7952: my ($tmp)=keys(%current_permissions);
7953: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7954: return \%current_permissions;
7955: }
7956:
7957: #---------------------------------------------Get portfolio file access controls
7958:
1.749 raeburn 7959: sub get_access_controls {
1.745 raeburn 7960: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7961: my %access;
7962: my $real_file = $file;
7963: $file =~ s/\.meta$//;
1.745 raeburn 7964: if (defined($file)) {
1.749 raeburn 7965: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7966: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7967: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7968: }
7969: }
1.745 raeburn 7970: } else {
1.749 raeburn 7971: foreach my $key (keys(%{$current_permissions})) {
7972: if ($key =~ /\0accesscontrol$/) {
7973: if (defined($group)) {
7974: if ($key !~ m-^\Q$group\E/-) {
7975: next;
7976: }
7977: }
7978: my ($fullpath) = split(/\0/,$key);
7979: if (ref($$current_permissions{$key}) eq 'HASH') {
7980: foreach my $control (keys(%{$$current_permissions{$key}})) {
7981: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7982: }
7983: }
7984: }
7985: }
7986: }
7987: return %access;
7988: }
7989:
7990: sub modify_access_controls {
7991: my ($file_name,$changes,$domain,$user)=@_;
7992: my ($outcome,$deloutcome);
7993: my %store_permissions;
7994: my %new_values;
7995: my %new_control;
7996: my %translation;
7997: my @deletions = ();
7998: my $now = time;
7999: if (exists($$changes{'activate'})) {
8000: if (ref($$changes{'activate'}) eq 'HASH') {
8001: my @newitems = sort(keys(%{$$changes{'activate'}}));
8002: my $numnew = scalar(@newitems);
8003: for (my $i=0; $i<$numnew; $i++) {
8004: my $newkey = $newitems[$i];
8005: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 8006: if ($newkey =~ /^\d+:/) {
8007: $newkey =~ s/^(\d+)/$newid/;
8008: $translation{$1} = $newid;
8009: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8010: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8011: $translation{$1} = $newid;
8012: }
1.749 raeburn 8013: $new_values{$file_name."\0".$newkey} =
8014: $$changes{'activate'}{$newitems[$i]};
8015: $new_control{$newkey} = $now;
8016: }
8017: }
8018: }
8019: my %todelete;
8020: my %changed_items;
8021: foreach my $action ('delete','update') {
8022: if (exists($$changes{$action})) {
8023: if (ref($$changes{$action}) eq 'HASH') {
8024: foreach my $key (keys(%{$$changes{$action}})) {
8025: my ($itemnum) = ($key =~ /^([^:]+):/);
8026: if ($action eq 'delete') {
8027: $todelete{$itemnum} = 1;
8028: } else {
8029: $changed_items{$itemnum} = $key;
8030: }
8031: }
1.745 raeburn 8032: }
8033: }
1.749 raeburn 8034: }
8035: # get lock on access controls for file.
8036: my $lockhash = {
8037: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8038: ':'.$env{'user.domain'},
8039: };
8040: my $tries = 0;
8041: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8042:
8043: while (($gotlock ne 'ok') && $tries <3) {
8044: $tries ++;
8045: sleep 1;
8046: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8047: }
8048: if ($gotlock eq 'ok') {
8049: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8050: my ($tmp)=keys(%curr_permissions);
8051: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8052: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8053: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8054: if (ref($curr_controls) eq 'HASH') {
8055: foreach my $control_item (keys(%{$curr_controls})) {
8056: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8057: if (defined($todelete{$itemnum})) {
8058: push(@deletions,$file_name."\0".$control_item);
8059: } else {
8060: if (defined($changed_items{$itemnum})) {
8061: $new_control{$changed_items{$itemnum}} = $now;
8062: push(@deletions,$file_name."\0".$control_item);
8063: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8064: } else {
8065: $new_control{$control_item} = $$curr_controls{$control_item};
8066: }
8067: }
1.745 raeburn 8068: }
8069: }
8070: }
1.970 raeburn 8071: my ($group);
8072: if (&is_course($domain,$user)) {
8073: ($group,my $file) = split(/\//,$file_name,2);
8074: }
1.749 raeburn 8075: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8076: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8077: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8078: # remove lock
8079: my @del_lock = ($file_name."\0".'locked_access_records');
8080: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 8081: my $sqlresult =
1.970 raeburn 8082: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 8083: $group);
1.749 raeburn 8084: } else {
8085: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 8086: }
1.749 raeburn 8087: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 8088: }
8089:
1.827 raeburn 8090: sub make_public_indefinitely {
8091: my ($requrl) = @_;
8092: my $now = time;
8093: my $action = 'activate';
8094: my $aclnum = 0;
8095: if (&is_portfolio_url($requrl)) {
8096: my (undef,$udom,$unum,$file_name,$group) =
8097: &parse_portfolio_url($requrl);
8098: my $current_perms = &get_portfile_permissions($udom,$unum);
8099: my %access_controls = &get_access_controls($current_perms,
8100: $group,$file_name);
8101: foreach my $key (keys(%{$access_controls{$file_name}})) {
8102: my ($num,$scope,$end,$start) =
8103: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8104: if ($scope eq 'public') {
8105: if ($start <= $now && $end == 0) {
8106: $action = 'none';
8107: } else {
8108: $action = 'update';
8109: $aclnum = $num;
8110: }
8111: last;
8112: }
8113: }
8114: if ($action eq 'none') {
8115: return 'ok';
8116: } else {
8117: my %changes;
8118: my $newend = 0;
8119: my $newstart = $now;
8120: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8121: $changes{$action}{$newkey} = {
8122: type => 'public',
8123: time => {
8124: start => $newstart,
8125: end => $newend,
8126: },
8127: };
8128: my ($outcome,$deloutcome,$new_values,$translation) =
8129: &modify_access_controls($file_name,\%changes,$udom,$unum);
8130: return $outcome;
8131: }
8132: } else {
8133: return 'invalid';
8134: }
8135: }
8136:
1.745 raeburn 8137: #------------------------------------------------------Get Marked as Read Only
8138:
8139: sub get_marked_as_readonly {
8140: my ($domain,$user,$what,$group) = @_;
8141: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 8142: my @readonly_files;
1.629 banghart 8143: my $cmp1=$what;
8144: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 8145: while (my ($file_name,$value) = each(%{$current_permissions})) {
8146: if (defined($group)) {
8147: if ($file_name !~ m-^\Q$group\E/-) {
8148: next;
8149: }
8150: }
1.561 banghart 8151: if (ref($value) eq "ARRAY"){
8152: foreach my $stored_what (@{$value}) {
1.629 banghart 8153: my $cmp2=$stored_what;
1.759 albertel 8154: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 8155: $cmp2=join('',@{$stored_what});
1.745 raeburn 8156: }
1.629 banghart 8157: if ($cmp1 eq $cmp2) {
1.561 banghart 8158: push(@readonly_files, $file_name);
1.745 raeburn 8159: last;
1.563 banghart 8160: } elsif (!defined($what)) {
8161: push(@readonly_files, $file_name);
1.745 raeburn 8162: last;
1.561 banghart 8163: }
8164: }
1.745 raeburn 8165: }
1.561 banghart 8166: }
8167: return @readonly_files;
8168: }
1.577 banghart 8169: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 8170:
1.577 banghart 8171: sub get_marked_as_readonly_hash {
1.745 raeburn 8172: my ($current_permissions,$group,$what) = @_;
1.577 banghart 8173: my %readonly_files;
1.745 raeburn 8174: while (my ($file_name,$value) = each(%{$current_permissions})) {
8175: if (defined($group)) {
8176: if ($file_name !~ m-^\Q$group\E/-) {
8177: next;
8178: }
8179: }
1.577 banghart 8180: if (ref($value) eq "ARRAY"){
8181: foreach my $stored_what (@{$value}) {
1.745 raeburn 8182: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 8183: foreach my $lock_descriptor(@{$stored_what}) {
8184: if ($lock_descriptor eq 'graded') {
8185: $readonly_files{$file_name} = 'graded';
8186: } elsif ($lock_descriptor eq 'handback') {
8187: $readonly_files{$file_name} = 'handback';
8188: } else {
8189: if (!exists($readonly_files{$file_name})) {
8190: $readonly_files{$file_name} = 'locked';
8191: }
8192: }
1.745 raeburn 8193: }
1.750 banghart 8194: }
1.577 banghart 8195: }
8196: }
8197: }
8198: return %readonly_files;
8199: }
1.559 banghart 8200: # ------------------------------------------------------------ Unmark as Read Only
8201:
8202: sub unmark_as_readonly {
1.629 banghart 8203: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8204: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 8205: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 8206: $file_name = &declutter_portfile($file_name);
1.634 albertel 8207: my $symb_crs = $what;
8208: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 8209: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 8210: my ($tmp)=keys(%current_permissions);
8211: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8212: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 8213: foreach my $file (@readonly_files) {
1.759 albertel 8214: my $clean_file = &declutter_portfile($file);
8215: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 8216: my $current_locks = $current_permissions{$file};
1.563 banghart 8217: my @new_locks;
8218: my @del_keys;
8219: if (ref($current_locks) eq "ARRAY"){
8220: foreach my $locker (@{$current_locks}) {
1.632 albertel 8221: my $compare=$locker;
1.749 raeburn 8222: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 8223: $compare=join('',@{$locker});
1.746 raeburn 8224: if ($compare ne $symb_crs) {
8225: push(@new_locks, $locker);
8226: }
1.563 banghart 8227: }
8228: }
1.650 albertel 8229: if (scalar(@new_locks) > 0) {
1.563 banghart 8230: $current_permissions{$file} = \@new_locks;
8231: } else {
8232: push(@del_keys, $file);
1.613 albertel 8233: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 8234: delete($current_permissions{$file});
1.563 banghart 8235: }
8236: }
1.561 banghart 8237: }
1.613 albertel 8238: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8239: return;
8240: }
1.512 banghart 8241:
1.17 www 8242: # ------------------------------------------------------------ Directory lister
8243:
8244: sub dirlist {
1.955 raeburn 8245: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 8246: $uri=~s/^\///;
8247: $uri=~s/\/$//;
1.253 stredwic 8248: my ($udom, $uname);
1.955 raeburn 8249: if ($getuserdir) {
1.253 stredwic 8250: $udom = $userdomain;
8251: $uname = $username;
1.955 raeburn 8252: } else {
8253: (undef,$udom,$uname)=split(/\//,$uri);
8254: if(defined($userdomain)) {
8255: $udom = $userdomain;
8256: }
8257: if(defined($username)) {
8258: $uname = $username;
8259: }
1.253 stredwic 8260: }
1.955 raeburn 8261: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 8262:
1.955 raeburn 8263: $dirRoot = $perlvar{'lonDocRoot'};
8264: if (defined($getpropath)) {
8265: $dirRoot = &propath($udom,$uname);
1.253 stredwic 8266: $dirRoot =~ s/\/$//;
1.955 raeburn 8267: } elsif (defined($getuserdir)) {
8268: my $subdir=$uname.'__';
8269: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8270: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8271: ."/$udom/$subdir/$uname";
8272: } elsif (defined($alternateRoot)) {
8273: $dirRoot = $alternateRoot;
1.751 banghart 8274: }
1.253 stredwic 8275:
8276: if($udom) {
8277: if($uname) {
1.1135 raeburn 8278: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 8279: if ($uhome eq 'no_host') {
8280: return ([],'no_host');
8281: }
1.955 raeburn 8282: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 8283: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 8284: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 8285: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8286: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 8287: } else {
8288: @listing_results = map { &unescape($_); } split(/:/,$listing);
8289: }
1.605 matthew 8290: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8291: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 8292: @listing_results = split(/:/,$listing);
8293: } else {
8294: @listing_results = map { &unescape($_); } split(/:/,$listing);
8295: }
1.1135 raeburn 8296: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 8297: ($listing eq 'rejected') || ($listing eq 'refused') ||
8298: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8299: return ([],$listing);
8300: } else {
8301: return (\@listing_results);
1.1135 raeburn 8302: }
1.955 raeburn 8303: } elsif(!$alternateRoot) {
1.1136 raeburn 8304: my (%allusers,%listerror);
1.841 albertel 8305: my %servers = &get_servers($udom,'library');
1.955 raeburn 8306: foreach my $tryserver (keys(%servers)) {
8307: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8308: &escape($udom),$tryserver);
8309: if ($listing eq 'unknown_cmd') {
8310: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8311: $udom, $tryserver);
8312: } else {
8313: @listing_results = map { &unescape($_); } split(/:/,$listing);
8314: }
1.841 albertel 8315: if ($listing eq 'unknown_cmd') {
8316: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8317: $udom, $tryserver);
8318: @listing_results = split(/:/,$listing);
8319: } else {
8320: @listing_results =
8321: map { &unescape($_); } split(/:/,$listing);
8322: }
1.1136 raeburn 8323: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8324: ($listing eq 'rejected') || ($listing eq 'refused') ||
8325: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8326: $listerror{$tryserver} = $listing;
8327: } else {
1.841 albertel 8328: foreach my $line (@listing_results) {
8329: my ($entry) = split(/&/,$line,2);
8330: $allusers{$entry} = 1;
8331: }
8332: }
1.253 stredwic 8333: }
1.1136 raeburn 8334: my @alluserslist=();
1.800 albertel 8335: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 8336: push(@alluserslist,$user.'&user');
1.253 stredwic 8337: }
1.1136 raeburn 8338: return (\@alluserslist);
1.253 stredwic 8339: } else {
1.1136 raeburn 8340: return ([],'missing username');
1.253 stredwic 8341: }
1.955 raeburn 8342: } elsif(!defined($getpropath)) {
1.1136 raeburn 8343: my $path = $perlvar{'lonDocRoot'}.'/res/';
8344: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8345: return (\@all_domains);
1.955 raeburn 8346: } else {
1.1136 raeburn 8347: return ([],'missing domain');
1.275 stredwic 8348: }
8349: }
8350:
8351: # --------------------------------------------- GetFileTimestamp
8352: # This function utilizes dirlist and returns the date stamp for
8353: # when it was last modified. It will also return an error of -1
8354: # if an error occurs
8355:
8356: sub GetFileTimestamp {
1.955 raeburn 8357: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 8358: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8359: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 8360: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8361: undef,$getuserdir);
8362: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8363: return -1;
8364: }
8365: if (ref($fileref) eq 'ARRAY') {
8366: my @stats = split('&',$fileref->[0]);
1.375 matthew 8367: # @stats contains first the filename, then the stat output
8368: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 8369: } else {
8370: return -1;
1.253 stredwic 8371: }
1.26 www 8372: }
8373:
1.712 albertel 8374: sub stat_file {
8375: my ($uri) = @_;
1.787 albertel 8376: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 8377:
1.955 raeburn 8378: my ($udom,$uname,$file);
1.712 albertel 8379: if ($uri =~ m-^/(uploaded|editupload)/-) {
8380: ($udom,$uname,$file) =
1.811 albertel 8381: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 8382: $file = 'userfiles/'.$file;
8383: }
8384: if ($uri =~ m-^/res/-) {
8385: ($udom,$uname) =
1.807 albertel 8386: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 8387: $file = $uri;
8388: }
8389:
8390: if (!$udom || !$uname || !$file) {
8391: # unable to handle the uri
8392: return ();
8393: }
1.956 raeburn 8394: my $getpropath;
8395: if ($file =~ /^userfiles\//) {
8396: $getpropath = 1;
8397: }
1.1136 raeburn 8398: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8399: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8400: return ();
8401: } else {
8402: if (ref($listref) eq 'ARRAY') {
8403: my @stats = split('&',$listref->[0]);
8404: shift(@stats); #filename is first
8405: return @stats;
8406: }
1.712 albertel 8407: }
8408: return ();
8409: }
8410:
1.26 www 8411: # -------------------------------------------------------- Value of a Condition
8412:
1.713 albertel 8413: # gets the value of a specific preevaluated condition
8414: # stored in the string $env{user.state.<cid>}
8415: # or looks up a condition reference in the bighash and if if hasn't
8416: # already been evaluated recurses into docondval to get the value of
8417: # the condition, then memoizing it to
8418: # $env{user.state.<cid>.<condition>}
1.40 www 8419: sub directcondval {
8420: my $number=shift;
1.620 albertel 8421: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8422: &Apache::lonuserstate::evalstate();
8423: }
1.713 albertel 8424: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8425: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8426: } elsif ($number =~ /^_/) {
8427: my $sub_condition;
8428: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8429: &GDBM_READER(),0640)) {
8430: $sub_condition=$bighash{'conditions'.$number};
8431: untie(%bighash);
8432: }
8433: my $value = &docondval($sub_condition);
1.949 raeburn 8434: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8435: return $value;
8436: }
1.620 albertel 8437: if ($env{'user.state.'.$env{'request.course.id'}}) {
8438: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8439: } else {
8440: return 2;
8441: }
8442: }
8443:
1.713 albertel 8444: # get the collection of conditions for this resource
1.26 www 8445: sub condval {
8446: my $condidx=shift;
1.54 www 8447: my $allpathcond='';
1.713 albertel 8448: foreach my $cond (split(/\|/,$condidx)) {
8449: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8450: $allpathcond.=
8451: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8452: }
1.191 harris41 8453: }
1.54 www 8454: $allpathcond=~s/\|$//;
1.713 albertel 8455: return &docondval($allpathcond);
8456: }
8457:
8458: #evaluates an expression of conditions
8459: sub docondval {
8460: my ($allpathcond) = @_;
8461: my $result=0;
8462: if ($env{'request.course.id'}
8463: && defined($allpathcond)) {
8464: my $operand='|';
8465: my @stack;
8466: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8467: if ($chunk eq '(') {
8468: push @stack,($operand,$result);
8469: } elsif ($chunk eq ')') {
8470: my $before=pop @stack;
8471: if (pop @stack eq '&') {
8472: $result=$result>$before?$before:$result;
8473: } else {
8474: $result=$result>$before?$result:$before;
8475: }
8476: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8477: $operand=$chunk;
8478: } else {
8479: my $new=directcondval($chunk);
8480: if ($operand eq '&') {
8481: $result=$result>$new?$new:$result;
8482: } else {
8483: $result=$result>$new?$result:$new;
8484: }
8485: }
8486: }
1.26 www 8487: }
8488: return $result;
1.421 albertel 8489: }
8490:
8491: # ---------------------------------------------------- Devalidate courseresdata
8492:
8493: sub devalidatecourseresdata {
8494: my ($coursenum,$coursedomain)=@_;
8495: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8496: &devalidate_cache_new('courseres',$hashid);
1.28 www 8497: }
8498:
1.763 www 8499:
1.200 www 8500: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8501: #
8502: # Parameters:
8503: # $coursenum - Number of the course.
8504: # $coursedomain - Domain at which the course was created.
8505: # Returns:
8506: # A hash of the course parameters along (I think) with timestamps
8507: # and version info.
1.877 foxr 8508:
1.624 albertel 8509: sub get_courseresdata {
8510: my ($coursenum,$coursedomain)=@_;
1.200 www 8511: my $coursehom=&homeserver($coursenum,$coursedomain);
8512: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8513: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8514: my %dumpreply;
1.417 albertel 8515: unless (defined($cached)) {
1.624 albertel 8516: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8517: $result=\%dumpreply;
1.251 albertel 8518: my ($tmp) = keys(%dumpreply);
8519: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8520: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8521: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8522: return $tmp;
1.416 albertel 8523: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8524: $result=undef;
1.599 albertel 8525: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8526: }
8527: }
1.624 albertel 8528: return $result;
8529: }
8530:
1.633 albertel 8531: sub devalidateuserresdata {
8532: my ($uname,$udom)=@_;
8533: my $hashid="$udom:$uname";
8534: &devalidate_cache_new('userres',$hashid);
8535: }
8536:
1.624 albertel 8537: sub get_userresdata {
8538: my ($uname,$udom)=@_;
8539: #most student don\'t have any data set, check if there is some data
8540: if (&EXT_cache_status($udom,$uname)) { return undef; }
8541:
8542: my $hashid="$udom:$uname";
8543: my ($result,$cached)=&is_cached_new('userres',$hashid);
8544: if (!defined($cached)) {
8545: my %resourcedata=&dump('resourcedata',$udom,$uname);
8546: $result=\%resourcedata;
8547: &do_cache_new('userres',$hashid,$result,600);
8548: }
8549: my ($tmp)=keys(%$result);
8550: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8551: return $result;
8552: }
8553: #error 2 occurs when the .db doesn't exist
8554: if ($tmp!~/error: 2 /) {
1.672 albertel 8555: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8556: " Trying to get resource data for ".
8557: $uname." at ".$udom.": ".
8558: $tmp."</font>");
8559: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8560: #&EXT_cache_set($udom,$uname);
8561: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8562: undef($tmp); # not really an error so don't send it back
1.624 albertel 8563: }
8564: return $tmp;
8565: }
1.879 foxr 8566: #----------------------------------------------- resdata - return resource data
8567: # Purpose:
8568: # Return resource data for either users or for a course.
8569: # Parameters:
8570: # $name - Course/user name.
8571: # $domain - Name of the domain the user/course is registered on.
8572: # $type - Type of thing $name is (must be 'course' or 'user'
8573: # @which - Array of names of resources desired.
8574: # Returns:
8575: # The value of the first reasource in @which that is found in the
8576: # resource hash.
8577: # Exceptional Conditions:
8578: # If the $type passed in is not valid (not the string 'course' or
8579: # 'user', an undefined reference is returned.
8580: # If none of the resources are found, an undef is returned
1.624 albertel 8581: sub resdata {
8582: my ($name,$domain,$type,@which)=@_;
8583: my $result;
8584: if ($type eq 'course') {
8585: $result=&get_courseresdata($name,$domain);
8586: } elsif ($type eq 'user') {
8587: $result=&get_userresdata($name,$domain);
8588: }
8589: if (!ref($result)) { return $result; }
1.251 albertel 8590: foreach my $item (@which) {
1.927 albertel 8591: if (defined($result->{$item->[0]})) {
8592: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8593: }
1.250 albertel 8594: }
1.291 albertel 8595: return undef;
1.200 www 8596: }
8597:
1.379 matthew 8598: #
8599: # EXT resource caching routines
8600: #
8601:
8602: sub clear_EXT_cache_status {
1.383 albertel 8603: &delenv('cache.EXT.');
1.379 matthew 8604: }
8605:
8606: sub EXT_cache_status {
8607: my ($target_domain,$target_user) = @_;
1.383 albertel 8608: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8609: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8610: # We know already the user has no data
8611: return 1;
8612: } else {
8613: return 0;
8614: }
8615: }
8616:
8617: sub EXT_cache_set {
8618: my ($target_domain,$target_user) = @_;
1.383 albertel 8619: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8620: #&appenv({$cachename => time});
1.379 matthew 8621: }
8622:
1.28 www 8623: # --------------------------------------------------------- Value of a Variable
1.58 www 8624: sub EXT {
1.715 albertel 8625:
1.395 albertel 8626: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8627: unless ($varname) { return ''; }
1.218 albertel 8628: #get real user name/domain, courseid and symb
8629: my $courseid;
1.359 albertel 8630: my $publicuser;
1.427 www 8631: if ($symbparm) {
8632: $symbparm=&get_symb_from_alias($symbparm);
8633: }
1.218 albertel 8634: if (!($uname && $udom)) {
1.790 albertel 8635: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8636: if (!$symbparm) { $symbparm=$cursymb; }
8637: } else {
1.620 albertel 8638: $courseid=$env{'request.course.id'};
1.218 albertel 8639: }
1.48 www 8640: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8641: my $rest;
1.320 albertel 8642: if (defined($therest[0])) {
1.48 www 8643: $rest=join('.',@therest);
8644: } else {
8645: $rest='';
8646: }
1.320 albertel 8647:
1.57 www 8648: my $qualifierrest=$qualifier;
8649: if ($rest) { $qualifierrest.='.'.$rest; }
8650: my $spacequalifierrest=$space;
8651: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8652: if ($realm eq 'user') {
1.48 www 8653: # --------------------------------------------------------------- user.resource
8654: if ($space eq 'resource') {
1.651 albertel 8655: if ( (defined($Apache::lonhomework::parsing_a_problem)
8656: || defined($Apache::lonhomework::parsing_a_task))
8657: &&
1.744 albertel 8658: ($symbparm eq &symbread()) ) {
8659: # if we are in the middle of processing the resource the
8660: # get the value we are planning on committing
8661: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8662: return $Apache::lonhomework::results{$qualifierrest};
8663: } else {
8664: return $Apache::lonhomework::history{$qualifierrest};
8665: }
1.335 albertel 8666: } else {
1.359 albertel 8667: my %restored;
1.620 albertel 8668: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8669: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8670: } else {
8671: %restored=&restore($symbparm,$courseid,$udom,$uname);
8672: }
1.335 albertel 8673: return $restored{$qualifierrest};
8674: }
1.48 www 8675: # ----------------------------------------------------------------- user.access
8676: } elsif ($space eq 'access') {
1.218 albertel 8677: # FIXME - not supporting calls for a specific user
1.48 www 8678: return &allowed($qualifier,$rest);
8679: # ------------------------------------------ user.preferences, user.environment
8680: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8681: if (($uname eq $env{'user.name'}) &&
8682: ($udom eq $env{'user.domain'})) {
8683: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8684: } else {
1.359 albertel 8685: my %returnhash;
8686: if (!$publicuser) {
8687: %returnhash=&userenvironment($udom,$uname,
8688: $qualifierrest);
8689: }
1.218 albertel 8690: return $returnhash{$qualifierrest};
8691: }
1.48 www 8692: # ----------------------------------------------------------------- user.course
8693: } elsif ($space eq 'course') {
1.218 albertel 8694: # FIXME - not supporting calls for a specific user
1.620 albertel 8695: return $env{join('.',('request.course',$qualifier))};
1.48 www 8696: # ------------------------------------------------------------------- user.role
8697: } elsif ($space eq 'role') {
1.218 albertel 8698: # FIXME - not supporting calls for a specific user
1.620 albertel 8699: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8700: if ($qualifier eq 'value') {
8701: return $role;
8702: } elsif ($qualifier eq 'extent') {
8703: return $where;
8704: }
8705: # ----------------------------------------------------------------- user.domain
8706: } elsif ($space eq 'domain') {
1.218 albertel 8707: return $udom;
1.48 www 8708: # ------------------------------------------------------------------- user.name
8709: } elsif ($space eq 'name') {
1.218 albertel 8710: return $uname;
1.48 www 8711: # ---------------------------------------------------- Any other user namespace
1.29 www 8712: } else {
1.359 albertel 8713: my %reply;
8714: if (!$publicuser) {
8715: %reply=&get($space,[$qualifierrest],$udom,$uname);
8716: }
8717: return $reply{$qualifierrest};
1.48 www 8718: }
1.236 www 8719: } elsif ($realm eq 'query') {
8720: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8721: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8722: [$spacequalifierrest]);
1.620 albertel 8723: return $env{'form.'.$spacequalifierrest};
1.236 www 8724: } elsif ($realm eq 'request') {
1.48 www 8725: # ------------------------------------------------------------- request.browser
8726: if ($space eq 'browser') {
1.1145 bisitz 8727: return $env{'browser.'.$qualifier};
1.57 www 8728: # ------------------------------------------------------------ request.filename
8729: } else {
1.620 albertel 8730: return $env{'request.'.$spacequalifierrest};
1.29 www 8731: }
1.28 www 8732: } elsif ($realm eq 'course') {
1.48 www 8733: # ---------------------------------------------------------- course.description
1.620 albertel 8734: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8735: } elsif ($realm eq 'resource') {
1.165 www 8736:
1.620 albertel 8737: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8738: if (!$symbparm) { $symbparm=&symbread(); }
8739: }
1.693 albertel 8740:
8741: if ($space eq 'title') {
8742: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8743: return &gettitle($symbparm);
8744: }
8745:
8746: if ($space eq 'map') {
8747: my ($map) = &decode_symb($symbparm);
8748: return &symbread($map);
8749: }
1.905 albertel 8750: if ($space eq 'filename') {
8751: if ($symbparm) {
8752: return &clutter((&decode_symb($symbparm))[2]);
8753: }
8754: return &hreflocation('',$env{'request.filename'});
8755: }
1.693 albertel 8756:
8757: my ($section, $group, @groups);
1.593 albertel 8758: my ($courselevelm,$courselevel);
1.539 albertel 8759: if ($symbparm && defined($courseid) &&
1.620 albertel 8760: $courseid eq $env{'request.course.id'}) {
1.165 www 8761:
1.218 albertel 8762: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8763:
1.60 www 8764: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8765: my $symbp=$symbparm;
1.735 albertel 8766: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8767:
8768: my $symbparm=$symbp.'.'.$spacequalifierrest;
8769: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8770:
1.620 albertel 8771: if (($env{'user.name'} eq $uname) &&
8772: ($env{'user.domain'} eq $udom)) {
8773: $section=$env{'request.course.sec'};
1.733 raeburn 8774: @groups = split(/:/,$env{'request.course.groups'});
8775: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8776: } else {
1.539 albertel 8777: if (! defined($usection)) {
1.551 albertel 8778: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8779: } else {
8780: $section = $usection;
8781: }
1.733 raeburn 8782: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8783: }
8784:
8785: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8786: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8787: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8788:
1.593 albertel 8789: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8790: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8791: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8792:
1.60 www 8793: # ----------------------------------------------------------- first, check user
1.624 albertel 8794:
8795: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8796: ([$courselevelr,'resource'],
8797: [$courselevelm,'map' ],
8798: [$courselevel, 'course' ]));
1.931 albertel 8799: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8800:
1.594 albertel 8801: # ------------------------------------------------ second, check some of course
1.684 raeburn 8802: my $coursereply;
1.691 raeburn 8803: if (@groups > 0) {
8804: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8805: $mapparm,$spacequalifierrest);
1.927 albertel 8806: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8807: }
1.96 www 8808:
1.684 raeburn 8809: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8810: $env{'course.'.$courseid.'.domain'},
8811: 'course',
8812: ([$seclevelr, 'resource'],
8813: [$seclevelm, 'map' ],
8814: [$seclevel, 'course' ],
8815: [$courselevelr,'resource']));
8816: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8817:
1.60 www 8818: # ------------------------------------------------------ third, check map parms
1.218 albertel 8819: my %parmhash=();
8820: my $thisparm='';
8821: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8822: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8823: &GDBM_READER(),0640)) {
1.218 albertel 8824: $thisparm=$parmhash{$symbparm};
8825: untie(%parmhash);
8826: }
1.927 albertel 8827: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8828: }
1.594 albertel 8829: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8830:
1.218 albertel 8831: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8832: my $filename;
8833: if (!$symbparm) { $symbparm=&symbread(); }
8834: if ($symbparm) {
1.409 www 8835: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8836: } else {
1.620 albertel 8837: $filename=$env{'request.filename'};
1.282 albertel 8838: }
8839: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8840: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8841: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8842: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8843:
1.927 albertel 8844: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8845: if ($symbparm && defined($courseid) &&
1.620 albertel 8846: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8847: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8848: $env{'course.'.$courseid.'.domain'},
8849: 'course',
1.927 albertel 8850: ([$courselevelm,'map' ],
8851: [$courselevel, 'course']));
8852: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8853: }
1.145 www 8854: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8855: unless ($space eq '0') {
1.336 albertel 8856: my @parts=split(/_/,$space);
8857: my $id=pop(@parts);
8858: my $part=join('_',@parts);
8859: if ($part eq '') { $part='0'; }
1.927 albertel 8860: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8861: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8862: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8863: }
1.395 albertel 8864: if ($recurse) { return undef; }
8865: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8866: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8867: # ---------------------------------------------------- Any other user namespace
8868: } elsif ($realm eq 'environment') {
8869: # ----------------------------------------------------------------- environment
1.620 albertel 8870: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8871: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8872: } else {
1.770 albertel 8873: if ($uname eq 'anonymous' && $udom eq '') {
8874: return '';
8875: }
1.219 albertel 8876: my %returnhash=&userenvironment($udom,$uname,
8877: $spacequalifierrest);
8878: return $returnhash{$spacequalifierrest};
8879: }
1.28 www 8880: } elsif ($realm eq 'system') {
1.48 www 8881: # ----------------------------------------------------------------- system.time
8882: if ($space eq 'time') {
8883: return time;
8884: }
1.696 albertel 8885: } elsif ($realm eq 'server') {
8886: # ----------------------------------------------------------------- system.time
8887: if ($space eq 'name') {
8888: return $ENV{'SERVER_NAME'};
8889: }
1.28 www 8890: }
1.48 www 8891: return '';
1.61 www 8892: }
8893:
1.927 albertel 8894: sub get_reply {
8895: my ($reply_value) = @_;
1.940 raeburn 8896: if (ref($reply_value) eq 'ARRAY') {
8897: if (wantarray) {
8898: return @$reply_value;
8899: }
8900: return $reply_value->[0];
8901: } else {
8902: return $reply_value;
1.927 albertel 8903: }
8904: }
8905:
1.691 raeburn 8906: sub check_group_parms {
8907: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8908: my @groupitems = ();
8909: my $resultitem;
1.927 albertel 8910: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8911: foreach my $group (@{$groups}) {
8912: foreach my $level (@levels) {
1.927 albertel 8913: my $item = $courseid.'.['.$group.'].'.$level->[0];
8914: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8915: }
8916: }
8917: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8918: $env{'course.'.$courseid.'.domain'},
8919: 'course',@groupitems);
8920: return $coursereply;
8921: }
8922:
8923: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8924: my ($courseid,@groups) = @_;
8925: @groups = sort(@groups);
1.691 raeburn 8926: return @groups;
8927: }
8928:
1.395 albertel 8929: sub packages_tab_default {
8930: my ($uri,$varname)=@_;
8931: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8932:
8933: my (@extension,@specifics,$do_default);
8934: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8935: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8936: if ($pack_type eq 'default') {
8937: $do_default=1;
8938: } elsif ($pack_type eq 'extension') {
8939: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8940: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8941: # only look at packages defaults for packages that this id is
1.738 albertel 8942: push(@specifics,[$package,$pack_type,$pack_part]);
8943: }
8944: }
8945: # first look for a package that matches the requested part id
8946: foreach my $package (@specifics) {
8947: my (undef,$pack_type,$pack_part)=@{$package};
8948: next if ($pack_part ne $part);
8949: if (defined($packagetab{"$pack_type&$name&default"})) {
8950: return $packagetab{"$pack_type&$name&default"};
8951: }
8952: }
8953: # look for any possible matching non extension_ package
8954: foreach my $package (@specifics) {
8955: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8956: if (defined($packagetab{"$pack_type&$name&default"})) {
8957: return $packagetab{"$pack_type&$name&default"};
8958: }
1.585 albertel 8959: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8960: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8961: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8962: }
8963: }
1.738 albertel 8964: # look for any posible extension_ match
8965: foreach my $package (@extension) {
8966: my ($package,$pack_type)=@{$package};
8967: if (defined($packagetab{"$pack_type&$name&default"})) {
8968: return $packagetab{"$pack_type&$name&default"};
8969: }
8970: if (defined($packagetab{$package."&$name&default"})) {
8971: return $packagetab{$package."&$name&default"};
8972: }
8973: }
8974: # look for a global default setting
8975: if ($do_default && defined($packagetab{"default&$name&default"})) {
8976: return $packagetab{"default&$name&default"};
8977: }
1.395 albertel 8978: return undef;
8979: }
8980:
1.334 albertel 8981: sub add_prefix_and_part {
8982: my ($prefix,$part)=@_;
8983: my $keyroot;
8984: if (defined($prefix) && $prefix !~ /^__/) {
8985: # prefix that has a part already
8986: $keyroot=$prefix;
8987: } elsif (defined($prefix)) {
8988: # prefix that is missing a part
8989: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8990: } else {
8991: # no prefix at all
8992: if (defined($part)) { $keyroot='_'.$part; }
8993: }
8994: return $keyroot;
8995: }
8996:
1.71 www 8997: # ---------------------------------------------------------------- Get metadata
8998:
1.599 albertel 8999: my %metaentry;
1.1070 www 9000: my %importedpartids;
1.71 www 9001: sub metadata {
1.176 www 9002: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 9003: $uri=&declutter($uri);
1.288 albertel 9004: # if it is a non metadata possible uri return quickly
1.529 albertel 9005: if (($uri eq '') ||
9006: (($uri =~ m|^/*adm/|) &&
1.698 albertel 9007: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108 raeburn 9008: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 9009: return undef;
9010: }
1.1140 www 9011: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 9012: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 9013: return undef;
1.288 albertel 9014: }
1.73 www 9015: my $filename=$uri;
9016: $uri=~s/\.meta$//;
1.172 www 9017: #
9018: # Is the metadata already cached?
1.177 www 9019: # Look at timestamp of caching
1.172 www 9020: # Everything is cached by the main uri, libraries are never directly cached
9021: #
1.428 albertel 9022: if (!defined($liburi)) {
1.599 albertel 9023: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 9024: if (defined($cached)) { return $result->{':'.$what}; }
9025: }
9026: {
1.1069 www 9027: # Imported parts would go here
1.1070 www 9028: my %importedids=();
9029: my @origfileimportpartids=();
1.1069 www 9030: my $importedparts=0;
1.172 www 9031: #
9032: # Is this a recursive call for a library?
9033: #
1.599 albertel 9034: # if (! exists($metacache{$uri})) {
9035: # $metacache{$uri}={};
9036: # }
1.924 albertel 9037: my $cachetime = 60*60;
1.171 www 9038: if ($liburi) {
9039: $liburi=&declutter($liburi);
9040: $filename=$liburi;
1.401 bowersj2 9041: } else {
1.599 albertel 9042: &devalidate_cache_new('meta',$uri);
9043: undef(%metaentry);
1.401 bowersj2 9044: }
1.140 www 9045: my %metathesekeys=();
1.73 www 9046: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 9047: my $metastring;
1.1140 www 9048: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 9049: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 9050: $metastring =
1.929 albertel 9051: &Apache::lonnet::ssi_body($which,
1.924 albertel 9052: ('grade_target' => 'meta'));
9053: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 9054: } elsif (($uri !~ m -^(editupload)/-) &&
9055: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 9056: my $file=&filelocation('',&clutter($filename));
1.599 albertel 9057: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 9058: $metastring=&getfile($file);
1.489 albertel 9059: }
1.208 albertel 9060: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 9061: my $token;
1.140 www 9062: undef %metathesekeys;
1.71 www 9063: while ($token=$parser->get_token) {
1.339 albertel 9064: if ($token->[0] eq 'S') {
9065: if (defined($token->[2]->{'package'})) {
1.172 www 9066: #
9067: # This is a package - get package info
9068: #
1.339 albertel 9069: my $package=$token->[2]->{'package'};
9070: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9071: if (defined($token->[2]->{'id'})) {
9072: $keyroot.='_'.$token->[2]->{'id'};
9073: }
1.599 albertel 9074: if ($metaentry{':packages'}) {
9075: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 9076: } else {
1.599 albertel 9077: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 9078: }
1.736 albertel 9079: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 9080: my $part=$keyroot;
9081: $part=~s/^\_//;
1.736 albertel 9082: if ($pack_entry=~/^\Q$package\E\&/ ||
9083: $pack_entry=~/^\Q$package\E_0\&/) {
9084: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 9085: # ignore package.tab specified default values
9086: # here &package_tab_default() will fetch those
9087: if ($subp eq 'default') { next; }
1.736 albertel 9088: my $value=$packagetab{$pack_entry};
1.432 albertel 9089: my $unikey;
9090: if ($pack =~ /_0$/) {
9091: $unikey='parameter_0_'.$name;
9092: $part=0;
9093: } else {
9094: $unikey='parameter'.$keyroot.'_'.$name;
9095: }
1.339 albertel 9096: if ($subp eq 'display') {
9097: $value.=' [Part: '.$part.']';
9098: }
1.599 albertel 9099: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 9100: $metathesekeys{$unikey}=1;
1.599 albertel 9101: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9102: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 9103: }
1.599 albertel 9104: if (defined($metaentry{':'.$unikey.'.default'})) {
9105: $metaentry{':'.$unikey}=
9106: $metaentry{':'.$unikey.'.default'};
1.356 albertel 9107: }
1.339 albertel 9108: }
9109: }
9110: } else {
1.172 www 9111: #
9112: # This is not a package - some other kind of start tag
1.339 albertel 9113: #
9114: my $entry=$token->[1];
1.1068 www 9115: my $unikey='';
1.175 www 9116:
1.339 albertel 9117: if ($entry eq 'import') {
1.175 www 9118: #
9119: # Importing a library here
1.339 albertel 9120: #
1.1067 www 9121: my $location=$parser->get_text('/import');
9122: my $dir=$filename;
9123: $dir=~s|[^/]*$||;
9124: $location=&filelocation($dir,$location);
1.1069 www 9125:
1.1068 www 9126: my $importmode=$token->[2]->{'importmode'};
9127: if ($importmode eq 'problem') {
1.1069 www 9128: # Import as problem/response
1.1068 www 9129: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9130: } elsif ($importmode eq 'part') {
9131: # Import as part(s)
1.1069 www 9132: $importedparts=1;
9133: # We need to get the original file and the imported file to get the part order correct
9134: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9135: # Load and inspect original file
1.1070 www 9136: if ($#origfileimportpartids<0) {
9137: undef(%importedpartids);
9138: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9139: my $origfile=&getfile($origfilelocation);
9140: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9141: }
9142:
1.1069 www 9143: # Load and inspect imported file
9144: my $impfile=&getfile($location);
9145: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9146: if ($#impfilepartids>=0) {
9147: # This problem had parts
1.1070 www 9148: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 9149: } else {
9150: # Importing by turning a single problem into a problem part
9151: # It gets the import-tags ID as part-ID
9152: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 9153: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 9154: }
1.1068 www 9155: } else {
9156: # Normal import
9157: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9158: if (defined($token->[2]->{'id'})) {
9159: $unikey.='_'.$token->[2]->{'id'};
9160: }
1.1067 www 9161: }
9162:
1.339 albertel 9163: if ($depthcount<20) {
1.736 albertel 9164: my $metadata =
9165: &metadata($uri,'keys', $location,$unikey,
9166: $depthcount+1);
9167: foreach my $meta (split(',',$metadata)) {
9168: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9169: $metathesekeys{$meta}=1;
1.339 albertel 9170: }
1.1068 www 9171:
9172: }
1.1067 www 9173: } else {
9174: #
9175: # Not importing, some other kind of non-package, non-library start tag
9176: #
9177: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9178: if (defined($token->[2]->{'id'})) {
9179: $unikey.='_'.$token->[2]->{'id'};
9180: }
1.339 albertel 9181: if (defined($token->[2]->{'name'})) {
9182: $unikey.='_'.$token->[2]->{'name'};
9183: }
9184: $metathesekeys{$unikey}=1;
1.736 albertel 9185: foreach my $param (@{$token->[3]}) {
9186: $metaentry{':'.$unikey.'.'.$param} =
9187: $token->[2]->{$param};
1.339 albertel 9188: }
9189: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 9190: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 9191: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9192: # only ws inside the tag, and not in default, so use default
9193: # as value
1.599 albertel 9194: $metaentry{':'.$unikey}=$default;
1.908 albertel 9195: } elsif ( $internaltext =~ /\S/ ) {
9196: # something interesting inside the tag
9197: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 9198: } else {
1.908 albertel 9199: # no interesting values, don't set a default
1.339 albertel 9200: }
1.172 www 9201: # end of not-a-package not-a-library import
1.339 albertel 9202: }
1.172 www 9203: # end of not-a-package start tag
1.339 albertel 9204: }
1.172 www 9205: # the next is the end of "start tag"
1.339 albertel 9206: }
9207: }
1.483 albertel 9208: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 9209: $extension = lc($extension);
9210: if ($extension eq 'htm') { $extension='html'; }
9211:
1.737 albertel 9212: foreach my $key (keys(%packagetab)) {
1.483 albertel 9213: #no specific packages #how's our extension
9214: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 9215: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 9216: \%metathesekeys);
9217: }
1.883 albertel 9218:
9219: if (!exists($metaentry{':packages'})
9220: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 9221: foreach my $key (keys(%packagetab)) {
1.483 albertel 9222: #no specific packages well let's get default then
9223: if ($key!~/^default&/) { next; }
1.488 albertel 9224: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 9225: \%metathesekeys);
9226: }
9227: }
1.338 www 9228: # are there custom rights to evaluate
1.599 albertel 9229: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 9230:
1.338 www 9231: #
9232: # Importing a rights file here
1.339 albertel 9233: #
9234: unless ($depthcount) {
1.599 albertel 9235: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 9236: my $dir=$filename;
9237: $dir=~s|[^/]*$||;
9238: $location=&filelocation($dir,$location);
1.736 albertel 9239: my $rights_metadata =
9240: &metadata($uri,'keys',$location,'_rights',
9241: $depthcount+1);
9242: foreach my $rights (split(',',$rights_metadata)) {
9243: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9244: $metathesekeys{$rights}=1;
1.339 albertel 9245: }
9246: }
9247: }
1.737 albertel 9248: # uniqifiy package listing
9249: my %seen;
9250: my @uniq_packages =
9251: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9252: $metaentry{':packages'} = join(',',@uniq_packages);
9253:
1.1070 www 9254: if ($importedparts) {
9255: # We had imported parts and need to rebuild partorder
9256: $metaentry{':partorder'}='';
9257: $metathesekeys{'partorder'}=1;
9258: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9259: if ($origfileimportpartids[$index] eq 'part') {
9260: # original part, part of the problem
9261: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9262: } else {
9263: # we have imported parts at this position
9264: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9265: }
9266: }
9267: $metaentry{':partorder'}=~s/^\,//;
9268: }
9269:
1.737 albertel 9270: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 9271: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9272: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 9273: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 9274: # this is the end of "was not already recently cached
1.71 www 9275: }
1.599 albertel 9276: return $metaentry{':'.$what};
1.261 albertel 9277: }
9278:
1.488 albertel 9279: sub metadata_create_package_def {
1.483 albertel 9280: my ($uri,$key,$package,$metathesekeys)=@_;
9281: my ($pack,$name,$subp)=split(/\&/,$key);
9282: if ($subp eq 'default') { next; }
9283:
1.599 albertel 9284: if (defined($metaentry{':packages'})) {
9285: $metaentry{':packages'}.=','.$package;
1.483 albertel 9286: } else {
1.599 albertel 9287: $metaentry{':packages'}=$package;
1.483 albertel 9288: }
9289: my $value=$packagetab{$key};
9290: my $unikey;
9291: $unikey='parameter_0_'.$name;
1.599 albertel 9292: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 9293: $$metathesekeys{$unikey}=1;
1.599 albertel 9294: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9295: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 9296: }
1.599 albertel 9297: if (defined($metaentry{':'.$unikey.'.default'})) {
9298: $metaentry{':'.$unikey}=
9299: $metaentry{':'.$unikey.'.default'};
1.483 albertel 9300: }
9301: }
9302:
1.261 albertel 9303: sub metadata_generate_part0 {
9304: my ($metadata,$metacache,$uri) = @_;
9305: my %allnames;
1.737 albertel 9306: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 9307: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 9308: my $part=$$metacache{':'.$metakey.'.part'};
9309: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 9310: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 9311: $allnames{$name}=$part;
9312: }
9313: }
9314: }
9315: foreach my $name (keys(%allnames)) {
9316: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 9317: my $key=":parameter_0_$name";
1.261 albertel 9318: $$metacache{"$key.part"}='0';
9319: $$metacache{"$key.name"}=$name;
1.428 albertel 9320: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 9321: $allnames{$name}.'_'.$name.
9322: '.type'};
1.428 albertel 9323: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 9324: '.display'};
1.644 www 9325: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 9326: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 9327: $$metacache{"$key.display"}=$olddis;
9328: }
1.71 www 9329: }
9330:
1.764 albertel 9331: # ------------------------------------------------------ Devalidate title cache
9332:
9333: sub devalidate_title_cache {
9334: my ($url)=@_;
9335: if (!$env{'request.course.id'}) { return; }
9336: my $symb=&symbread($url);
9337: if (!$symb) { return; }
9338: my $key=$env{'request.course.id'}."\0".$symb;
9339: &devalidate_cache_new('title',$key);
9340: }
9341:
1.1014 droeschl 9342: # ------------------------------------------------- Get the title of a course
9343:
9344: sub current_course_title {
9345: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9346: }
1.301 www 9347: # ------------------------------------------------- Get the title of a resource
9348:
9349: sub gettitle {
9350: my $urlsymb=shift;
9351: my $symb=&symbread($urlsymb);
1.534 albertel 9352: if ($symb) {
1.620 albertel 9353: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 9354: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 9355: if (defined($cached)) {
9356: return $result;
9357: }
1.534 albertel 9358: my ($map,$resid,$url)=&decode_symb($symb);
9359: my $title='';
1.907 albertel 9360: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9361: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9362: } else {
9363: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9364: &GDBM_READER(),0640)) {
9365: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9366: $title=$bighash{'title_'.$mapid.'.'.$resid};
9367: untie(%bighash);
9368: }
1.534 albertel 9369: }
9370: $title=~s/\&colon\;/\:/gs;
9371: if ($title) {
1.599 albertel 9372: return &do_cache_new('title',$key,$title,600);
1.534 albertel 9373: }
9374: $urlsymb=$url;
9375: }
9376: my $title=&metadata($urlsymb,'title');
9377: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9378: return $title;
1.301 www 9379: }
1.613 albertel 9380:
1.614 albertel 9381: sub get_slot {
9382: my ($which,$cnum,$cdom)=@_;
9383: if (!$cnum || !$cdom) {
1.790 albertel 9384: (undef,my $courseid)=&whichuser();
1.620 albertel 9385: $cdom=$env{'course.'.$courseid.'.domain'};
9386: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 9387: }
1.703 albertel 9388: my $key=join("\0",'slots',$cdom,$cnum,$which);
9389: my %slotinfo;
9390: if (exists($remembered{$key})) {
9391: $slotinfo{$which} = $remembered{$key};
9392: } else {
9393: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9394: &Apache::lonhomework::showhash(%slotinfo);
9395: my ($tmp)=keys(%slotinfo);
9396: if ($tmp=~/^error:/) { return (); }
9397: $remembered{$key} = $slotinfo{$which};
9398: }
1.616 albertel 9399: if (ref($slotinfo{$which}) eq 'HASH') {
9400: return %{$slotinfo{$which}};
9401: }
9402: return $slotinfo{$which};
1.614 albertel 9403: }
1.1150 raeburn 9404:
9405: sub get_reservable_slots {
9406: my ($cnum,$cdom,$uname,$udom) = @_;
9407: my $now = time;
9408: my $reservable_info;
9409: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
9410: if (exists($remembered{$key})) {
9411: $reservable_info = $remembered{$key};
9412: } else {
9413: my %resv;
9414: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
9415: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
9416: $reservable_info = \%resv;
9417: $remembered{$key} = $reservable_info;
9418: }
9419: return $reservable_info;
9420: }
9421:
9422: sub get_course_slots {
9423: my ($cnum,$cdom) = @_;
9424: my $hashid=$cnum.':'.$cdom;
9425: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
9426: if (defined($cached)) {
9427: if (ref($result) eq 'HASH') {
9428: return %{$result};
9429: }
9430: } else {
9431: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
9432: my ($tmp) = keys(%slots);
9433: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9434: &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
9435: return %slots;
9436: }
9437: }
9438: return;
9439: }
9440:
9441: sub devalidate_slots_cache {
9442: my ($cnum,$cdom)=@_;
9443: my $hashid=$cnum.':'.$cdom;
9444: &devalidate_cache_new('allslots',$hashid);
9445: }
9446:
1.31 www 9447: # ------------------------------------------------- Update symbolic store links
9448:
9449: sub symblist {
9450: my ($mapname,%newhash)=@_;
1.438 www 9451: $mapname=&deversion(&declutter($mapname));
1.31 www 9452: my %hash;
1.620 albertel 9453: if (($env{'request.course.fn'}) && (%newhash)) {
9454: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9455: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 9456: foreach my $url (keys(%newhash)) {
1.711 albertel 9457: next if ($url eq 'last_known'
9458: && $env{'form.no_update_last_known'});
9459: $hash{declutter($url)}=&encode_symb($mapname,
9460: $newhash{$url}->[1],
9461: $newhash{$url}->[0]);
1.191 harris41 9462: }
1.31 www 9463: if (untie(%hash)) {
9464: return 'ok';
9465: }
9466: }
9467: }
9468: return 'error';
1.212 www 9469: }
9470:
9471: # --------------------------------------------------------------- Verify a symb
9472:
9473: sub symbverify {
1.510 www 9474: my ($symb,$thisurl)=@_;
9475: my $thisfn=$thisurl;
1.439 www 9476: $thisfn=&declutter($thisfn);
1.215 www 9477: # direct jump to resource in page or to a sequence - will construct own symbs
9478: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9479: # check URL part
1.409 www 9480: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 9481:
1.431 www 9482: unless ($url eq $thisfn) { return 0; }
1.213 www 9483:
1.216 www 9484: $symb=&symbclean($symb);
1.510 www 9485: $thisurl=&deversion($thisurl);
1.439 www 9486: $thisfn=&deversion($thisfn);
1.213 www 9487:
9488: my %bighash;
9489: my $okay=0;
1.431 www 9490:
1.620 albertel 9491: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9492: &GDBM_READER(),0640)) {
1.1032 raeburn 9493: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9494: $thisurl =~ s/\?.+$//;
9495: }
1.510 www 9496: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102 raeburn 9497: unless ($ids) {
9498: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9499: $ids=$bighash{$idkey};
1.216 www 9500: }
9501: if ($ids) {
9502: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 9503: foreach my $id (split(/\,/,$ids)) {
9504: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 9505: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9506: $symb =~ s/\?.+$//;
9507: }
1.216 www 9508: if (
9509: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9510: eq $symb) {
1.620 albertel 9511: if (($env{'request.role.adv'}) ||
1.1101 raeburn 9512: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9513: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 9514: $okay=1;
9515: }
9516: }
1.216 www 9517: }
9518: }
1.213 www 9519: untie(%bighash);
9520: }
9521: return $okay;
1.31 www 9522: }
9523:
1.210 www 9524: # --------------------------------------------------------------- Clean-up symb
9525:
9526: sub symbclean {
9527: my $symb=shift;
1.568 albertel 9528: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 9529: # remove version from map
9530: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 9531:
1.210 www 9532: # remove version from URL
9533: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 9534:
1.507 www 9535: # remove wrapper
9536:
1.510 www 9537: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 9538: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 9539: return $symb;
1.409 www 9540: }
9541:
9542: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 9543:
9544: sub encode_symb {
9545: my ($map,$resid,$url)=@_;
9546: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9547: }
1.409 www 9548:
9549: sub decode_symb {
1.568 albertel 9550: my $symb=shift;
9551: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9552: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9553: return (&fixversion($map),$resid,&fixversion($url));
9554: }
9555:
9556: sub fixversion {
9557: my $fn=shift;
1.609 banghart 9558: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9559: my %bighash;
9560: my $uri=&clutter($fn);
1.620 albertel 9561: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9562: # is this cached?
1.599 albertel 9563: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9564: if (defined($cached)) { return $result; }
9565: # unfortunately not cached, or expired
1.620 albertel 9566: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9567: &GDBM_READER(),0640)) {
9568: if ($bighash{'version_'.$uri}) {
9569: my $version=$bighash{'version_'.$uri};
1.444 www 9570: unless (($version eq 'mostrecent') ||
9571: ($version==&getversion($uri))) {
1.440 www 9572: $uri=~s/\.(\w+)$/\.$version\.$1/;
9573: }
9574: }
9575: untie %bighash;
1.413 www 9576: }
1.599 albertel 9577: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9578: }
9579:
9580: sub deversion {
9581: my $url=shift;
9582: $url=~s/\.\d+\.(\w+)$/\.$1/;
9583: return $url;
1.210 www 9584: }
9585:
1.31 www 9586: # ------------------------------------------------------ Return symb list entry
9587:
9588: sub symbread {
1.249 www 9589: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9590: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9591: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9592: # no filename provided? try from environment
1.44 www 9593: unless ($thisfn) {
1.620 albertel 9594: if ($env{'request.symb'}) {
9595: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9596: }
1.620 albertel 9597: $thisfn=$env{'request.filename'};
1.44 www 9598: }
1.569 albertel 9599: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9600: # is that filename actually a symb? Verify, clean, and return
9601: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9602: if (&symbverify($thisfn,$1)) {
1.620 albertel 9603: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9604: }
1.242 www 9605: }
1.44 www 9606: $thisfn=declutter($thisfn);
1.31 www 9607: my %hash;
1.37 www 9608: my %bighash;
9609: my $syval='';
1.620 albertel 9610: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9611: my $targetfn = $thisfn;
1.609 banghart 9612: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9613: $targetfn = 'adm/wrapper/'.$thisfn;
9614: }
1.687 albertel 9615: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9616: $targetfn=$1;
9617: }
1.620 albertel 9618: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9619: &GDBM_READER(),0640)) {
1.481 raeburn 9620: $syval=$hash{$targetfn};
1.37 www 9621: untie(%hash);
9622: }
9623: # ---------------------------------------------------------- There was an entry
9624: if ($syval) {
1.601 albertel 9625: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9626: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9627: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9628: #return $env{$cache_str}='';
1.601 albertel 9629: #}
9630: #$syval.=$1;
9631: #}
1.37 www 9632: } else {
9633: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9634: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9635: &GDBM_READER(),0640)) {
1.37 www 9636: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9637: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9638: unless ($ids) {
9639: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9640: }
9641: unless ($ids) {
9642: # alias?
9643: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9644: }
1.37 www 9645: if ($ids) {
9646: # ------------------------------------------------------------------- Has ID(s)
9647: my @possibilities=split(/\,/,$ids);
1.39 www 9648: if ($#possibilities==0) {
9649: # ----------------------------------------------- There is only one possibility
1.37 www 9650: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9651: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9652: $resid,$thisfn);
1.249 www 9653: } elsif (!$donotrecurse) {
1.39 www 9654: # ------------------------------------------ There is more than one possibility
9655: my $realpossible=0;
1.800 albertel 9656: foreach my $id (@possibilities) {
9657: my $file=$bighash{'src_'.$id};
1.39 www 9658: if (&allowed('bre',$file)) {
1.800 albertel 9659: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9660: if ($bighash{'map_type_'.$mapid} ne 'page') {
9661: $realpossible++;
1.626 albertel 9662: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9663: $resid,$thisfn);
1.39 www 9664: }
9665: }
1.191 harris41 9666: }
1.39 www 9667: if ($realpossible!=1) { $syval=''; }
1.249 www 9668: } else {
9669: $syval='';
1.37 www 9670: }
9671: }
9672: untie(%bighash)
1.481 raeburn 9673: }
1.31 www 9674: }
1.62 www 9675: if ($syval) {
1.620 albertel 9676: return $env{$cache_str}=$syval;
1.62 www 9677: }
1.31 www 9678: }
1.949 raeburn 9679: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9680: return $env{$cache_str}='';
1.31 www 9681: }
9682:
9683: # ---------------------------------------------------------- Return random seed
9684:
1.32 www 9685: sub numval {
9686: my $txt=shift;
9687: $txt=~tr/A-J/0-9/;
9688: $txt=~tr/a-j/0-9/;
9689: $txt=~tr/K-T/0-9/;
9690: $txt=~tr/k-t/0-9/;
9691: $txt=~tr/U-Z/0-5/;
9692: $txt=~tr/u-z/0-5/;
9693: $txt=~s/\D//g;
1.564 albertel 9694: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9695: return int($txt);
1.368 albertel 9696: }
9697:
1.484 albertel 9698: sub numval2 {
9699: my $txt=shift;
9700: $txt=~tr/A-J/0-9/;
9701: $txt=~tr/a-j/0-9/;
9702: $txt=~tr/K-T/0-9/;
9703: $txt=~tr/k-t/0-9/;
9704: $txt=~tr/U-Z/0-5/;
9705: $txt=~tr/u-z/0-5/;
9706: $txt=~s/\D//g;
9707: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9708: my $total;
9709: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9710: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9711: return int($total);
9712: }
9713:
1.575 albertel 9714: sub numval3 {
9715: use integer;
9716: my $txt=shift;
9717: $txt=~tr/A-J/0-9/;
9718: $txt=~tr/a-j/0-9/;
9719: $txt=~tr/K-T/0-9/;
9720: $txt=~tr/k-t/0-9/;
9721: $txt=~tr/U-Z/0-5/;
9722: $txt=~tr/u-z/0-5/;
9723: $txt=~s/\D//g;
9724: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9725: my $total;
9726: foreach my $val (@txts) { $total+=$val; }
9727: if ($_64bit) { $total=(($total<<32)>>32); }
9728: return $total;
9729: }
9730:
1.675 albertel 9731: sub digest {
9732: my ($data)=@_;
9733: my $digest=&Digest::MD5::md5($data);
9734: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9735: my ($e,$f);
9736: {
9737: use integer;
9738: $e=($a+$b);
9739: $f=($c+$d);
9740: if ($_64bit) {
9741: $e=(($e<<32)>>32);
9742: $f=(($f<<32)>>32);
9743: }
9744: }
9745: if (wantarray) {
9746: return ($e,$f);
9747: } else {
9748: my $g;
9749: {
9750: use integer;
9751: $g=($e+$f);
9752: if ($_64bit) {
9753: $g=(($g<<32)>>32);
9754: }
9755: }
9756: return $g;
9757: }
9758: }
9759:
1.368 albertel 9760: sub latest_rnd_algorithm_id {
1.675 albertel 9761: return '64bit5';
1.366 albertel 9762: }
1.32 www 9763:
1.503 albertel 9764: sub get_rand_alg {
9765: my ($courseid)=@_;
1.790 albertel 9766: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9767: if ($courseid) {
1.620 albertel 9768: return $env{"course.$courseid.rndseed"};
1.503 albertel 9769: }
9770: return &latest_rnd_algorithm_id();
9771: }
9772:
1.562 albertel 9773: sub validCODE {
9774: my ($CODE)=@_;
9775: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9776: return 0;
9777: }
9778:
1.491 albertel 9779: sub getCODE {
1.620 albertel 9780: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9781: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9782: defined($Apache::lonhomework::parsing_a_task) ) &&
9783: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9784: return $Apache::lonhomework::history{'resource.CODE'};
9785: }
9786: return undef;
9787: }
1.1133 foxr 9788: #
9789: # Determines the random seed for a specific context:
9790: #
9791: # parameters:
9792: # symb - in course context the symb for the seed.
9793: # course_id - The course id of the form domain_coursenum.
9794: # domain - Domain for the user.
9795: # course - Course for the user.
9796: # cenv - environment of the course.
9797: #
9798: # NOTE:
9799: # All parameters are picked out of the environment if missing
9800: # or not defined.
9801: # If a symb cannot be determined the current time is used instead.
9802: #
9803: # For a given well defined symb, courside, domain, username,
9804: # and course environment, the seed is reproducible.
9805: #
1.31 www 9806: sub rndseed {
1.1133 foxr 9807: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 9808: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9809: if (!defined($symb)) {
1.366 albertel 9810: unless ($symb=$wsymb) { return time; }
9811: }
1.1146 foxr 9812: if (!defined $courseid) {
9813: $courseid=$wcourseid;
9814: }
9815: if (!defined $domain) { $domain=$wdomain; }
9816: if (!defined $username) { $username=$wusername }
1.1133 foxr 9817:
9818: my $which;
9819: if (defined($cenv->{'rndseed'})) {
9820: $which = $cenv->{'rndseed'};
9821: } else {
9822: $which =&get_rand_alg($courseid);
9823: }
1.491 albertel 9824: if (defined(&getCODE())) {
1.1133 foxr 9825:
1.675 albertel 9826: if ($which eq '64bit5') {
9827: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9828: } elsif ($which eq '64bit4') {
1.575 albertel 9829: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9830: } else {
9831: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9832: }
1.675 albertel 9833: } elsif ($which eq '64bit5') {
9834: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9835: } elsif ($which eq '64bit4') {
9836: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9837: } elsif ($which eq '64bit3') {
9838: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9839: } elsif ($which eq '64bit2') {
9840: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9841: } elsif ($which eq '64bit') {
9842: return &rndseed_64bit($symb,$courseid,$domain,$username);
9843: }
9844: return &rndseed_32bit($symb,$courseid,$domain,$username);
9845: }
9846:
9847: sub rndseed_32bit {
9848: my ($symb,$courseid,$domain,$username)=@_;
9849: {
9850: use integer;
9851: my $symbchck=unpack("%32C*",$symb) << 27;
9852: my $symbseed=numval($symb) << 22;
9853: my $namechck=unpack("%32C*",$username) << 17;
9854: my $nameseed=numval($username) << 12;
9855: my $domainseed=unpack("%32C*",$domain) << 7;
9856: my $courseseed=unpack("%32C*",$courseid);
9857: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9858: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9859: #&logthis("rndseed :$num:$symb");
1.564 albertel 9860: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9861: return $num;
9862: }
9863: }
9864:
9865: sub rndseed_64bit {
9866: my ($symb,$courseid,$domain,$username)=@_;
9867: {
9868: use integer;
9869: my $symbchck=unpack("%32S*",$symb) << 21;
9870: my $symbseed=numval($symb) << 10;
9871: my $namechck=unpack("%32S*",$username);
9872:
9873: my $nameseed=numval($username) << 21;
9874: my $domainseed=unpack("%32S*",$domain) << 10;
9875: my $courseseed=unpack("%32S*",$courseid);
9876:
9877: my $num1=$symbchck+$symbseed+$namechck;
9878: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9879: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9880: #&logthis("rndseed :$num:$symb");
1.564 albertel 9881: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9882: return "$num1,$num2";
1.155 albertel 9883: }
1.366 albertel 9884: }
9885:
1.443 albertel 9886: sub rndseed_64bit2 {
9887: my ($symb,$courseid,$domain,$username)=@_;
9888: {
9889: use integer;
9890: # strings need to be an even # of cahracters long, it it is odd the
9891: # last characters gets thrown away
9892: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9893: my $symbseed=numval($symb) << 10;
9894: my $namechck=unpack("%32S*",$username.' ');
9895:
9896: my $nameseed=numval($username) << 21;
1.501 albertel 9897: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9898: my $courseseed=unpack("%32S*",$courseid.' ');
9899:
9900: my $num1=$symbchck+$symbseed+$namechck;
9901: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9902: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9903: #&logthis("rndseed :$num:$symb");
1.803 albertel 9904: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9905: return "$num1,$num2";
9906: }
9907: }
9908:
9909: sub rndseed_64bit3 {
9910: my ($symb,$courseid,$domain,$username)=@_;
9911: {
9912: use integer;
9913: # strings need to be an even # of cahracters long, it it is odd the
9914: # last characters gets thrown away
9915: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9916: my $symbseed=numval2($symb) << 10;
9917: my $namechck=unpack("%32S*",$username.' ');
9918:
9919: my $nameseed=numval2($username) << 21;
1.443 albertel 9920: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9921: my $courseseed=unpack("%32S*",$courseid.' ');
9922:
9923: my $num1=$symbchck+$symbseed+$namechck;
9924: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9925: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9926: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9927: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 9928:
1.503 albertel 9929: return "$num1:$num2";
1.443 albertel 9930: }
9931: }
9932:
1.575 albertel 9933: sub rndseed_64bit4 {
9934: my ($symb,$courseid,$domain,$username)=@_;
9935: {
9936: use integer;
9937: # strings need to be an even # of cahracters long, it it is odd the
9938: # last characters gets thrown away
9939: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9940: my $symbseed=numval3($symb) << 10;
9941: my $namechck=unpack("%32S*",$username.' ');
9942:
9943: my $nameseed=numval3($username) << 21;
9944: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9945: my $courseseed=unpack("%32S*",$courseid.' ');
9946:
9947: my $num1=$symbchck+$symbseed+$namechck;
9948: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9949: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9950: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9951: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 9952:
1.575 albertel 9953: return "$num1:$num2";
9954: }
9955: }
9956:
1.675 albertel 9957: sub rndseed_64bit5 {
9958: my ($symb,$courseid,$domain,$username)=@_;
9959: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9960: return "$num1:$num2";
9961: }
9962:
1.366 albertel 9963: sub rndseed_CODE_64bit {
9964: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9965: {
1.366 albertel 9966: use integer;
1.443 albertel 9967: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9968: my $symbseed=numval2($symb);
1.491 albertel 9969: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9970: my $CODEseed=numval(&getCODE());
1.443 albertel 9971: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9972: my $num1=$symbseed+$CODEchck;
9973: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9974: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9975: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9976: if ($_64bit) { $num1=(($num1<<32)>>32); }
9977: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9978: return "$num1:$num2";
1.366 albertel 9979: }
9980: }
9981:
1.575 albertel 9982: sub rndseed_CODE_64bit4 {
9983: my ($symb,$courseid,$domain,$username)=@_;
9984: {
9985: use integer;
9986: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9987: my $symbseed=numval3($symb);
9988: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9989: my $CODEseed=numval3(&getCODE());
9990: my $courseseed=unpack("%32S*",$courseid.' ');
9991: my $num1=$symbseed+$CODEchck;
9992: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9993: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9994: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9995: if ($_64bit) { $num1=(($num1<<32)>>32); }
9996: if ($_64bit) { $num2=(($num2<<32)>>32); }
9997: return "$num1:$num2";
9998: }
9999: }
10000:
1.675 albertel 10001: sub rndseed_CODE_64bit5 {
10002: my ($symb,$courseid,$domain,$username)=@_;
10003: my $code = &getCODE();
10004: my ($num1,$num2)=&digest("$symb,$courseid,$code");
10005: return "$num1:$num2";
10006: }
10007:
1.366 albertel 10008: sub setup_random_from_rndseed {
10009: my ($rndseed)=@_;
1.503 albertel 10010: if ($rndseed =~/([,:])/) {
10011: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 10012: &Math::Random::random_set_seed(abs($num1),abs($num2));
10013: } else {
10014: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 10015: }
1.36 albertel 10016: }
10017:
1.474 albertel 10018: sub latest_receipt_algorithm_id {
1.835 albertel 10019: return 'receipt3';
1.474 albertel 10020: }
10021:
1.480 www 10022: sub recunique {
10023: my $fucourseid=shift;
10024: my $unique;
1.835 albertel 10025: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10026: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10027: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 10028: } else {
10029: $unique=$perlvar{'lonReceipt'};
10030: }
10031: return unpack("%32C*",$unique);
10032: }
10033:
10034: sub recprefix {
10035: my $fucourseid=shift;
10036: my $prefix;
1.835 albertel 10037: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10038: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10039: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 10040: } else {
10041: $prefix=$perlvar{'lonHostID'};
10042: }
10043: return unpack("%32C*",$prefix);
10044: }
10045:
1.76 www 10046: sub ireceipt {
1.474 albertel 10047: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 10048:
10049: my $return =&recprefix($fucourseid).'-';
10050:
10051: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10052: $env{'request.state'} eq 'construct') {
10053: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10054: return $return;
10055: }
10056:
1.76 www 10057: my $cuname=unpack("%32C*",$funame);
10058: my $cudom=unpack("%32C*",$fudom);
10059: my $cucourseid=unpack("%32C*",$fucourseid);
10060: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 10061: my $cunique=&recunique($fucourseid);
1.474 albertel 10062: my $cpart=unpack("%32S*",$part);
1.835 albertel 10063: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10064:
1.790 albertel 10065: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 10066:
10067: $return.= ($cunique%$cuname+
10068: $cunique%$cudom+
10069: $cusymb%$cuname+
10070: $cusymb%$cudom+
10071: $cucourseid%$cuname+
10072: $cucourseid%$cudom+
10073: $cpart%$cuname+
10074: $cpart%$cudom);
10075: } else {
10076: $return.= ($cunique%$cuname+
10077: $cunique%$cudom+
10078: $cusymb%$cuname+
10079: $cusymb%$cudom+
10080: $cucourseid%$cuname+
10081: $cucourseid%$cudom);
10082: }
10083: return $return;
1.76 www 10084: }
10085:
10086: sub receipt {
1.474 albertel 10087: my ($part)=@_;
1.790 albertel 10088: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 10089: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 10090: }
1.260 ng 10091:
1.790 albertel 10092: sub whichuser {
10093: my ($passedsymb)=@_;
10094: my ($symb,$courseid,$domain,$name,$publicuser);
10095: if (defined($env{'form.grade_symb'})) {
10096: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10097: my $allowed=&allowed('vgr',$tmp_courseid);
10098: if (!$allowed &&
10099: exists($env{'request.course.sec'}) &&
10100: $env{'request.course.sec'} !~ /^\s*$/) {
10101: $allowed=&allowed('vgr',$tmp_courseid.
10102: '/'.$env{'request.course.sec'});
10103: }
10104: if ($allowed) {
10105: ($symb)=&get_env_multiple('form.grade_symb');
10106: $courseid=$tmp_courseid;
10107: ($domain)=&get_env_multiple('form.grade_domain');
10108: ($name)=&get_env_multiple('form.grade_username');
10109: return ($symb,$courseid,$domain,$name,$publicuser);
10110: }
10111: }
10112: if (!$passedsymb) {
10113: $symb=&symbread();
10114: } else {
10115: $symb=$passedsymb;
10116: }
10117: $courseid=$env{'request.course.id'};
10118: $domain=$env{'user.domain'};
10119: $name=$env{'user.name'};
10120: if ($name eq 'public' && $domain eq 'public') {
10121: if (!defined($env{'form.username'})) {
10122: $env{'form.username'}.=time.rand(10000000);
10123: }
10124: $name.=$env{'form.username'};
10125: }
10126: return ($symb,$courseid,$domain,$name,$publicuser);
10127:
10128: }
10129:
1.36 albertel 10130: # ------------------------------------------------------------ Serves up a file
1.472 albertel 10131: # returns either the contents of the file or
10132: # -1 if the file doesn't exist
1.481 raeburn 10133: #
10134: # if the target is a file that was uploaded via DOCS,
10135: # a check will be made to see if a current copy exists on the local server,
10136: # if it does this will be served, otherwise a copy will be retrieved from
10137: # the home server for the course and stored in /home/httpd/html/userfiles on
10138: # the local server.
1.472 albertel 10139:
1.36 albertel 10140: sub getfile {
1.538 albertel 10141: my ($file) = @_;
1.609 banghart 10142: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 10143: &repcopy($file);
10144: return &readfile($file);
10145: }
10146:
10147: sub repcopy_userfile {
10148: my ($file)=@_;
1.1142 raeburn 10149: my $londocroot = $perlvar{'lonDocRoot'};
10150: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10151: if ($file =~ m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
1.538 albertel 10152: my ($cdom,$cnum,$filename) =
1.811 albertel 10153: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 10154: my $uri="/uploaded/$cdom/$cnum/$filename";
10155: if (-e "$file") {
1.828 www 10156: # we already have a local copy, check it out
1.538 albertel 10157: my @fileinfo = stat($file);
1.828 www 10158: my $rtncode;
10159: my $info;
1.538 albertel 10160: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 10161: if ($lwpresp ne 'ok') {
1.828 www 10162: # there is no such file anymore, even though we had a local copy
1.482 albertel 10163: if ($rtncode eq '404') {
1.538 albertel 10164: unlink($file);
1.482 albertel 10165: }
10166: return -1;
10167: }
10168: if ($info < $fileinfo[9]) {
1.828 www 10169: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 10170: return 'ok';
1.828 www 10171: } else {
10172: # the file is outdated, get rid of it
10173: unlink($file);
1.482 albertel 10174: }
1.828 www 10175: }
10176: # one way or the other, at this point, we don't have the file
10177: # construct the correct path for the file
10178: my @parts = ($cdom,$cnum);
10179: if ($filename =~ m|^(.+)/[^/]+$|) {
10180: push @parts, split(/\//,$1);
10181: }
10182: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10183: foreach my $part (@parts) {
10184: $path .= '/'.$part;
10185: if (!-e $path) {
10186: mkdir($path,0770);
1.482 albertel 10187: }
10188: }
1.828 www 10189: # now the path exists for sure
10190: # get a user agent
10191: my $ua=new LWP::UserAgent;
10192: my $transferfile=$file.'.in.transfer';
10193: # FIXME: this should flock
10194: if (-e $transferfile) { return 'ok'; }
10195: my $request;
10196: $uri=~s/^\///;
1.980 raeburn 10197: my $homeserver = &homeserver($cnum,$cdom);
10198: my $protocol = $protocol{$homeserver};
10199: $protocol = 'http' if ($protocol ne 'https');
10200: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 10201: my $response=$ua->request($request,$transferfile);
10202: # did it work?
10203: if ($response->is_error()) {
10204: unlink($transferfile);
10205: &logthis("Userfile repcopy failed for $uri");
10206: return -1;
10207: }
10208: # worked, rename the transfer file
10209: rename($transferfile,$file);
1.607 raeburn 10210: return 'ok';
1.481 raeburn 10211: }
10212:
1.517 albertel 10213: sub tokenwrapper {
10214: my $uri=shift;
1.980 raeburn 10215: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 10216: $uri=~s|^/||;
1.620 albertel 10217: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 10218: my $token=$1;
1.552 albertel 10219: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10220: if ($udom && $uname && $file) {
10221: $file=~s|(\?\.*)*$||;
1.949 raeburn 10222: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 10223: my $homeserver = &homeserver($uname,$udom);
10224: my $protocol = $protocol{$homeserver};
10225: $protocol = 'http' if ($protocol ne 'https');
10226: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 10227: (($uri=~/\?/)?'&':'?').'token='.$token.
10228: '&tokenissued='.$perlvar{'lonHostID'};
10229: } else {
10230: return '/adm/notfound.html';
10231: }
10232: }
10233:
1.828 www 10234: # call with reqtype HEAD: get last modification time
10235: # call with reqtype GET: get the file contents
10236: # Do not call this with reqtype GET for large files! It loads everything into memory
10237: #
1.481 raeburn 10238: sub getuploaded {
10239: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10240: $uri=~s/^\///;
1.980 raeburn 10241: my $homeserver = &homeserver($cnum,$cdom);
10242: my $protocol = $protocol{$homeserver};
10243: $protocol = 'http' if ($protocol ne 'https');
10244: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 10245: my $ua=new LWP::UserAgent;
10246: my $request=new HTTP::Request($reqtype,$uri);
10247: my $response=$ua->request($request);
10248: $$rtncode = $response->code;
1.482 albertel 10249: if (! $response->is_success()) {
10250: return 'failed';
10251: }
10252: if ($reqtype eq 'HEAD') {
1.486 www 10253: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 10254: } elsif ($reqtype eq 'GET') {
10255: $$info = $response->content;
1.472 albertel 10256: }
1.482 albertel 10257: return 'ok';
1.36 albertel 10258: }
10259:
1.481 raeburn 10260: sub readfile {
10261: my $file = shift;
10262: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10263: my $fh;
10264: open($fh,"<$file");
10265: my $a='';
1.800 albertel 10266: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 10267: return $a;
10268: }
10269:
1.36 albertel 10270: sub filelocation {
1.590 banghart 10271: my ($dir,$file) = @_;
10272: my $location;
10273: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 10274:
10275: if ($file =~ m-^/adm/-) {
10276: $file=~s-^/adm/wrapper/-/-;
10277: $file=~s-^/adm/coursedocs/showdoc/-/-;
10278: }
1.882 albertel 10279:
1.1139 www 10280: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 10281: $location = $file;
1.609 banghart 10282: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 10283: my ($udom,$uname,$filename)=
1.811 albertel 10284: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 10285: my $home=&homeserver($uname,$udom);
10286: my $is_me=0;
10287: my @ids=¤t_machine_ids();
10288: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10289: if ($is_me) {
1.1117 foxr 10290: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 10291: } else {
10292: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10293: $udom.'/'.$uname.'/'.$filename;
10294: }
1.882 albertel 10295: } elsif ($file =~ m-^/adm/-) {
10296: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 10297: } else {
10298: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 10299: $file=~s:^/(res|priv)/:/:;
10300: my $space=$1;
1.590 banghart 10301: if ( !( $file =~ m:^/:) ) {
10302: $location = $dir. '/'.$file;
10303: } else {
1.1142 raeburn 10304: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 10305: }
1.59 albertel 10306: }
1.590 banghart 10307: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 10308: while ($location=~m{/\.\./}) {
10309: if ($location =~ m{/[^/]+/\.\./}) {
10310: $location=~ s{/[^/]+/\.\./}{/}g;
10311: } else {
10312: $location=~ s{/\.\./}{/}g;
10313: }
10314: } #remove dir/..
1.590 banghart 10315: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10316: return $location;
1.46 www 10317: }
1.36 albertel 10318:
1.46 www 10319: sub hreflocation {
10320: my ($dir,$file)=@_;
1.980 raeburn 10321: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 10322: $file=filelocation($dir,$file);
1.700 albertel 10323: } elsif ($file=~m-^/adm/-) {
10324: $file=~s-^/adm/wrapper/-/-;
10325: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 10326: }
10327: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10328: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10329: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 10330: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10331: {/uploaded/$1/$2/}x;
1.46 www 10332: }
1.913 albertel 10333: if ($file=~ m{^/userfiles/}) {
10334: $file =~ s{^/userfiles/}{/uploaded/};
10335: }
1.462 albertel 10336: return $file;
1.465 albertel 10337: }
10338:
1.1139 www 10339:
10340:
10341:
10342:
1.465 albertel 10343: sub current_machine_domains {
1.853 albertel 10344: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10345: }
10346:
10347: sub machine_domains {
10348: my ($hostname) = @_;
1.465 albertel 10349: my @domains;
1.838 albertel 10350: my %hostname = &all_hostnames();
1.465 albertel 10351: while( my($id, $name) = each(%hostname)) {
1.467 matthew 10352: # &logthis("-$id-$name-$hostname-");
1.465 albertel 10353: if ($hostname eq $name) {
1.844 albertel 10354: push(@domains,&host_domain($id));
1.465 albertel 10355: }
10356: }
10357: return @domains;
10358: }
10359:
10360: sub current_machine_ids {
1.853 albertel 10361: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10362: }
10363:
10364: sub machine_ids {
10365: my ($hostname) = @_;
10366: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 10367: my @ids;
1.888 albertel 10368: my %name_to_host = &all_names();
1.889 albertel 10369: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10370: return @{ $name_to_host{$hostname} };
10371: }
10372: return;
1.31 www 10373: }
10374:
1.824 raeburn 10375: sub additional_machine_domains {
10376: my @domains;
10377: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10378: while( my $line = <$fh>) {
10379: $line =~ s/\s//g;
10380: push(@domains,$line);
10381: }
10382: return @domains;
10383: }
10384:
10385: sub default_login_domain {
10386: my $domain = $perlvar{'lonDefDomain'};
10387: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10388: foreach my $posdom (¤t_machine_domains(),
10389: &additional_machine_domains()) {
10390: if (lc($posdom) eq lc($testdomain)) {
10391: $domain=$posdom;
10392: last;
10393: }
10394: }
10395: return $domain;
10396: }
10397:
1.31 www 10398: # ------------------------------------------------------------- Declutters URLs
10399:
10400: sub declutter {
10401: my $thisfn=shift;
1.569 albertel 10402: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 10403: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 10404: $thisfn=~s/^\///;
1.697 albertel 10405: $thisfn=~s|^adm/wrapper/||;
10406: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 10407: $thisfn=~s/^res\///;
1.1032 raeburn 10408: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10409: $thisfn=~s/\?.+$//;
10410: }
1.268 www 10411: return $thisfn;
10412: }
10413:
10414: # ------------------------------------------------------------- Clutter up URLs
10415:
10416: sub clutter {
10417: my $thisfn='/'.&declutter(shift);
1.887 albertel 10418: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 10419: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 10420: $thisfn='/res'.$thisfn;
10421: }
1.1031 raeburn 10422: if ($thisfn !~m|^/adm|) {
10423: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 10424: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 10425: } else {
10426: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10427: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 10428: if ($embstyle eq 'ssi'
10429: || ($embstyle eq 'hdn')
10430: || ($embstyle eq 'rat')
10431: || ($embstyle eq 'prv')
10432: || ($embstyle eq 'ign')) {
10433: #do nothing with these
10434: } elsif (($embstyle eq 'img')
1.695 albertel 10435: || ($embstyle eq 'emb')
10436: || ($embstyle eq 'wrp')) {
10437: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 10438: } elsif ($embstyle eq 'unk'
10439: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 10440: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 10441: } else {
1.718 www 10442: # &logthis("Got a blank emb style");
1.695 albertel 10443: }
1.694 albertel 10444: }
10445: }
1.31 www 10446: return $thisfn;
1.12 www 10447: }
10448:
1.787 albertel 10449: sub clutter_with_no_wrapper {
10450: my $uri = &clutter(shift);
10451: if ($uri =~ m-^/adm/-) {
10452: $uri =~ s-^/adm/wrapper/-/-;
10453: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10454: }
10455: return $uri;
10456: }
10457:
1.557 albertel 10458: sub freeze_escape {
10459: my ($value)=@_;
10460: if (ref($value)) {
10461: $value=&nfreeze($value);
10462: return '__FROZEN__'.&escape($value);
10463: }
10464: return &escape($value);
10465: }
10466:
1.11 www 10467:
1.557 albertel 10468: sub thaw_unescape {
10469: my ($value)=@_;
10470: if ($value =~ /^__FROZEN__/) {
10471: substr($value,0,10,undef);
10472: $value=&unescape($value);
10473: return &thaw($value);
10474: }
10475: return &unescape($value);
10476: }
10477:
1.436 albertel 10478: sub correct_line_ends {
10479: my ($result)=@_;
10480: $$result =~s/\r\n/\n/mg;
10481: $$result =~s/\r/\n/mg;
1.415 albertel 10482: }
1.1 albertel 10483: # ================================================================ Main Program
10484:
1.184 www 10485: sub goodbye {
1.204 albertel 10486: &logthis("Starting Shut down");
1.443 albertel 10487: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 10488: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 10489: #converted
1.599 albertel 10490: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 10491: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10492: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10493: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 10494: #1.1 only
1.870 albertel 10495: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10496: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10497: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10498: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10499: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 10500: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10501: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 10502: &flushcourselogs();
10503: &logthis("Shutting down");
10504: }
10505:
1.852 albertel 10506: sub get_dns {
1.869 albertel 10507: my ($url,$func,$ignore_cache) = @_;
10508: if (!$ignore_cache) {
10509: my ($content,$cached)=
10510: &Apache::lonnet::is_cached_new('dns',$url);
10511: if ($cached) {
10512: &$func($content);
10513: return;
10514: }
10515: }
10516:
10517: my %alldns;
1.852 albertel 10518: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10519: foreach my $dns (<$config>) {
10520: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 10521: my $line = $1;
10522: my ($host,$protocol) = split(/:/,$line);
10523: if ($protocol ne 'https') {
10524: $protocol = 'http';
10525: }
10526: $alldns{$host} = $protocol;
1.869 albertel 10527: }
10528: while (%alldns) {
10529: my ($dns) = keys(%alldns);
1.852 albertel 10530: my $ua=new LWP::UserAgent;
1.1134 raeburn 10531: $ua->timeout(30);
1.979 raeburn 10532: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 10533: my $response=$ua->request($request);
1.979 raeburn 10534: delete($alldns{$dns});
1.852 albertel 10535: next if ($response->is_error());
10536: my @content = split("\n",$response->content);
1.869 albertel 10537: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 10538: &$func(\@content);
1.869 albertel 10539: return;
1.852 albertel 10540: }
10541: close($config);
1.871 albertel 10542: my $which = (split('/',$url))[3];
10543: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10544: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 10545: my @content = <$config>;
10546: &$func(\@content);
10547: return;
1.852 albertel 10548: }
1.327 albertel 10549: # ------------------------------------------------------------ Read domain file
10550: {
1.852 albertel 10551: my $loaded;
1.846 albertel 10552: my %domain;
10553:
1.852 albertel 10554: sub parse_domain_tab {
10555: my ($lines) = @_;
10556: foreach my $line (@$lines) {
10557: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 10558:
1.846 albertel 10559: chomp($line);
1.852 albertel 10560: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 10561: my %this_domain;
10562: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10563: 'lang_def', 'city', 'longi', 'lati',
10564: 'primary') {
10565: $this_domain{$field} = shift(@elements);
10566: }
10567: $domain{$name} = \%this_domain;
1.852 albertel 10568: }
10569: }
1.864 albertel 10570:
10571: sub reset_domain_info {
10572: undef($loaded);
10573: undef(%domain);
10574: }
10575:
1.852 albertel 10576: sub load_domain_tab {
1.869 albertel 10577: my ($ignore_cache) = @_;
10578: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10579: my $fh;
10580: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10581: my @lines = <$fh>;
10582: &parse_domain_tab(\@lines);
1.448 albertel 10583: }
1.852 albertel 10584: close($fh);
10585: $loaded = 1;
1.327 albertel 10586: }
1.846 albertel 10587:
10588: sub domain {
1.852 albertel 10589: &load_domain_tab() if (!$loaded);
10590:
1.846 albertel 10591: my ($name,$what) = @_;
10592: return if ( !exists($domain{$name}) );
10593:
10594: if (!$what) {
10595: return $domain{$name}{'description'};
10596: }
10597: return $domain{$name}{$what};
10598: }
1.974 raeburn 10599:
10600: sub domain_info {
10601: &load_domain_tab() if (!$loaded);
10602: return %domain;
10603: }
10604:
1.327 albertel 10605: }
10606:
10607:
1.1 albertel 10608: # ------------------------------------------------------------- Read hosts file
10609: {
1.838 albertel 10610: my %hostname;
1.844 albertel 10611: my %hostdom;
1.845 albertel 10612: my %libserv;
1.852 albertel 10613: my $loaded;
1.888 albertel 10614: my %name_to_host;
1.1074 raeburn 10615: my %internetdom;
1.1107 raeburn 10616: my %LC_dns_serv;
1.852 albertel 10617:
10618: sub parse_hosts_tab {
10619: my ($file) = @_;
10620: foreach my $configline (@$file) {
10621: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 10622: chomp($configline);
10623: if ($configline =~ /^\^/) {
10624: if ($configline =~ /^\^([\w.\-]+)/) {
10625: $LC_dns_serv{$1} = 1;
10626: }
10627: next;
10628: }
1.1074 raeburn 10629: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10630: $name=~s/\s//g;
10631: if ($id && $domain && $role && $name) {
10632: $hostname{$id}=$name;
1.888 albertel 10633: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10634: $hostdom{$id}=$domain;
10635: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 10636: if (defined($protocol)) {
10637: if ($protocol eq 'https') {
10638: $protocol{$id} = $protocol;
10639: } else {
10640: $protocol{$id} = 'http';
10641: }
1.968 raeburn 10642: } else {
1.969 raeburn 10643: $protocol{$id} = 'http';
1.968 raeburn 10644: }
1.1074 raeburn 10645: if (defined($intdom)) {
10646: $internetdom{$id} = $intdom;
10647: }
1.852 albertel 10648: }
10649: }
10650: }
1.864 albertel 10651:
10652: sub reset_hosts_info {
1.897 albertel 10653: &purge_remembered();
1.864 albertel 10654: &reset_domain_info();
10655: &reset_hosts_ip_info();
1.892 albertel 10656: undef(%name_to_host);
1.864 albertel 10657: undef(%hostname);
10658: undef(%hostdom);
10659: undef(%libserv);
10660: undef($loaded);
10661: }
1.1 albertel 10662:
1.852 albertel 10663: sub load_hosts_tab {
1.869 albertel 10664: my ($ignore_cache) = @_;
10665: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 10666: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10667: my @config = <$config>;
10668: &parse_hosts_tab(\@config);
10669: close($config);
10670: $loaded=1;
1.1 albertel 10671: }
1.852 albertel 10672:
1.838 albertel 10673: sub hostname {
1.852 albertel 10674: &load_hosts_tab() if (!$loaded);
10675:
1.838 albertel 10676: my ($lonid) = @_;
10677: return $hostname{$lonid};
10678: }
1.845 albertel 10679:
1.838 albertel 10680: sub all_hostnames {
1.852 albertel 10681: &load_hosts_tab() if (!$loaded);
10682:
1.838 albertel 10683: return %hostname;
10684: }
1.845 albertel 10685:
1.888 albertel 10686: sub all_names {
10687: &load_hosts_tab() if (!$loaded);
10688:
10689: return %name_to_host;
10690: }
10691:
1.974 raeburn 10692: sub all_host_domain {
10693: &load_hosts_tab() if (!$loaded);
10694: return %hostdom;
10695: }
10696:
1.845 albertel 10697: sub is_library {
1.852 albertel 10698: &load_hosts_tab() if (!$loaded);
10699:
1.845 albertel 10700: return exists($libserv{$_[0]});
10701: }
10702:
10703: sub all_library {
1.852 albertel 10704: &load_hosts_tab() if (!$loaded);
10705:
1.845 albertel 10706: return %libserv;
10707: }
10708:
1.1062 droeschl 10709: sub unique_library {
10710: #2x reverse removes all hostnames that appear more than once
10711: my %unique = reverse &all_library();
10712: return reverse %unique;
10713: }
10714:
1.841 albertel 10715: sub get_servers {
1.852 albertel 10716: &load_hosts_tab() if (!$loaded);
10717:
1.841 albertel 10718: my ($domain,$type) = @_;
10719: my %possible_hosts = ($type eq 'library') ? %libserv
10720: : %hostname;
10721: my %result;
1.842 albertel 10722: if (ref($domain) eq 'ARRAY') {
10723: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10724: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10725: $result{$host} = $hostname;
10726: }
10727: }
10728: } else {
10729: while ( my ($host,$hostname) = each(%possible_hosts)) {
10730: if ($hostdom{$host} eq $domain) {
10731: $result{$host} = $hostname;
10732: }
1.841 albertel 10733: }
10734: }
10735: return %result;
10736: }
1.845 albertel 10737:
1.1062 droeschl 10738: sub get_unique_servers {
10739: my %unique = reverse &get_servers(@_);
10740: return reverse %unique;
10741: }
10742:
1.844 albertel 10743: sub host_domain {
1.852 albertel 10744: &load_hosts_tab() if (!$loaded);
10745:
1.844 albertel 10746: my ($lonid) = @_;
10747: return $hostdom{$lonid};
10748: }
10749:
1.841 albertel 10750: sub all_domains {
1.852 albertel 10751: &load_hosts_tab() if (!$loaded);
10752:
1.841 albertel 10753: my %seen;
10754: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10755: return @uniq;
10756: }
1.1074 raeburn 10757:
10758: sub internet_dom {
10759: &load_hosts_tab() if (!$loaded);
10760:
10761: my ($lonid) = @_;
10762: return $internetdom{$lonid};
10763: }
1.1107 raeburn 10764:
10765: sub is_LC_dns {
10766: &load_hosts_tab() if (!$loaded);
10767:
10768: my ($hostname) = @_;
10769: return exists($LC_dns_serv{$hostname});
10770: }
10771:
1.1 albertel 10772: }
10773:
1.847 albertel 10774: {
10775: my %iphost;
1.856 albertel 10776: my %name_to_ip;
10777: my %lonid_to_ip;
1.869 albertel 10778:
1.847 albertel 10779: sub get_hosts_from_ip {
10780: my ($ip) = @_;
10781: my %iphosts = &get_iphost();
10782: if (ref($iphosts{$ip})) {
10783: return @{$iphosts{$ip}};
10784: }
10785: return;
1.839 albertel 10786: }
1.864 albertel 10787:
10788: sub reset_hosts_ip_info {
10789: undef(%iphost);
10790: undef(%name_to_ip);
10791: undef(%lonid_to_ip);
10792: }
1.856 albertel 10793:
10794: sub get_host_ip {
10795: my ($lonid) = @_;
10796: if (exists($lonid_to_ip{$lonid})) {
10797: return $lonid_to_ip{$lonid};
10798: }
10799: my $name=&hostname($lonid);
10800: my $ip = gethostbyname($name);
10801: return if (!$ip || length($ip) ne 4);
10802: $ip=inet_ntoa($ip);
10803: $name_to_ip{$name} = $ip;
10804: $lonid_to_ip{$lonid} = $ip;
10805: return $ip;
10806: }
1.847 albertel 10807:
10808: sub get_iphost {
1.869 albertel 10809: my ($ignore_cache) = @_;
1.894 albertel 10810:
1.869 albertel 10811: if (!$ignore_cache) {
10812: if (%iphost) {
10813: return %iphost;
10814: }
10815: my ($ip_info,$cached)=
10816: &Apache::lonnet::is_cached_new('iphost','iphost');
10817: if ($cached) {
10818: %iphost = %{$ip_info->[0]};
10819: %name_to_ip = %{$ip_info->[1]};
10820: %lonid_to_ip = %{$ip_info->[2]};
10821: return %iphost;
10822: }
10823: }
1.894 albertel 10824:
10825: # get yesterday's info for fallback
10826: my %old_name_to_ip;
10827: my ($ip_info,$cached)=
10828: &Apache::lonnet::is_cached_new('iphost','iphost');
10829: if ($cached) {
10830: %old_name_to_ip = %{$ip_info->[1]};
10831: }
10832:
1.888 albertel 10833: my %name_to_host = &all_names();
10834: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10835: my $ip;
10836: if (!exists($name_to_ip{$name})) {
10837: $ip = gethostbyname($name);
10838: if (!$ip || length($ip) ne 4) {
1.894 albertel 10839: if (defined($old_name_to_ip{$name})) {
10840: $ip = $old_name_to_ip{$name};
10841: &logthis("Can't find $name defaulting to old $ip");
10842: } else {
10843: &logthis("Name $name no IP found");
10844: next;
10845: }
10846: } else {
10847: $ip=inet_ntoa($ip);
1.847 albertel 10848: }
10849: $name_to_ip{$name} = $ip;
10850: } else {
10851: $ip = $name_to_ip{$name};
1.653 albertel 10852: }
1.888 albertel 10853: foreach my $id (@{ $name_to_host{$name} }) {
10854: $lonid_to_ip{$id} = $ip;
10855: }
10856: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10857: }
1.869 albertel 10858: &Apache::lonnet::do_cache_new('iphost','iphost',
10859: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10860: 48*60*60);
1.869 albertel 10861:
1.847 albertel 10862: return %iphost;
1.598 albertel 10863: }
10864:
1.992 raeburn 10865: #
10866: # Given a DNS returns the loncapa host name for that DNS
10867: #
10868: sub host_from_dns {
10869: my ($dns) = @_;
10870: my @hosts;
10871: my $ip;
10872:
1.993 raeburn 10873: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10874: $ip = $name_to_ip{$dns};
10875: }
10876: if (!$ip) {
10877: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10878: if (length($ip) == 4) {
10879: $ip = &IO::Socket::inet_ntoa($ip);
10880: }
10881: }
10882: if ($ip) {
10883: @hosts = get_hosts_from_ip($ip);
10884: return $hosts[0];
10885: }
10886: return undef;
1.986 foxr 10887: }
1.992 raeburn 10888:
1.1074 raeburn 10889: sub get_internet_names {
10890: my ($lonid) = @_;
10891: return if ($lonid eq '');
10892: my ($idnref,$cached)=
10893: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10894: if ($cached) {
10895: return $idnref;
10896: }
10897: my $ip = &get_host_ip($lonid);
10898: my @hosts = &get_hosts_from_ip($ip);
10899: my %iphost = &get_iphost();
10900: my (@idns,%seen);
10901: foreach my $id (@hosts) {
10902: my $dom = &host_domain($id);
10903: my $prim_id = &domain($dom,'primary');
10904: my $prim_ip = &get_host_ip($prim_id);
10905: next if ($seen{$prim_ip});
10906: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10907: foreach my $id (@{$iphost{$prim_ip}}) {
10908: my $intdom = &internet_dom($id);
10909: unless (grep(/^\Q$intdom\E$/,@idns)) {
10910: push(@idns,$intdom);
10911: }
10912: }
10913: }
10914: $seen{$prim_ip} = 1;
10915: }
10916: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10917: }
10918:
1.986 foxr 10919: }
10920:
1.1079 raeburn 10921: sub all_loncaparevs {
10922: 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);
10923: }
10924:
1.862 albertel 10925: BEGIN {
10926:
10927: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10928: unless ($readit) {
10929: {
10930: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10931: %perlvar = (%perlvar,%{$configvars});
10932: }
10933:
10934:
1.1 albertel 10935: # ------------------------------------------------------ Read spare server file
10936: {
1.448 albertel 10937: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10938:
10939: while (my $configline=<$config>) {
10940: chomp($configline);
1.284 matthew 10941: if ($configline) {
1.784 albertel 10942: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10943: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10944: push(@{ $spareid{$type} }, $host);
1.1 albertel 10945: }
10946: }
1.448 albertel 10947: close($config);
1.1 albertel 10948: }
1.11 www 10949: # ------------------------------------------------------------ Read permissions
10950: {
1.448 albertel 10951: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10952:
10953: while (my $configline=<$config>) {
1.448 albertel 10954: chomp($configline);
10955: if ($configline) {
10956: my ($role,$perm)=split(/ /,$configline);
10957: if ($perm ne '') { $pr{$role}=$perm; }
10958: }
1.11 www 10959: }
1.448 albertel 10960: close($config);
1.11 www 10961: }
10962:
10963: # -------------------------------------------- Read plain texts for permissions
10964: {
1.448 albertel 10965: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10966:
10967: while (my $configline=<$config>) {
1.448 albertel 10968: chomp($configline);
10969: if ($configline) {
1.742 raeburn 10970: my ($short,@plain)=split(/:/,$configline);
10971: %{$prp{$short}} = ();
10972: if (@plain > 0) {
10973: $prp{$short}{'std'} = $plain[0];
10974: for (my $i=1; $i<@plain; $i++) {
10975: $prp{$short}{'alt'.$i} = $plain[$i];
10976: }
10977: }
1.448 albertel 10978: }
1.135 www 10979: }
1.448 albertel 10980: close($config);
1.135 www 10981: }
10982:
10983: # ---------------------------------------------------------- Read package table
10984: {
1.448 albertel 10985: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10986:
10987: while (my $configline=<$config>) {
1.483 albertel 10988: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10989: chomp($configline);
10990: my ($short,$plain)=split(/:/,$configline);
10991: my ($pack,$name)=split(/\&/,$short);
10992: if ($plain ne '') {
10993: $packagetab{$pack.'&'.$name.'&name'}=$name;
10994: $packagetab{$short}=$plain;
10995: }
1.11 www 10996: }
1.448 albertel 10997: close($config);
1.329 matthew 10998: }
10999:
1.1073 raeburn 11000: # ---------------------------------------------------------- Read loncaparev table
11001: {
11002: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11003: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11004: while (my $configline=<$config>) {
11005: chomp($configline);
11006: my ($hostid,$loncaparev)=split(/:/,$configline);
11007: $loncaparevs{$hostid}=$loncaparev;
11008: }
11009: close($config);
11010: }
11011: }
11012: }
11013:
1.1074 raeburn 11014: # ---------------------------------------------------------- Read serverhostID table
11015: {
11016: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11017: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11018: while (my $configline=<$config>) {
11019: chomp($configline);
11020: my ($name,$id)=split(/:/,$configline);
11021: $serverhomeIDs{$name}=$id;
11022: }
11023: close($config);
11024: }
11025: }
11026: }
11027:
1.1079 raeburn 11028: {
11029: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11030: if (-e $file) {
11031: my $parser = HTML::LCParser->new($file);
11032: while (my $token = $parser->get_token()) {
11033: if ($token->[0] eq 'S') {
11034: my $item = $token->[1];
11035: my $name = $token->[2]{'name'};
11036: my $value = $token->[2]{'value'};
11037: if ($item ne '' && $name ne '' && $value ne '') {
11038: my $release = $parser->get_text();
11039: $release =~ s/(^\s*|\s*$ )//gx;
11040: $needsrelease{$item.':'.$name.':'.$value} = $release;
11041: }
11042: }
11043: }
11044: }
1.1073 raeburn 11045: }
11046:
1.1138 raeburn 11047: # ---------------------------------------------------------- Read managers table
11048: {
11049: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11050: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11051: while (my $configline=<$config>) {
11052: chomp($configline);
11053: next if ($configline =~ /^\#/);
11054: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11055: $managerstab{$configline} = 1;
11056: }
11057: }
11058: close($config);
11059: }
11060: }
11061: }
11062:
1.329 matthew 11063: # ------------- set up temporary directory
11064: {
1.1117 foxr 11065: $tmpdir = LONCAPA::tempdir();
1.329 matthew 11066:
1.11 www 11067: }
11068:
1.794 albertel 11069: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11070: 'compress_threshold'=> 20_000,
11071: });
1.185 www 11072:
1.281 www 11073: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 11074: $dumpcount=0;
1.958 www 11075: $locknum=0;
1.22 www 11076:
1.163 harris41 11077: &logtouch();
1.672 albertel 11078: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 11079: $readit=1;
1.564 albertel 11080: {
11081: use integer;
11082: my $test=(2**32)+1;
1.568 albertel 11083: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 11084: &logthis(" Detected 64bit platform ($_64bit)");
11085: }
1.195 www 11086: }
1.1 albertel 11087: }
1.179 www 11088:
1.1 albertel 11089: 1;
1.191 harris41 11090: __END__
11091:
1.243 albertel 11092: =pod
11093:
1.191 harris41 11094: =head1 NAME
11095:
1.243 albertel 11096: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 11097:
11098: =head1 SYNOPSIS
11099:
1.243 albertel 11100: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 11101:
11102: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11103:
1.243 albertel 11104: Common parameters:
11105:
11106: =over 4
11107:
11108: =item *
11109:
11110: $uname : an internal username (if $cname expecting a course Id specifically)
11111:
11112: =item *
11113:
11114: $udom : a domain (if $cdom expecting a course's domain specifically)
11115:
11116: =item *
11117:
11118: $symb : a resource instance identifier
11119:
11120: =item *
11121:
11122: $namespace : the name of a .db file that contains the data needed or
11123: being set.
11124:
11125: =back
11126:
1.394 bowersj2 11127: =head1 OVERVIEW
1.191 harris41 11128:
1.394 bowersj2 11129: lonnet provides subroutines which interact with the
11130: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11131: about classes, users, and resources.
1.243 albertel 11132:
11133: For many of these objects you can also use this to store data about
11134: them or modify them in various ways.
1.191 harris41 11135:
1.394 bowersj2 11136: =head2 Symbs
1.191 harris41 11137:
1.394 bowersj2 11138: To identify a specific instance of a resource, LON-CAPA uses symbols
11139: or "symbs"X<symb>. These identifiers are built from the URL of the
11140: map, the resource number of the resource in the map, and the URL of
11141: the resource itself. The latter is somewhat redundant, but might help
11142: if maps change.
11143:
11144: An example is
11145:
11146: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11147:
11148: The respective map entry is
11149:
11150: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11151: title="Problem 2">
11152: </resource>
11153:
11154: Symbs are used by the random number generator, as well as to store and
11155: restore data specific to a certain instance of for example a problem.
11156:
11157: =head2 Storing And Retrieving Data
11158:
11159: X<store()>X<cstore()>X<restore()>Three of the most important functions
11160: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11161: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11162: is is the non-critical message twin of cstore. These functions are for
11163: handlers to store a perl hash to a user's permanent data space in an
11164: easy manner, and to retrieve it again on another call. It is expected
11165: that a handler would use this once at the beginning to retrieve data,
11166: and then again once at the end to send only the new data back.
11167:
11168: The data is stored in the user's data directory on the user's
11169: homeserver under the ID of the course.
11170:
11171: The hash that is returned by restore will have all of the previous
11172: value for all of the elements of the hash.
11173:
11174: Example:
11175:
11176: #creating a hash
11177: my %hash;
11178: $hash{'foo'}='bar';
11179:
11180: #storing it
11181: &Apache::lonnet::cstore(\%hash);
11182:
11183: #changing a value
11184: $hash{'foo'}='notbar';
11185:
11186: #adding a new value
11187: $hash{'bar'}='foo';
11188: &Apache::lonnet::cstore(\%hash);
11189:
11190: #retrieving the hash
11191: my %history=&Apache::lonnet::restore();
11192:
11193: #print the hash
11194: foreach my $key (sort(keys(%history))) {
11195: print("\%history{$key} = $history{$key}");
11196: }
11197:
11198: Will print out:
1.191 harris41 11199:
1.394 bowersj2 11200: %history{1:foo} = bar
11201: %history{1:keys} = foo:timestamp
11202: %history{1:timestamp} = 990455579
11203: %history{2:bar} = foo
11204: %history{2:foo} = notbar
11205: %history{2:keys} = foo:bar:timestamp
11206: %history{2:timestamp} = 990455580
11207: %history{bar} = foo
11208: %history{foo} = notbar
11209: %history{timestamp} = 990455580
11210: %history{version} = 2
11211:
11212: Note that the special hash entries C<keys>, C<version> and
11213: C<timestamp> were added to the hash. C<version> will be equal to the
11214: total number of versions of the data that have been stored. The
11215: C<timestamp> attribute will be the UNIX time the hash was
11216: stored. C<keys> is available in every historical section to list which
11217: keys were added or changed at a specific historical revision of a
11218: hash.
11219:
11220: B<Warning>: do not store the hash that restore returns directly. This
11221: will cause a mess since it will restore the historical keys as if the
11222: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 11223:
1.394 bowersj2 11224: Calling convention:
1.191 harris41 11225:
1.394 bowersj2 11226: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11227: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 11228:
1.394 bowersj2 11229: For more detailed information, see lonnet specific documentation.
1.191 harris41 11230:
1.394 bowersj2 11231: =head1 RETURN MESSAGES
1.191 harris41 11232:
1.394 bowersj2 11233: =over 4
1.191 harris41 11234:
1.394 bowersj2 11235: =item * B<con_lost>: unable to contact remote host
1.191 harris41 11236:
1.394 bowersj2 11237: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11238: when the connection is brought back up
1.191 harris41 11239:
1.394 bowersj2 11240: =item * B<con_failed>: unable to contact remote host and unable to save message
11241: for later delivery
1.191 harris41 11242:
1.967 bisitz 11243: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 11244:
1.394 bowersj2 11245: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 11246: that was requested
1.191 harris41 11247:
1.243 albertel 11248: =back
1.191 harris41 11249:
1.243 albertel 11250: =head1 PUBLIC SUBROUTINES
1.191 harris41 11251:
1.243 albertel 11252: =head2 Session Environment Functions
1.191 harris41 11253:
1.243 albertel 11254: =over 4
1.191 harris41 11255:
1.394 bowersj2 11256: =item *
11257: X<appenv()>
1.949 raeburn 11258: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 11259: the user envirnoment file, and will be restored for each access this
1.620 albertel 11260: user makes during this session, also modifies the %env for the current
1.949 raeburn 11261: process. Optional rolesarrayref - if defined contains a reference to an array
11262: of roles which are exempt from the restriction on modifying user.role entries
11263: in the user's environment.db and in %env.
1.191 harris41 11264:
11265: =item *
1.394 bowersj2 11266: X<delenv()>
1.987 raeburn 11267: B<delenv($delthis,$regexp)>: removes all items from the session
11268: environment file that begin with $delthis. If the
11269: optional second arg - $regexp - is true, $delthis is treated as a
11270: regular expression, otherwise \Q$delthis\E is used.
11271: The values are also deleted from the current processes %env.
1.191 harris41 11272:
1.795 albertel 11273: =item * get_env_multiple($name)
11274:
11275: gets $name from the %env hash, it seemlessly handles the cases where multiple
11276: values may be defined and end up as an array ref.
11277:
11278: returns an array of values
11279:
1.243 albertel 11280: =back
11281:
11282: =head2 User Information
1.191 harris41 11283:
1.243 albertel 11284: =over 4
1.191 harris41 11285:
11286: =item *
1.394 bowersj2 11287: X<queryauthenticate()>
11288: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 11289: authentication scheme
11290:
11291: =item *
1.394 bowersj2 11292: X<authenticate()>
1.1073 raeburn 11293: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 11294: authenticate user from domain's lib servers (first use the current
11295: one). C<$upass> should be the users password.
1.1073 raeburn 11296: $checkdefauth is optional (value is 1 if a check should be made to
11297: authenticate user using default authentication method, and allow
11298: account creation if username does not have account in the domain).
11299: $clientcancheckhost is optional (value is 1 if checking whether the
11300: server can host will occur on the client side in lonauth.pm).
1.191 harris41 11301:
11302: =item *
1.394 bowersj2 11303: X<homeserver()>
11304: B<homeserver($uname,$udom)>: find the server which has
11305: the user's directory and files (there must be only one), this caches
11306: the answer, and also caches if there is a borken connection.
1.191 harris41 11307:
11308: =item *
1.394 bowersj2 11309: X<idget()>
11310: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11311: (IDs are a unique resource in a domain, there must be only 1 ID per
11312: username, and only 1 username per ID in a specific domain) (returns
11313: hash: id=>name,id=>name)
1.191 harris41 11314:
11315: =item *
1.394 bowersj2 11316: X<idrget()>
11317: B<idrget($udom,@unames)>: find the IDs behind a list of
11318: usernames (returns hash: name=>id,name=>id)
1.191 harris41 11319:
11320: =item *
1.394 bowersj2 11321: X<idput()>
11322: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 11323:
11324: =item *
1.394 bowersj2 11325: X<rolesinit()>
11326: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 11327:
11328: =item *
1.551 albertel 11329: X<getsection()>
11330: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 11331: course $cname, return section name/number or '' for "not in course"
11332: and '-1' for "no section"
11333:
11334: =item *
1.394 bowersj2 11335: X<userenvironment()>
11336: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 11337: passed in @what from the requested user's environment, returns a hash
11338:
1.858 raeburn 11339: =item *
11340: X<userlog_query()>
1.859 albertel 11341: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11342: activity.log file. %filters defines filters applied when parsing the
11343: log file. These can be start or end timestamps, or the type of action
11344: - log to look for Login or Logout events, check for Checkin or
11345: Checkout, role for role selection. The response is in the form
11346: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11347: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 11348:
1.243 albertel 11349: =back
11350:
11351: =head2 User Roles
11352:
11353: =over 4
11354:
11355: =item *
11356:
1.810 raeburn 11357: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 11358: F: full access
11359: U,I,K: authentication modes (cxx only)
11360: '': forbidden
11361: 1: user needs to choose course
11362: 2: browse allowed
1.766 albertel 11363: A: passphrase authentication needed
1.243 albertel 11364:
11365: =item *
11366:
11367: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11368: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11369: and course level
11370:
11371: =item *
11372:
1.988 raeburn 11373: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11374: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 11375: $type is Course (default) or Community.
1.988 raeburn 11376: If $forcedefault evaluates to true, text returned will be default
11377: text for $type. Otherwise, if this is a course, the text returned
11378: will be a custom name for the role (if defined in the course's
11379: environment). If no custom name is defined the default is returned.
11380:
1.832 raeburn 11381: =item *
11382:
1.935 raeburn 11383: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 11384: All arguments are optional. Returns a hash of a roles, either for
11385: co-author/assistant author roles for a user's Construction Space
1.906 albertel 11386: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 11387: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11388: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11389: For each key, value is set to colon-separated start and end times for
11390: the role. If no username and domain are specified, will default to
1.934 raeburn 11391: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 11392: of role statuses (active, future or previous), roles
11393: (e.g., cc,in, st etc.) and domains of the roles which can be used
11394: to restrict the list of roles reported. If no array ref is
11395: provided for types, will default to return only active roles.
1.834 albertel 11396:
1.243 albertel 11397: =back
11398:
11399: =head2 User Modification
11400:
11401: =over 4
11402:
11403: =item *
11404:
1.957 raeburn 11405: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 11406: user for the level given by URL. Optional start and end dates (leave empty
11407: string or zero for "no date")
1.191 harris41 11408:
11409: =item *
11410:
1.243 albertel 11411: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11412: change a users, password, possible return values are: ok,
11413: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11414: refused
1.191 harris41 11415:
11416: =item *
11417:
1.243 albertel 11418: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 11419:
11420: =item *
11421:
1.1058 raeburn 11422: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11423: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11424:
11425: will update user information (firstname,middlename,lastname,generation,
11426: permanentemail), and if forceid is true, student/employee ID also.
11427: A user's institutional affiliation(s) can also be updated.
11428: User information fields will not be overwritten with empty entries
11429: unless the field is included in the $candelete array reference.
11430: This array is included when a single user is modified via "Manage Users",
11431: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 11432:
11433: =item *
11434:
1.286 matthew 11435: modifystudent
11436:
1.957 raeburn 11437: modify a student's enrollment and identification information.
1.286 matthew 11438: The course id is resolved based on the current users environment.
11439: This means the envoking user must be a course coordinator or otherwise
11440: associated with a course.
11441:
1.297 matthew 11442: This call is essentially a wrapper for lonnet::modifyuser and
11443: lonnet::modify_student_enrollment
1.286 matthew 11444:
11445: Inputs:
11446:
11447: =over 4
11448:
1.957 raeburn 11449: =item B<$udom> Student's loncapa domain
1.286 matthew 11450:
1.957 raeburn 11451: =item B<$uname> Student's loncapa login name
1.286 matthew 11452:
1.964 bisitz 11453: =item B<$uid> Student/Employee ID
1.286 matthew 11454:
1.957 raeburn 11455: =item B<$umode> Student's authentication mode
1.286 matthew 11456:
1.957 raeburn 11457: =item B<$upass> Student's password
1.286 matthew 11458:
1.957 raeburn 11459: =item B<$first> Student's first name
1.286 matthew 11460:
1.957 raeburn 11461: =item B<$middle> Student's middle name
1.286 matthew 11462:
1.957 raeburn 11463: =item B<$last> Student's last name
1.286 matthew 11464:
1.957 raeburn 11465: =item B<$gene> Student's generation
1.286 matthew 11466:
1.957 raeburn 11467: =item B<$usec> Student's section in course
1.286 matthew 11468:
11469: =item B<$end> Unix time of the roles expiration
11470:
11471: =item B<$start> Unix time of the roles start date
11472:
11473: =item B<$forceid> If defined, allow $uid to be changed
11474:
11475: =item B<$desiredhome> server to use as home server for student
11476:
1.957 raeburn 11477: =item B<$email> Student's permanent e-mail address
11478:
11479: =item B<$type> Type of enrollment (auto or manual)
11480:
1.963 raeburn 11481: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11482:
11483: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 11484:
1.963 raeburn 11485: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 11486:
1.963 raeburn 11487: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 11488:
1.963 raeburn 11489: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 11490:
1.286 matthew 11491: =back
1.297 matthew 11492:
11493: =item *
11494:
11495: modify_student_enrollment
11496:
11497: Change a students enrollment status in a class. The environment variable
11498: 'role.request.course' must be defined for this function to proceed.
11499:
11500: Inputs:
11501:
11502: =over 4
11503:
11504: =item $udom, students domain
11505:
11506: =item $uname, students name
11507:
11508: =item $uid, students user id
11509:
11510: =item $first, students first name
11511:
11512: =item $middle
11513:
11514: =item $last
11515:
11516: =item $gene
11517:
11518: =item $usec
11519:
11520: =item $end
11521:
11522: =item $start
11523:
1.957 raeburn 11524: =item $type
11525:
11526: =item $locktype
11527:
11528: =item $cid
11529:
11530: =item $selfenroll
11531:
11532: =item $context
11533:
1.297 matthew 11534: =back
11535:
1.191 harris41 11536:
11537: =item *
11538:
1.243 albertel 11539: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11540: custom role; give a custom role to a user for the level given by URL. Specify
11541: name and domain of role author, and role name
1.191 harris41 11542:
11543: =item *
11544:
1.243 albertel 11545: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 11546:
11547: =item *
11548:
1.243 albertel 11549: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11550:
11551: =back
11552:
11553: =head2 Course Infomation
11554:
11555: =over 4
1.191 harris41 11556:
11557: =item *
11558:
1.1118 foxr 11559: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 11560: specified course id, including all environment settings for the
11561: course, the description of the course will be in the hash under the
11562: key 'description'
1.191 harris41 11563:
1.1118 foxr 11564: $options is an optional parameter that if supplied is a hash reference that controls
11565: what how this function works. It has the following key/values:
11566:
11567: =over 4
11568:
11569: =item freshen_cache
11570:
11571: If defined, and the environment cache for the course is valid, it is
11572: returned in the returned hash.
11573:
11574: =item one_time
11575:
11576: If defined, the last cache time is set to _now_
11577:
11578: =item user
11579:
11580: If defined, the supplied username is used instead of the current user.
11581:
11582:
11583: =back
11584:
1.191 harris41 11585: =item *
11586:
1.624 albertel 11587: resdata($name,$domain,$type,@which) : request for current parameter
11588: setting for a specific $type, where $type is either 'course' or 'user',
11589: @what should be a list of parameters to ask about. This routine caches
11590: answers for 5 minutes.
1.243 albertel 11591:
1.877 foxr 11592: =item *
11593:
11594: get_courseresdata($courseid, $domain) : dump the entire course resource
11595: data base, returning a hash that is keyed by the resource name and has
11596: values that are the resource value. I believe that the timestamps and
11597: versions are also returned.
11598:
11599:
1.243 albertel 11600: =back
11601:
11602: =head2 Course Modification
11603:
11604: =over 4
1.191 harris41 11605:
11606: =item *
11607:
1.243 albertel 11608: writecoursepref($courseid,%prefs) : write preferences (environment
11609: database) for a course
1.191 harris41 11610:
11611: =item *
11612:
1.1011 raeburn 11613: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11614:
11615: =item *
11616:
1.1038 raeburn 11617: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 11618:
11619: =back
11620:
11621: =head2 Resource Subroutines
11622:
11623: =over 4
1.191 harris41 11624:
11625: =item *
11626:
1.243 albertel 11627: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 11628:
11629: =item *
11630:
1.243 albertel 11631: repcopy($filename) : subscribes to the requested file, and attempts to
11632: replicate from the owning library server, Might return
1.607 raeburn 11633: 'unavailable', 'not_found', 'forbidden', 'ok', or
11634: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 11635: resource. Expects the local filesystem pathname
11636: (/home/httpd/html/res/....)
11637:
11638: =back
11639:
11640: =head2 Resource Information
11641:
11642: =over 4
1.191 harris41 11643:
11644: =item *
11645:
1.243 albertel 11646: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11647: a vairety of different possible values, $varname should be a request
11648: string, and the other parameters can be used to specify who and what
11649: one is asking about.
11650:
11651: Possible values for $varname are environment.lastname (or other item
11652: from the envirnment hash), user.name (or someother aspect about the
11653: user), resource.0.maxtries (or some other part and parameter of a
11654: resource)
1.204 albertel 11655:
11656: =item *
11657:
1.243 albertel 11658: directcondval($number) : get current value of a condition; reads from a state
11659: string
1.204 albertel 11660:
11661: =item *
11662:
1.243 albertel 11663: condval($condidx) : value of condition index based on state
1.204 albertel 11664:
11665: =item *
11666:
1.243 albertel 11667: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11668: resource's metadata, $what should be either a specific key, or either
11669: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11670: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11671:
11672: this function automatically caches all requests
1.191 harris41 11673:
11674: =item *
11675:
1.243 albertel 11676: metadata_query($query,$custom,$customshow) : make a metadata query against the
11677: network of library servers; returns file handle of where SQL and regex results
11678: will be stored for query
1.191 harris41 11679:
11680: =item *
11681:
1.243 albertel 11682: symbread($filename) : return symbolic list entry (filename argument optional);
11683: returns the data handle
1.191 harris41 11684:
11685: =item *
11686:
1.243 albertel 11687: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 11688: a possible symb for the URL in $thisfn, and if is an encryypted
11689: resource that the user accessed using /enc/ returns a 1 on success, 0
11690: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 11691: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 11692:
1.191 harris41 11693:
11694: =item *
11695:
1.243 albertel 11696: symbclean($symb) : removes versions numbers from a symb, returns the
11697: cleaned symb
1.191 harris41 11698:
11699: =item *
11700:
1.243 albertel 11701: is_on_map($uri) : checks if the $uri is somewhere on the current
11702: course map, user must be in a course for it to work.
1.191 harris41 11703:
11704: =item *
11705:
1.243 albertel 11706: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 11707:
11708: =item *
11709:
1.243 albertel 11710: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11711: a random seed, all arguments are optional, if they aren't sent it uses the
11712: environment to derive them. Note: if symb isn't sent and it can't get one
11713: from &symbread it will use the current time as its return value
1.191 harris41 11714:
11715: =item *
11716:
1.243 albertel 11717: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11718: unfakeable, receipt
1.191 harris41 11719:
11720: =item *
11721:
1.620 albertel 11722: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11723:
11724: =item *
11725:
1.243 albertel 11726: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11727:
11728: =item *
11729:
1.243 albertel 11730: 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 11731:
11732: =item *
11733:
1.243 albertel 11734: 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 11735:
11736: =item *
11737:
1.243 albertel 11738: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11739:
11740: =item *
11741:
1.243 albertel 11742: devalidate($symb) : devalidate temporary spreadsheet calculations,
11743: forcing spreadsheet to reevaluate the resource scores next time.
11744:
11745: =back
11746:
11747: =head2 Storing/Retreiving Data
11748:
11749: =over 4
1.191 harris41 11750:
11751: =item *
11752:
1.243 albertel 11753: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11754: for this url; hashref needs to be given and should be a \%hashname; the
11755: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11756: be derived from the env
1.191 harris41 11757:
11758: =item *
11759:
1.243 albertel 11760: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11761: uses critical subroutine
1.191 harris41 11762:
11763: =item *
11764:
1.243 albertel 11765: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11766: all args are optional
1.191 harris41 11767:
11768: =item *
11769:
1.717 albertel 11770: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11771: dumps the complete (or key matching regexp) namespace into a hash
11772: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11773: normally &store()ed into
11774:
11775: $range should be either an integer '100' (give me the first 100
11776: matching records)
11777: or be two integers sperated by a - with no spaces
11778: '30-50' (give me the 30th through the 50th matching
11779: records)
11780:
11781:
11782: =item *
11783:
11784: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11785: replaces a &store() version of data with a replacement set of data
11786: for a particular resource in a namespace passed in the $storehash hash
11787: reference
11788:
11789: =item *
11790:
1.243 albertel 11791: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11792: works very similar to store/cstore, but all data is stored in a
11793: temporary location and can be reset using tmpreset, $storehash should
11794: be a hash reference, returns nothing on success
1.191 harris41 11795:
11796: =item *
11797:
1.243 albertel 11798: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11799: similar to restore, but all data is stored in a temporary location and
11800: can be reset using tmpreset. Returns a hash of values on success,
11801: error string otherwise.
1.191 harris41 11802:
11803: =item *
11804:
1.243 albertel 11805: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11806: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11807:
11808: =item *
11809:
1.243 albertel 11810: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11811: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11812:
11813: =item *
11814:
1.243 albertel 11815: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11816: namesp ($udom and $uname are optional)
1.191 harris41 11817:
11818: =item *
11819:
1.702 albertel 11820: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11821: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11822: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11823:
1.702 albertel 11824: $range should be either an integer '100' (give me the first 100
11825: matching records)
11826: or be two integers sperated by a - with no spaces
11827: '30-50' (give me the 30th through the 50th matching
11828: records)
1.449 matthew 11829: =item *
11830:
11831: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11832: $store can be a scalar, an array reference, or if the amount to be
11833: incremented is > 1, a hash reference.
11834:
11835: ($udom and $uname are optional)
1.191 harris41 11836:
11837: =item *
11838:
1.243 albertel 11839: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11840: ($udom and $uname are optional)
1.191 harris41 11841:
11842: =item *
11843:
1.243 albertel 11844: cput($namespace,$storehash,$udom,$uname) : critical put
11845: ($udom and $uname are optional)
1.191 harris41 11846:
11847: =item *
11848:
1.748 albertel 11849: newput($namespace,$storehash,$udom,$uname) :
11850:
11851: Attempts to store the items in the $storehash, but only if they don't
11852: currently exist, if this succeeds you can be certain that you have
11853: successfully created a new key value pair in the $namespace db.
11854:
11855:
11856: Args:
11857: $namespace: name of database to store values to
11858: $storehash: hashref to store to the db
11859: $udom: (optional) domain of user containing the db
11860: $uname: (optional) name of user caontaining the db
11861:
11862: Returns:
11863: 'ok' -> succeeded in storing all keys of $storehash
11864: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11865: least <key> already existed in the db (other
11866: requested keys may also already exist)
1.967 bisitz 11867: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11868: 'con_lost' -> unable to contact request server
11869: 'refused' -> action was not allowed by remote machine
11870:
11871:
11872: =item *
11873:
1.243 albertel 11874: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11875: reference filled in from namesp (encrypts the return communication)
11876: ($udom and $uname are optional)
1.191 harris41 11877:
11878: =item *
11879:
1.243 albertel 11880: log($udom,$name,$home,$message) : write to permanent log for user; use
11881: critical subroutine
11882:
1.806 raeburn 11883: =item *
11884:
1.860 raeburn 11885: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11886: array reference filled in from namespace found in domain level on either
11887: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11888:
11889: =item *
11890:
1.860 raeburn 11891: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11892: domain level either on specified domain server ($uhome) or primary domain
11893: server ($udom and $uhome are optional)
1.806 raeburn 11894:
1.943 raeburn 11895: =item *
11896:
11897: get_domain_defaults($target_domain) : returns hash with defaults for
11898: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11899: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11900: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11901: Values are retrieved from cache (if current), or from domain's configuration.db
11902: (if available), or lastly from values in lonTabs/dns_domain,tab,
11903: or lonTabs/domain.tab.
11904:
11905: %domdefaults = &get_auth_defaults($target_domain);
11906:
1.243 albertel 11907: =back
11908:
11909: =head2 Network Status Functions
11910:
11911: =over 4
1.191 harris41 11912:
11913: =item *
11914:
1.1137 raeburn 11915: dirlist() : return directory list based on URI (first arg).
11916:
11917: Inputs: 1 required, 5 optional.
11918:
11919: =over
11920:
11921: =item
11922: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
11923:
11924: =item
11925: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
11926:
11927: =item
11928: $username - username of user/course to be listed. Extracted from $uri if absent.
11929:
11930: =item
11931: $getpropath - boolean: 1 if prepend path using &propath().
11932:
11933: =item
11934: $getuserdir - boolean: 1 if prepend path for "userfiles".
11935:
11936: =item
11937: $alternateRoot - path to prepend in place of path from $uri.
11938:
11939: =back
11940:
11941: Returns: Array of up to two items.
11942:
11943: =over
11944:
11945: a reference to an array of files/subdirectories
11946:
11947: =over
11948:
11949: Each element in the array of files/subdirectories is a & separated list of
11950: item name and the result of running stat on the item. If dirlist was requested
11951: for a file instead of a directory, the item name will be ''. For a directory
11952: listing, if the item is a metadata file, the element will end &N&M
11953: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
11954: default copyright set (1).
11955:
11956: =back
11957:
11958: a scalar containing error condition (if encountered).
11959:
11960: =over
11961:
11962: =item
11963: no_host (no homeserver identified for $username:$domain).
11964:
11965: =item
11966: no_such_host (server contacted for listing not identified as valid host).
11967:
11968: =item
11969: con_lost (connection to remote server failed).
11970:
11971: =item
11972: refused (invalid $username:$domain received on lond side).
11973:
11974: =item
11975: no_such_dir (directory at specified path on lond side does not exist).
11976:
11977: =item
11978: empty (directory at specified path on lond side is empty).
11979:
11980: =over
11981:
11982: This is currently not encountered because the &ls3, &ls2,
11983: &ls (_handler) routines on the lond side do not filter out
11984: . and .. from a directory listing.
11985:
11986: =back
11987:
11988: =back
11989:
11990: =back
1.191 harris41 11991:
11992: =item *
11993:
1.243 albertel 11994: spareserver() : find server with least workload from spare.tab
11995:
1.986 foxr 11996:
11997: =item *
11998:
11999: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12000: if there is no corresponding loncapa host.
12001:
1.243 albertel 12002: =back
12003:
1.986 foxr 12004:
1.243 albertel 12005: =head2 Apache Request
12006:
12007: =over 4
1.191 harris41 12008:
12009: =item *
12010:
1.243 albertel 12011: ssi($url,%hash) : server side include, does a complete request cycle on url to
12012: localhost, posts hash
12013:
12014: =back
12015:
12016: =head2 Data to String to Data
12017:
12018: =over 4
1.191 harris41 12019:
12020: =item *
12021:
1.243 albertel 12022: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12023: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 12024:
12025: =item *
12026:
1.243 albertel 12027: hashref2str($hashref) : convert a hashref into a string complete with
12028: escaping and '=' and '&' separators, supports elements that are
12029: arrayrefs and hashrefs
1.191 harris41 12030:
12031: =item *
12032:
1.243 albertel 12033: arrayref2str($arrayref) : convert an arrayref into a string complete
12034: with escaping and '&' separators, supports elements that are arrayrefs
12035: and hashrefs
1.191 harris41 12036:
12037: =item *
12038:
1.243 albertel 12039: str2hash($string) : convert string to hash using unescaping and
12040: splitting on '=' and '&', supports elements that are arrayrefs and
12041: hashrefs
1.191 harris41 12042:
12043: =item *
12044:
1.243 albertel 12045: str2array($string) : convert string to hash using unescaping and
12046: splitting on '&', supports elements that are arrayrefs and hashrefs
12047:
12048: =back
12049:
12050: =head2 Logging Routines
12051:
12052:
12053: These routines allow one to make log messages in the lonnet.log and
12054: lonnet.perm logfiles.
1.191 harris41 12055:
1.1119 foxr 12056: =over 4
12057:
1.191 harris41 12058: =item *
12059:
1.243 albertel 12060: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 12061:
12062: =item *
12063:
1.243 albertel 12064: logthis() : append message to the normal lonnet.log file, it gets
12065: preiodically rolled over and deleted.
1.191 harris41 12066:
12067: =item *
12068:
1.243 albertel 12069: logperm() : append a permanent message to lonnet.perm.log, this log
12070: file never gets deleted by any automated portion of the system, only
12071: messages of critical importance should go in here.
12072:
1.1119 foxr 12073:
1.243 albertel 12074: =back
12075:
12076: =head2 General File Helper Routines
12077:
12078: =over 4
1.191 harris41 12079:
12080: =item *
12081:
1.481 raeburn 12082: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12083: (a) files in /uploaded
12084: (i) If a local copy of the file exists -
12085: compares modification date of local copy with last-modified date for
12086: definitive version stored on home server for course. If local copy is
12087: stale, requests a new version from the home server and stores it.
12088: If the original has been removed from the home server, then local copy
12089: is unlinked.
12090: (ii) If local copy does not exist -
12091: requests the file from the home server and stores it.
12092:
12093: If $caller is 'uploadrep':
12094: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12095: for request for files originally uploaded via DOCS.
12096: - returns 'ok' if fresh local copy now available, -1 otherwise.
12097:
12098: Otherwise:
12099: This indicates a call from the content generation phase of the request.
12100: - returns the entire contents of the file or -1.
12101:
12102: (b) files in /res
12103: - returns the entire contents of a file or -1;
12104: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 12105:
1.712 albertel 12106:
12107: =item *
12108:
12109: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12110: reference
12111:
12112: returns either a stat() list of data about the file or an empty list
12113: if the file doesn't exist or couldn't find out about it (connection
12114: problems or user unknown)
12115:
1.191 harris41 12116: =item *
12117:
1.243 albertel 12118: filelocation($dir,$file) : returns file system location of a file
12119: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12120: directory that relative $file lookups are to looked in ($dir of /a/dir
12121: and a file of ../bob will become /a/bob)
1.191 harris41 12122:
12123: =item *
12124:
12125: hreflocation($dir,$file) : returns file system location or a URL; same as
12126: filelocation except for hrefs
12127:
12128: =item *
12129:
12130: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12131:
1.243 albertel 12132: =back
12133:
1.608 albertel 12134: =head2 Usererfile file routines (/uploaded*)
12135:
12136: =over 4
12137:
12138: =item *
12139:
12140: userfileupload(): main rotine for putting a file in a user or course's
12141: filespace, arguments are,
12142:
1.620 albertel 12143: formname - required - this is the name of the element in $env where the
1.608 albertel 12144: filename, and the contents of the file to create/modifed exist
1.620 albertel 12145: the filename is in $env{'form.'.$formname.'.filename'} and the
12146: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 12147: context - if coursedoc, store the file in the course of the active role
12148: of the current user;
12149: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12150: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 12151: subdir - required - subdirectory to put the file in under ../userfiles/
12152: if undefined, it will be placed in "unknown"
12153:
12154: (This routine calls clean_filename() to remove any dangerous
12155: characters from the filename, and then calls finuserfileupload() to
12156: complete the transaction)
12157:
12158: returns either the url of the uploaded file (/uploaded/....) if successful
12159: and /adm/notfound.html if unsuccessful
12160:
12161: =item *
12162:
12163: clean_filename(): routine for cleaing a filename up for storage in
12164: userfile space, argument is:
12165:
12166: filename - proposed filename
12167:
12168: returns: the new clean filename
12169:
12170: =item *
12171:
1.1090 raeburn 12172: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 12173: userspace, probably shouldn't be called directly
12174:
12175: docuname: username or courseid of destination for the file
12176: docudom: domain of user/course of destination for the file
12177: formname: same as for userfileupload()
1.1090 raeburn 12178: fname: filename (including subdirectories) for the file
12179: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12180: allfiles: reference to hash used to store objects found by parser
12181: codebase: reference to hash used for codebases of java objects found by parser
12182: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12183: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12184: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12185: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12186: context: if 'overwrite', will move the uploaded file from its temporary location to
12187: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 12188: mimetype: reference to scalar to accommodate mime type determined
12189: from File::MMagic if $parser = parse.
1.608 albertel 12190:
12191: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 12192: and /adm/notfound.html if unsuccessful (or an error message if context
12193: was 'overwrite').
12194:
1.608 albertel 12195:
12196: =item *
12197:
12198: renameuserfile(): renames an existing userfile to a new name
12199:
12200: Args:
12201: docuname: username or courseid of destination for the file
12202: docudom: domain of user/course of destination for the file
12203: old: current file name (including any subdirs under userfiles)
12204: new: desired file name (including any subdirs under userfiles)
12205:
12206: =item *
12207:
12208: mkdiruserfile(): creates a directory is a userfiles dir
12209:
12210: Args:
12211: docuname: username or courseid of destination for the file
12212: docudom: domain of user/course of destination for the file
12213: dir: dir to create (including any subdirs under userfiles)
12214:
12215: =item *
12216:
12217: removeuserfile(): removes a file that exists in userfiles
12218:
12219: Args:
12220: docuname: username or courseid of destination for the file
12221: docudom: domain of user/course of destination for the file
12222: fname: filname to delete (including any subdirs under userfiles)
12223:
12224: =item *
12225:
12226: removeuploadedurl(): convience function for removeuserfile()
12227:
12228: Args:
12229: url: a full /uploaded/... url to delete
12230:
1.747 albertel 12231: =item *
12232:
12233: get_portfile_permissions():
12234: Args:
12235: domain: domain of user or course contain the portfolio files
12236: user: name of user or num of course contain the portfolio files
12237: Returns:
12238: hashref of a dump of the proper file_permissions.db
12239:
12240:
12241: =item *
12242:
12243: get_access_controls():
12244:
12245: Args:
12246: current_permissions: the hash ref returned from get_portfile_permissions()
12247: group: (optional) the group you want the files associated with
12248: file: (optional) the file you want access info on
12249:
12250: Returns:
1.749 raeburn 12251: a hash (keys are file names) of hashes containing
12252: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12253: values are XML containing access control settings (see below)
1.747 albertel 12254:
12255: Internal notes:
12256:
1.749 raeburn 12257: access controls are stored in file_permissions.db as key=value pairs.
12258: key -> path to file/file_name\0uniqueID:scope_end_start
12259: where scope -> public,guest,course,group,domains or users.
12260: end -> UNIX time for end of access (0 -> no end date)
12261: start -> UNIX time for start of access
12262:
12263: value -> XML description of access control
12264: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12265: <start></start>
12266: <end></end>
12267:
12268: <password></password> for scope type = guest
12269:
12270: <domain></domain> for scope type = course or group
12271: <number></number>
12272: <roles id="">
12273: <role></role>
12274: <access></access>
12275: <section></section>
12276: <group></group>
12277: </roles>
12278:
12279: <dom></dom> for scope type = domains
12280:
12281: <users> for scope type = users
12282: <user>
12283: <uname></uname>
12284: <udom></udom>
12285: </user>
12286: </users>
12287: </scope>
12288:
12289: Access data is also aggregated for each file in an additional key=value pair:
12290: key -> path to file/file_name\0accesscontrol
12291: value -> reference to hash
12292: hash contains key = value pairs
12293: where key = uniqueID:scope_end_start
12294: value = UNIX time record was last updated
12295:
12296: Used to improve speed of look-ups of access controls for each file.
12297:
12298: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12299:
12300: modify_access_controls():
12301:
12302: Modifies access controls for a portfolio file
12303: Args
12304: 1. file name
12305: 2. reference to hash of required changes,
12306: 3. domain
12307: 4. username
12308: where domain,username are the domain of the portfolio owner
12309: (either a user or a course)
12310:
12311: Returns:
12312: 1. result of additions or updates ('ok' or 'error', with error message).
12313: 2. result of deletions ('ok' or 'error', with error message).
12314: 3. reference to hash of any new or updated access controls.
12315: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12316: key = integer (inbound ID)
12317: value = uniqueID
1.747 albertel 12318:
1.608 albertel 12319: =back
12320:
1.243 albertel 12321: =head2 HTTP Helper Routines
12322:
12323: =over 4
12324:
1.191 harris41 12325: =item *
12326:
12327: escape() : unpack non-word characters into CGI-compatible hex codes
12328:
12329: =item *
12330:
12331: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12332:
1.243 albertel 12333: =back
12334:
12335: =head1 PRIVATE SUBROUTINES
12336:
12337: =head2 Underlying communication routines (Shouldn't call)
12338:
12339: =over 4
12340:
12341: =item *
12342:
12343: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12344:
12345: =item *
12346:
12347: reply() : uses subreply to send a message to remote machine, logs all failures
12348:
12349: =item *
12350:
12351: critical() : passes a critical message to another server; if cannot
12352: get through then place message in connection buffer directory and
12353: returns con_delayed, if incapable of saving message, returns
12354: con_failed
12355:
12356: =item *
12357:
12358: reconlonc() : tries to reconnect lonc client processes.
12359:
12360: =back
12361:
12362: =head2 Resource Access Logging
12363:
12364: =over 4
12365:
12366: =item *
12367:
12368: flushcourselogs() : flush (save) buffer logs and access logs
12369:
12370: =item *
12371:
12372: courselog($what) : save message for course in hash
12373:
12374: =item *
12375:
12376: courseacclog($what) : save message for course using &courselog(). Perform
12377: special processing for specific resource types (problems, exams, quizzes, etc).
12378:
1.191 harris41 12379: =item *
12380:
12381: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12382: as a PerlChildExitHandler
1.243 albertel 12383:
12384: =back
12385:
12386: =head2 Other
12387:
12388: =over 4
12389:
12390: =item *
12391:
12392: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 12393:
12394: =back
12395:
12396: =cut
1.877 foxr 12397:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>