File:
[LON-CAPA] /
loncom /
lonnet /
perl /
lonnet.pm
Revision
1.1219:
download - view:
text,
annotated -
select for diffs
Thu Apr 11 15:30:42 2013 UTC (11 years, 4 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Efficiency improvements when checking if course personnel should be hidden.
- Identity of privileged users (i.e., dc) in a domain cached in memcache.
- Added course setting -- checkforpriv -- which includes comma separated
list of domains to check for privileged users (besides course's domain).
- Fix some xhtml in courseprefs.pm to satisfy w3c validation
- loncommon::select_dom_form() takes additional (optional) argument --
array ref of domains to exclude from options in the dropdown list.
- lonnet.pm -- eliminate Apache::lonnet:: from some calls to
do_cache_new() within lonnet.pm itself.
1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1219 2013/04/11 15:30:42 raeburn Exp $
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: #
28: ###
29:
30: =pod
31:
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:
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:
71: package Apache::lonnet;
72:
73: use strict;
74: use LWP::UserAgent();
75: use HTTP::Date;
76: use Image::Magick;
77:
78:
79: use Encode;
80:
81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
88: %courseownerbuf, %coursetypebuf,$locknum);
89:
90: use IO::Socket;
91: use GDBM_File;
92: use HTML::LCParser;
93: use Fcntl qw(:flock);
94: use Storable qw(thaw nfreeze);
95: use Time::HiRes qw( gettimeofday tv_interval );
96: use Cache::Memcached;
97: use Digest::MD5;
98: use Math::Random;
99: use File::MMagic;
100: use LONCAPA qw(:DEFAULT :match);
101: use LONCAPA::Configuration;
102: use LONCAPA::lonmetadata;
103: use LONCAPA::Lond;
104:
105: use File::Copy;
106:
107: my $readit;
108: my $max_connection_retries = 10; # Or some such value.
109:
110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
115:
116: # ------------------------------------ Logging (parameters, docs, slots, roles)
117: {
118: my $logid;
119: sub write_log {
120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
126: }
127: $logid ++;
128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
130: my $logentry = {
131: $id => {
132: 'exe_uname' => $env{'user.name'},
133: 'exe_udom' => $env{'user.domain'},
134: 'exe_time' => $now,
135: 'exe_ip' => $ENV{'REMOTE_ADDR'},
136: 'delflag' => $delflag,
137: 'logentry' => $storehash,
138: 'uname' => $uname,
139: 'udom' => $udom,
140: }
141: };
142: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
143: }
144: }
145:
146: sub logtouch {
147: my $execdir=$perlvar{'lonDaemons'};
148: unless (-e "$execdir/logs/lonnet.log") {
149: open(my $fh,">>$execdir/logs/lonnet.log");
150: close $fh;
151: }
152: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
153: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
154: }
155:
156: sub logthis {
157: my $message=shift;
158: my $execdir=$perlvar{'lonDaemons'};
159: my $now=time;
160: my $local=localtime($now);
161: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
162: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
163: print $fh $logstring;
164: close($fh);
165: }
166: return 1;
167: }
168:
169: sub logperm {
170: my $message=shift;
171: my $execdir=$perlvar{'lonDaemons'};
172: my $now=time;
173: my $local=localtime($now);
174: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
175: print $fh "$now:$message:$local\n";
176: close($fh);
177: }
178: return 1;
179: }
180:
181: sub create_connection {
182: my ($hostname,$lonid) = @_;
183: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
184: Type => SOCK_STREAM,
185: Timeout => 10);
186: return 0 if (!$client);
187: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
188: my $result = <$client>;
189: chomp($result);
190: return 1 if ($result eq 'done');
191: return 0;
192: }
193:
194: sub get_server_timezone {
195: my ($cnum,$cdom) = @_;
196: my $home=&homeserver($cnum,$cdom);
197: if ($home ne 'no_host') {
198: my $cachetime = 24*3600;
199: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
200: if (defined($cached)) {
201: return $timezone;
202: } else {
203: my $timezone = &reply('servertimezone',$home);
204: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
205: }
206: }
207: }
208:
209: sub get_server_distarch {
210: my ($lonhost,$ignore_cache) = @_;
211: if (defined($lonhost)) {
212: if (!defined(&hostname($lonhost))) {
213: return;
214: }
215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
218: if (defined($cached)) {
219: return $distarch;
220: }
221: }
222: my $rep = &reply('serverdistarch',$lonhost);
223: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
224: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
225: $rep eq '') {
226: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
227: }
228: }
229: return;
230: }
231:
232: sub get_server_loncaparev {
233: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
234: if (defined($lonhost)) {
235: if (!defined(&hostname($lonhost))) {
236: undef($lonhost);
237: }
238: }
239: if (!defined($lonhost)) {
240: if (defined(&domain($dom,'primary'))) {
241: $lonhost=&domain($dom,'primary');
242: if ($lonhost eq 'no_host') {
243: undef($lonhost);
244: }
245: }
246: }
247: if (defined($lonhost)) {
248: my $cachetime = 12*3600;
249: if (!$ignore_cache) {
250: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
251: if (defined($cached)) {
252: return $loncaparev;
253: }
254: }
255: my ($answer,$loncaparev);
256: my @ids=¤t_machine_ids();
257: if (grep(/^\Q$lonhost\E$/,@ids)) {
258: $answer = $perlvar{'lonVersion'};
259: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
260: $loncaparev = $1;
261: }
262: } else {
263: $answer = &reply('serverloncaparev',$lonhost);
264: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
265: if ($caller eq 'loncron') {
266: my $ua=new LWP::UserAgent;
267: $ua->timeout(4);
268: my $protocol = $protocol{$lonhost};
269: $protocol = 'http' if ($protocol ne 'https');
270: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
271: my $request=new HTTP::Request('GET',$url);
272: my $response=$ua->request($request);
273: unless ($response->is_error()) {
274: my $content = $response->content;
275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
283: $loncaparev = $1;
284: }
285: }
286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
287: }
288: }
289:
290: sub get_server_homeID {
291: my ($hostname,$ignore_cache,$caller) = @_;
292: unless ($ignore_cache) {
293: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
294: if (defined($cached)) {
295: return $serverhomeID;
296: }
297: }
298: my $cachetime = 12*3600;
299: my $serverhomeID;
300: if ($caller eq 'loncron') {
301: my @machine_ids = &machine_ids($hostname);
302: foreach my $id (@machine_ids) {
303: my $response = &reply('serverhomeID',$id);
304: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
305: $serverhomeID = $response;
306: last;
307: }
308: }
309: if ($serverhomeID eq '') {
310: $serverhomeID = $machine_ids[-1];
311: }
312: } else {
313: $serverhomeID = $serverhomeIDs{$hostname};
314: }
315: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
316: }
317:
318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
324: my ($response,$cached);
325: unless ($ignore_cache) {
326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
327: }
328: if (defined($cached)) {
329: $returnhash{$what} = $response;
330: } else {
331: $whatneeded{$what} = 1;
332: }
333: }
334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
344: my @pairs=split(/\&/,$rep);
345: foreach my $item (@pairs) {
346: my ($key,$value)=split(/=/,$item,2);
347: my $what = &unescape($key);
348: my $hashid = $lonhost.'-'.$what;
349: $returnhash{$what}=&thaw_unescape($value);
350: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
351: }
352: }
353: }
354: }
355: return ($result,\%returnhash);
356: }
357:
358: sub remote_devalidate_cache {
359: my ($lonhost,$name,$id) = @_;
360: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
361: return $response;
362: }
363:
364: # -------------------------------------------------- Non-critical communication
365: sub subreply {
366: my ($cmd,$server)=@_;
367: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
368: #
369: # With loncnew process trimming, there's a timing hole between lonc server
370: # process exit and the master server picking up the listen on the AF_UNIX
371: # socket. In that time interval, a lock file will exist:
372:
373: my $lockfile=$peerfile.".lock";
374: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
375: sleep(1);
376: }
377: # At this point, either a loncnew parent is listening or an old lonc
378: # or loncnew child is listening so we can connect or everything's dead.
379: #
380: # We'll give the connection a few tries before abandoning it. If
381: # connection is not possible, we'll con_lost back to the client.
382: #
383: my $client;
384: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
385: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
386: Type => SOCK_STREAM,
387: Timeout => 10);
388: if ($client) {
389: last; # Connected!
390: } else {
391: &create_connection(&hostname($server),$server);
392: }
393: sleep(1); # Try again later if failed connection.
394: }
395: my $answer;
396: if ($client) {
397: print $client "sethost:$server:$cmd\n";
398: $answer=<$client>;
399: if (!$answer) { $answer="con_lost"; }
400: chomp($answer);
401: } else {
402: $answer = 'con_lost'; # Failed connection.
403: }
404: return $answer;
405: }
406:
407: sub reply {
408: my ($cmd,$server)=@_;
409: unless (defined(&hostname($server))) { return 'no_such_host'; }
410: my $answer=subreply($cmd,$server);
411: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
412: &logthis("<font color=\"blue\">WARNING:".
413: " $cmd to $server returned $answer</font>");
414: }
415: return $answer;
416: }
417:
418: # ----------------------------------------------------------- Send USR1 to lonc
419:
420: sub reconlonc {
421: my ($lonid) = @_;
422: my $hostname = &hostname($lonid);
423: if ($lonid) {
424: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
425: if ($hostname && -e $peerfile) {
426: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
427: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
428: Type => SOCK_STREAM,
429: Timeout => 10);
430: if ($client) {
431: print $client ("reset_retries\n");
432: my $answer=<$client>;
433: #reset just this one.
434: }
435: }
436: return;
437: }
438:
439: &logthis("Trying to reconnect lonc");
440: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
441: if (open(my $fh,"<$loncfile")) {
442: my $loncpid=<$fh>;
443: chomp($loncpid);
444: if (kill 0 => $loncpid) {
445: &logthis("lonc at pid $loncpid responding, sending USR1");
446: kill USR1 => $loncpid;
447: sleep 1;
448: } else {
449: &logthis(
450: "<font color=\"blue\">WARNING:".
451: " lonc at pid $loncpid not responding, giving up</font>");
452: }
453: } else {
454: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
455: }
456: }
457:
458: # ------------------------------------------------------ Critical communication
459:
460: sub critical {
461: my ($cmd,$server)=@_;
462: unless (&hostname($server)) {
463: &logthis("<font color=\"blue\">WARNING:".
464: " Critical message to unknown server ($server)</font>");
465: return 'no_such_host';
466: }
467: my $answer=reply($cmd,$server);
468: if ($answer eq 'con_lost') {
469: &reconlonc("$perlvar{'lonSockDir'}/$server");
470: my $answer=reply($cmd,$server);
471: if ($answer eq 'con_lost') {
472: my $now=time;
473: my $middlename=$cmd;
474: $middlename=substr($middlename,0,16);
475: $middlename=~s/\W//g;
476: my $dfilename=
477: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
478: $dumpcount++;
479: {
480: my $dfh;
481: if (open($dfh,">$dfilename")) {
482: print $dfh "$cmd\n";
483: close($dfh);
484: }
485: }
486: sleep 2;
487: my $wcmd='';
488: {
489: my $dfh;
490: if (open($dfh,"<$dfilename")) {
491: $wcmd=<$dfh>;
492: close($dfh);
493: }
494: }
495: chomp($wcmd);
496: if ($wcmd eq $cmd) {
497: &logthis("<font color=\"blue\">WARNING: ".
498: "Connection buffer $dfilename: $cmd</font>");
499: &logperm("D:$server:$cmd");
500: return 'con_delayed';
501: } else {
502: &logthis("<font color=\"red\">CRITICAL:"
503: ." Critical connection failed: $server $cmd</font>");
504: &logperm("F:$server:$cmd");
505: return 'con_failed';
506: }
507: }
508: }
509: return $answer;
510: }
511:
512: # ------------------------------------------- check if return value is an error
513:
514: sub error {
515: my ($result) = @_;
516: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
517: if ($2 == 2) { return undef; }
518: return $1;
519: }
520: return undef;
521: }
522:
523: sub convert_and_load_session_env {
524: my ($lonidsdir,$handle)=@_;
525: my @profile;
526: {
527: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
528: if (!$opened) {
529: return 0;
530: }
531: flock($idf,LOCK_SH);
532: @profile=<$idf>;
533: close($idf);
534: }
535: my %temp_env;
536: foreach my $line (@profile) {
537: if ($line !~ m/=/) {
538: return 0;
539: }
540: chomp($line);
541: my ($envname,$envvalue)=split(/=/,$line,2);
542: $temp_env{&unescape($envname)} = &unescape($envvalue);
543: }
544: unlink("$lonidsdir/$handle.id");
545: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
546: 0640)) {
547: %disk_env = %temp_env;
548: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
549: untie(%disk_env);
550: }
551: return 1;
552: }
553:
554: # ------------------------------------------- Transfer profile into environment
555: my $env_loaded;
556: sub transfer_profile_to_env {
557: my ($lonidsdir,$handle,$force_transfer) = @_;
558: if (!$force_transfer && $env_loaded) { return; }
559:
560: if (!defined($lonidsdir)) {
561: $lonidsdir = $perlvar{'lonIDsDir'};
562: }
563: if (!defined($handle)) {
564: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
565: }
566:
567: my $convert;
568: {
569: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
570: if (!$opened) {
571: return;
572: }
573: flock($idf,LOCK_SH);
574: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
575: &GDBM_READER(),0640)) {
576: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
577: untie(%disk_env);
578: } else {
579: $convert = 1;
580: }
581: }
582: if ($convert) {
583: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
584: &logthis("Failed to load session, or convert session.");
585: }
586: }
587:
588: my %remove;
589: while ( my $envname = each(%env) ) {
590: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
591: if ($time < time-300) {
592: $remove{$key}++;
593: }
594: }
595: }
596:
597: $env{'user.environment'} = "$lonidsdir/$handle.id";
598: $env_loaded=1;
599: foreach my $expired_key (keys(%remove)) {
600: &delenv($expired_key);
601: }
602: }
603:
604: # ---------------------------------------------------- Check for valid session
605: sub check_for_valid_session {
606: my ($r,$name) = @_;
607: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
608: if ($name eq '') {
609: $name = 'lonID';
610: }
611: my $lonid=$cookies{$name};
612: return undef if (!$lonid);
613:
614: my $handle=&LONCAPA::clean_handle($lonid->value);
615: my $lonidsdir;
616: if ($name eq 'lonDAV') {
617: $lonidsdir=$r->dir_config('lonDAVsessDir');
618: } else {
619: $lonidsdir=$r->dir_config('lonIDsDir');
620: }
621: return undef if (!-e "$lonidsdir/$handle.id");
622:
623: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
624: return undef if (!$opened);
625:
626: flock($idf,LOCK_SH);
627: my %disk_env;
628: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
629: &GDBM_READER(),0640)) {
630: return undef;
631: }
632:
633: if (!defined($disk_env{'user.name'})
634: || !defined($disk_env{'user.domain'})) {
635: return undef;
636: }
637: if (($r->user() eq '') && ($apache >= 2.4)) {
638: if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
639: $r->user($disk_env{'user.name'});
640: } else {
641: $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
642: }
643: }
644: return $handle;
645: }
646:
647: sub timed_flock {
648: my ($file,$lock_type) = @_;
649: my $failed=0;
650: eval {
651: local $SIG{__DIE__}='DEFAULT';
652: local $SIG{ALRM}=sub {
653: $failed=1;
654: die("failed lock");
655: };
656: alarm(13);
657: flock($file,$lock_type);
658: alarm(0);
659: };
660: if ($failed) {
661: return undef;
662: } else {
663: return 1;
664: }
665: }
666:
667: # ---------------------------------------------------------- Append Environment
668:
669: sub appenv {
670: my ($newenv,$roles) = @_;
671: if (ref($newenv) eq 'HASH') {
672: foreach my $key (keys(%{$newenv})) {
673: my $refused = 0;
674: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
675: $refused = 1;
676: if (ref($roles) eq 'ARRAY') {
677: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
678: if (grep(/^\Q$role\E$/,@{$roles})) {
679: $refused = 0;
680: }
681: }
682: }
683: if ($refused) {
684: &logthis("<font color=\"blue\">WARNING: ".
685: "Attempt to modify environment ".$key." to ".$newenv->{$key}
686: .'</font>');
687: delete($newenv->{$key});
688: } else {
689: $env{$key}=$newenv->{$key};
690: }
691: }
692: my $opened = open(my $env_file,'+<',$env{'user.environment'});
693: if ($opened
694: && &timed_flock($env_file,LOCK_EX)
695: &&
696: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
697: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
698: while (my ($key,$value) = each(%{$newenv})) {
699: $disk_env{$key} = $value;
700: }
701: untie(%disk_env);
702: }
703: }
704: return 'ok';
705: }
706: # ----------------------------------------------------- Delete from Environment
707:
708: sub delenv {
709: my ($delthis,$regexp,$roles) = @_;
710: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
711: my $refused = 1;
712: if (ref($roles) eq 'ARRAY') {
713: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
714: if (grep(/^\Q$role\E$/,@{$roles})) {
715: $refused = 0;
716: }
717: }
718: if ($refused) {
719: &logthis("<font color=\"blue\">WARNING: ".
720: "Attempt to delete from environment ".$delthis);
721: return 'error';
722: }
723: }
724: my $opened = open(my $env_file,'+<',$env{'user.environment'});
725: if ($opened
726: && &timed_flock($env_file,LOCK_EX)
727: &&
728: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
729: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
730: foreach my $key (keys(%disk_env)) {
731: if ($regexp) {
732: if ($key=~/^$delthis/) {
733: delete($env{$key});
734: delete($disk_env{$key});
735: }
736: } else {
737: if ($key=~/^\Q$delthis\E/) {
738: delete($env{$key});
739: delete($disk_env{$key});
740: }
741: }
742: }
743: untie(%disk_env);
744: }
745: return 'ok';
746: }
747:
748: sub get_env_multiple {
749: my ($name) = @_;
750: my @values;
751: if (defined($env{$name})) {
752: # exists is it an array
753: if (ref($env{$name})) {
754: @values=@{ $env{$name} };
755: } else {
756: $values[0]=$env{$name};
757: }
758: }
759: return(@values);
760: }
761:
762: # ------------------------------------------------------------------- Locking
763:
764: sub set_lock {
765: my ($text)=@_;
766: $locknum++;
767: my $id=$$.'-'.$locknum;
768: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
769: 'session.lock.'.$id => $text});
770: return $id;
771: }
772:
773: sub get_locks {
774: my $num=0;
775: my %texts=();
776: foreach my $lock (split(/\,/,$env{'session.locks'})) {
777: if ($lock=~/\w/) {
778: $num++;
779: $texts{$lock}=$env{'session.lock.'.$lock};
780: }
781: }
782: return ($num,%texts);
783: }
784:
785: sub remove_lock {
786: my ($id)=@_;
787: my $newlocks='';
788: foreach my $lock (split(/\,/,$env{'session.locks'})) {
789: if (($lock=~/\w/) && ($lock ne $id)) {
790: $newlocks.=','.$lock;
791: }
792: }
793: &appenv({'session.locks' => $newlocks});
794: &delenv('session.lock.'.$id);
795: }
796:
797: sub remove_all_locks {
798: my $activelocks=$env{'session.locks'};
799: foreach my $lock (split(/\,/,$env{'session.locks'})) {
800: if ($lock=~/\w/) {
801: &remove_lock($lock);
802: }
803: }
804: }
805:
806:
807: # ------------------------------------------ Find out current server userload
808: sub userload {
809: my $numusers=0;
810: {
811: opendir(LONIDS,$perlvar{'lonIDsDir'});
812: my $filename;
813: my $curtime=time;
814: while ($filename=readdir(LONIDS)) {
815: next if ($filename eq '.' || $filename eq '..');
816: next if ($filename =~ /publicuser_\d+\.id/);
817: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
818: if ($curtime-$mtime < 1800) { $numusers++; }
819: }
820: closedir(LONIDS);
821: }
822: my $userloadpercent=0;
823: my $maxuserload=$perlvar{'lonUserLoadLim'};
824: if ($maxuserload) {
825: $userloadpercent=100*$numusers/$maxuserload;
826: }
827: $userloadpercent=sprintf("%.2f",$userloadpercent);
828: return $userloadpercent;
829: }
830:
831: # ------------------------------ Find server with least workload from spare.tab
832:
833: sub spareserver {
834: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
835: my $spare_server;
836: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
837: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
838: : $userloadpercent;
839: my ($uint_dom,$remotesessions);
840: if (($udom ne '') && (&domain($udom) ne '')) {
841: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
842: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
843: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
844: $remotesessions = $udomdefaults{'remotesessions'};
845: }
846: my $spareshash = &this_host_spares($udom);
847: if (ref($spareshash) eq 'HASH') {
848: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
849: foreach my $try_server (@{ $spareshash->{'primary'} }) {
850: if ($uint_dom) {
851: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
852: $try_server));
853: }
854: ($spare_server, $lowest_load) =
855: &compare_server_load($try_server, $spare_server, $lowest_load);
856: }
857: }
858:
859: my $found_server = ($spare_server ne '' && $lowest_load < 100);
860:
861: if (!$found_server) {
862: if (ref($spareshash->{'default'}) eq 'ARRAY') {
863: foreach my $try_server (@{ $spareshash->{'default'} }) {
864: if ($uint_dom) {
865: next unless (&spare_can_host($udom,$uint_dom,
866: $remotesessions,$try_server));
867: }
868: ($spare_server, $lowest_load) =
869: &compare_server_load($try_server, $spare_server, $lowest_load);
870: }
871: }
872: }
873: }
874:
875: if (!$want_server_name) {
876: my $protocol = 'http';
877: if ($protocol{$spare_server} eq 'https') {
878: $protocol = $protocol{$spare_server};
879: }
880: if (defined($spare_server)) {
881: my $hostname = &hostname($spare_server);
882: if (defined($hostname)) {
883: $spare_server = $protocol.'://'.$hostname;
884: }
885: }
886: }
887: return $spare_server;
888: }
889:
890: sub compare_server_load {
891: my ($try_server, $spare_server, $lowest_load) = @_;
892:
893: my $loadans = &reply('load', $try_server);
894: my $userloadans = &reply('userload',$try_server);
895:
896: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
897: return ($spare_server, $lowest_load); #didn't get a number from the server
898: }
899:
900: my $load;
901: if ($loadans =~ /\d/) {
902: if ($userloadans =~ /\d/) {
903: #both are numbers, pick the bigger one
904: $load = ($loadans > $userloadans) ? $loadans
905: : $userloadans;
906: } else {
907: $load = $loadans;
908: }
909: } else {
910: $load = $userloadans;
911: }
912:
913: if (($load =~ /\d/) && ($load < $lowest_load)) {
914: $spare_server = $try_server;
915: $lowest_load = $load;
916: }
917: return ($spare_server,$lowest_load);
918: }
919:
920: # --------------------------- ask offload servers if user already has a session
921: sub find_existing_session {
922: my ($udom,$uname) = @_;
923: my $spareshash = &this_host_spares($udom);
924: if (ref($spareshash) eq 'HASH') {
925: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
926: foreach my $try_server (@{ $spareshash->{'primary'} }) {
927: return $try_server if (&has_user_session($try_server, $udom, $uname));
928: }
929: }
930: if (ref($spareshash->{'default'}) eq 'ARRAY') {
931: foreach my $try_server (@{ $spareshash->{'default'} }) {
932: return $try_server if (&has_user_session($try_server, $udom, $uname));
933: }
934: }
935: }
936: return;
937: }
938:
939: # -------------------------------- ask if server already has a session for user
940: sub has_user_session {
941: my ($lonid,$udom,$uname) = @_;
942: my $result = &reply(join(':','userhassession',
943: map {&escape($_)} ($udom,$uname)),$lonid);
944: return 1 if ($result eq 'ok');
945:
946: return 0;
947: }
948:
949: # --------- determine least loaded server in a user's domain which allows login
950:
951: sub choose_server {
952: my ($udom,$checkloginvia) = @_;
953: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
954: my %servers = &get_servers($udom);
955: my $lowest_load = 30000;
956: my ($login_host,$hostname,$portal_path,$isredirect);
957: foreach my $lonhost (keys(%servers)) {
958: my $loginvia;
959: if ($checkloginvia) {
960: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
961: if ($loginvia) {
962: my ($server,$path) = split(/:/,$loginvia);
963: ($login_host, $lowest_load) =
964: &compare_server_load($server, $login_host, $lowest_load);
965: if ($login_host eq $server) {
966: $portal_path = $path;
967: $isredirect = 1;
968: }
969: } else {
970: ($login_host, $lowest_load) =
971: &compare_server_load($lonhost, $login_host, $lowest_load);
972: if ($login_host eq $lonhost) {
973: $portal_path = '';
974: $isredirect = '';
975: }
976: }
977: } else {
978: ($login_host, $lowest_load) =
979: &compare_server_load($lonhost, $login_host, $lowest_load);
980: }
981: }
982: if ($login_host ne '') {
983: $hostname = &hostname($login_host);
984: }
985: return ($login_host,$hostname,$portal_path,$isredirect);
986: }
987:
988: # --------------------------------------------- Try to change a user's password
989:
990: sub changepass {
991: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
992: $currentpass = &escape($currentpass);
993: $newpass = &escape($newpass);
994: my $lonhost = $perlvar{'lonHostID'};
995: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
996: $server);
997: if (! $answer) {
998: &logthis("No reply on password change request to $server ".
999: "by $uname in domain $udom.");
1000: } elsif ($answer =~ "^ok") {
1001: &logthis("$uname in $udom successfully changed their password ".
1002: "on $server.");
1003: } elsif ($answer =~ "^pwchange_failure") {
1004: &logthis("$uname in $udom was unable to change their password ".
1005: "on $server. The action was blocked by either lcpasswd ".
1006: "or pwchange");
1007: } elsif ($answer =~ "^non_authorized") {
1008: &logthis("$uname in $udom did not get their password correct when ".
1009: "attempting to change it on $server.");
1010: } elsif ($answer =~ "^auth_mode_error") {
1011: &logthis("$uname in $udom attempted to change their password despite ".
1012: "not being locally or internally authenticated on $server.");
1013: } elsif ($answer =~ "^unknown_user") {
1014: &logthis("$uname in $udom attempted to change their password ".
1015: "on $server but were unable to because $server is not ".
1016: "their home server.");
1017: } elsif ($answer =~ "^refused") {
1018: &logthis("$server refused to change $uname in $udom password because ".
1019: "it was sent an unencrypted request to change the password.");
1020: } elsif ($answer =~ "invalid_client") {
1021: &logthis("$server refused to change $uname in $udom password because ".
1022: "it was a reset by e-mail originating from an invalid server.");
1023: }
1024: return $answer;
1025: }
1026:
1027: # ----------------------- Try to determine user's current authentication scheme
1028:
1029: sub queryauthenticate {
1030: my ($uname,$udom)=@_;
1031: my $uhome=&homeserver($uname,$udom);
1032: if (!$uhome) {
1033: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1034: return 'no_host';
1035: }
1036: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1037: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1038: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1039: }
1040: return $answer;
1041: }
1042:
1043: # --------- Try to authenticate user from domain's lib servers (first this one)
1044:
1045: sub authenticate {
1046: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1047: $upass=&escape($upass);
1048: $uname= &LONCAPA::clean_username($uname);
1049: my $uhome=&homeserver($uname,$udom,1);
1050: my $newhome;
1051: if ((!$uhome) || ($uhome eq 'no_host')) {
1052: # Maybe the machine was offline and only re-appeared again recently?
1053: &reconlonc();
1054: # One more
1055: $uhome=&homeserver($uname,$udom,1);
1056: if (($uhome eq 'no_host') && $checkdefauth) {
1057: if (defined(&domain($udom,'primary'))) {
1058: $newhome=&domain($udom,'primary');
1059: }
1060: if ($newhome ne '') {
1061: $uhome = $newhome;
1062: }
1063: }
1064: if ((!$uhome) || ($uhome eq 'no_host')) {
1065: &logthis("User $uname at $udom is unknown in authenticate");
1066: return 'no_host';
1067: }
1068: }
1069: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1070: if ($answer eq 'authorized') {
1071: if ($newhome) {
1072: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1073: return 'no_account_on_host';
1074: } else {
1075: &logthis("User $uname at $udom authorized by $uhome");
1076: return $uhome;
1077: }
1078: }
1079: if ($answer eq 'non_authorized') {
1080: &logthis("User $uname at $udom rejected by $uhome");
1081: return 'no_host';
1082: }
1083: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1084: return 'no_host';
1085: }
1086:
1087: sub can_host_session {
1088: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1089: my $canhost = 1;
1090: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1091: if (ref($remotesessions) eq 'HASH') {
1092: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1093: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1094: $canhost = 0;
1095: } else {
1096: $canhost = 1;
1097: }
1098: }
1099: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1100: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1101: $canhost = 1;
1102: } else {
1103: $canhost = 0;
1104: }
1105: }
1106: if ($canhost) {
1107: if ($remotesessions->{'version'} ne '') {
1108: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1109: if ($reqmajor ne '' && $reqminor ne '') {
1110: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1111: my $major = $1;
1112: my $minor = $2;
1113: if (($major < $reqmajor ) ||
1114: (($major == $reqmajor) && ($minor < $reqminor))) {
1115: $canhost = 0;
1116: }
1117: } else {
1118: $canhost = 0;
1119: }
1120: }
1121: }
1122: }
1123: }
1124: if ($canhost) {
1125: if (ref($hostedsessions) eq 'HASH') {
1126: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1127: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1128: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1129: if (($uint_dom ne '') &&
1130: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1131: $canhost = 0;
1132: } else {
1133: $canhost = 1;
1134: }
1135: }
1136: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1137: if (($uint_dom ne '') &&
1138: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1139: $canhost = 1;
1140: } else {
1141: $canhost = 0;
1142: }
1143: }
1144: }
1145: }
1146: return $canhost;
1147: }
1148:
1149: sub spare_can_host {
1150: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1151: my $canhost=1;
1152: my @intdoms;
1153: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1154: if (ref($internet_names) eq 'ARRAY') {
1155: @intdoms = @{$internet_names};
1156: }
1157: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1158: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1159: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1160: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1161: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1162: $canhost = &can_host_session($udom,$try_server,$remoterev,
1163: $remotesessions,
1164: $defdomdefaults{'hostedsessions'});
1165: }
1166: return $canhost;
1167: }
1168:
1169: sub this_host_spares {
1170: my ($dom) = @_;
1171: my ($dom_in_use,$lonhost_in_use,$result);
1172: my @hosts = ¤t_machine_ids();
1173: foreach my $lonhost (@hosts) {
1174: if (&host_domain($lonhost) eq $dom) {
1175: $dom_in_use = $dom;
1176: $lonhost_in_use = $lonhost;
1177: last;
1178: }
1179: }
1180: if ($dom_in_use ne '') {
1181: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1182: }
1183: if (ref($result) ne 'HASH') {
1184: $lonhost_in_use = $perlvar{'lonHostID'};
1185: $dom_in_use = &host_domain($lonhost_in_use);
1186: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1187: if (ref($result) ne 'HASH') {
1188: $result = \%spareid;
1189: }
1190: }
1191: return $result;
1192: }
1193:
1194: sub spares_for_offload {
1195: my ($dom_in_use,$lonhost_in_use) = @_;
1196: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1197: if (defined($cached)) {
1198: return $result;
1199: } else {
1200: my $cachetime = 60*60*24;
1201: my %domconfig =
1202: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1203: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1204: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1205: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1206: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1207: }
1208: }
1209: }
1210: }
1211: return;
1212: }
1213:
1214: sub get_lonbalancer_config {
1215: my ($servers) = @_;
1216: my ($currbalancer,$currtargets);
1217: if (ref($servers) eq 'HASH') {
1218: foreach my $server (keys(%{$servers})) {
1219: my %what = (
1220: spareid => 1,
1221: perlvar => 1,
1222: );
1223: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1224: if ($result eq 'ok') {
1225: if (ref($returnhash) eq 'HASH') {
1226: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1227: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1228: $currbalancer = $server;
1229: $currtargets = {};
1230: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1231: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1232: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1233: }
1234: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1235: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1236: }
1237: }
1238: last;
1239: }
1240: }
1241: }
1242: }
1243: }
1244: }
1245: return ($currbalancer,$currtargets);
1246: }
1247:
1248: sub check_loadbalancing {
1249: my ($uname,$udom) = @_;
1250: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1251: $rule_in_effect,$offloadto,$otherserver);
1252: my $lonhost = $perlvar{'lonHostID'};
1253: my @hosts = ¤t_machine_ids();
1254: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1255: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1256: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1257: my $serverhomedom = &host_domain($lonhost);
1258:
1259: my $cachetime = 60*60*24;
1260:
1261: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1262: $dom_in_use = $udom;
1263: $homeintdom = 1;
1264: } else {
1265: $dom_in_use = $serverhomedom;
1266: }
1267: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1268: unless (defined($cached)) {
1269: my %domconfig =
1270: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1271: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1272: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1273: }
1274: }
1275: if (ref($result) eq 'HASH') {
1276: ($is_balancer,$currtargets,$currrules) =
1277: &check_balancer_result($result,@hosts);
1278: if ($is_balancer) {
1279: if (ref($currrules) eq 'HASH') {
1280: if ($homeintdom) {
1281: if ($uname ne '') {
1282: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1283: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1284: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1285: $rule_in_effect = $currrules->{'_LC_author'};
1286: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1287: $rule_in_effect = $currrules->{'_LC_adv'}
1288: }
1289: }
1290: if ($rule_in_effect eq '') {
1291: my %userenv = &userenvironment($udom,$uname,'inststatus');
1292: if ($userenv{'inststatus'} ne '') {
1293: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1294: my ($othertitle,$usertypes,$types) =
1295: &Apache::loncommon::sorted_inst_types($udom);
1296: if (ref($types) eq 'ARRAY') {
1297: foreach my $type (@{$types}) {
1298: if (grep(/^\Q$type\E$/,@statuses)) {
1299: if (exists($currrules->{$type})) {
1300: $rule_in_effect = $currrules->{$type};
1301: }
1302: }
1303: }
1304: }
1305: } else {
1306: if (exists($currrules->{'default'})) {
1307: $rule_in_effect = $currrules->{'default'};
1308: }
1309: }
1310: }
1311: } else {
1312: if (exists($currrules->{'default'})) {
1313: $rule_in_effect = $currrules->{'default'};
1314: }
1315: }
1316: } else {
1317: if ($currrules->{'_LC_external'} ne '') {
1318: $rule_in_effect = $currrules->{'_LC_external'};
1319: }
1320: }
1321: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1322: $uname,$udom);
1323: }
1324: }
1325: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1326: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1327: unless (defined($cached)) {
1328: my %domconfig =
1329: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1330: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1331: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1332: }
1333: }
1334: if (ref($result) eq 'HASH') {
1335: ($is_balancer,$currtargets,$currrules) =
1336: &check_balancer_result($result,@hosts);
1337: if ($is_balancer) {
1338: if (ref($currrules) eq 'HASH') {
1339: if ($currrules->{'_LC_internetdom'} ne '') {
1340: $rule_in_effect = $currrules->{'_LC_internetdom'};
1341: }
1342: }
1343: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1344: $uname,$udom);
1345: }
1346: } else {
1347: if ($perlvar{'lonBalancer'} eq 'yes') {
1348: $is_balancer = 1;
1349: $offloadto = &this_host_spares($dom_in_use);
1350: }
1351: }
1352: } else {
1353: if ($perlvar{'lonBalancer'} eq 'yes') {
1354: $is_balancer = 1;
1355: $offloadto = &this_host_spares($dom_in_use);
1356: }
1357: }
1358: if ($is_balancer) {
1359: my $lowest_load = 30000;
1360: if (ref($offloadto) eq 'HASH') {
1361: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1362: foreach my $try_server (@{$offloadto->{'primary'}}) {
1363: ($otherserver,$lowest_load) =
1364: &compare_server_load($try_server,$otherserver,$lowest_load);
1365: }
1366: }
1367: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1368:
1369: if (!$found_server) {
1370: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1371: foreach my $try_server (@{$offloadto->{'default'}}) {
1372: ($otherserver,$lowest_load) =
1373: &compare_server_load($try_server,$otherserver,$lowest_load);
1374: }
1375: }
1376: }
1377: } elsif (ref($offloadto) eq 'ARRAY') {
1378: if (@{$offloadto} == 1) {
1379: $otherserver = $offloadto->[0];
1380: } elsif (@{$offloadto} > 1) {
1381: foreach my $try_server (@{$offloadto}) {
1382: ($otherserver,$lowest_load) =
1383: &compare_server_load($try_server,$otherserver,$lowest_load);
1384: }
1385: }
1386: }
1387: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1388: $is_balancer = 0;
1389: if ($uname ne '' && $udom ne '') {
1390: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1391:
1392: &appenv({'user.loadbalexempt' => $lonhost,
1393: 'user.loadbalcheck.time' => time});
1394: }
1395: }
1396: }
1397: }
1398: return ($is_balancer,$otherserver);
1399: }
1400:
1401: sub check_balancer_result {
1402: my ($result,@hosts) = @_;
1403: my ($is_balancer,$currtargets,$currrules);
1404: if (ref($result) eq 'HASH') {
1405: if ($result->{'lonhost'} ne '') {
1406: my $currbalancer = $result->{'lonhost'};
1407: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1408: $is_balancer = 1;
1409: $currtargets = $result->{'targets'};
1410: $currrules = $result->{'rules'};
1411: }
1412: } else {
1413: foreach my $key (keys(%{$result})) {
1414: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1415: (ref($result->{$key}) eq 'HASH')) {
1416: $is_balancer = 1;
1417: $currrules = $result->{$key}{'rules'};
1418: $currtargets = $result->{$key}{'targets'};
1419: last;
1420: }
1421: }
1422: }
1423: }
1424: return ($is_balancer,$currtargets,$currrules);
1425: }
1426:
1427: sub get_loadbalancer_targets {
1428: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1429: my $offloadto;
1430: if ($rule_in_effect eq 'none') {
1431: return [$perlvar{'lonHostID'}];
1432: } elsif ($rule_in_effect eq '') {
1433: $offloadto = $currtargets;
1434: } else {
1435: if ($rule_in_effect eq 'homeserver') {
1436: my $homeserver = &homeserver($uname,$udom);
1437: if ($homeserver ne 'no_host') {
1438: $offloadto = [$homeserver];
1439: }
1440: } elsif ($rule_in_effect eq 'externalbalancer') {
1441: my %domconfig =
1442: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1443: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1444: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1445: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1446: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1447: }
1448: }
1449: } else {
1450: my %servers = &internet_dom_servers($udom);
1451: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1452: if (&hostname($remotebalancer) ne '') {
1453: $offloadto = [$remotebalancer];
1454: }
1455: }
1456: } elsif (&hostname($rule_in_effect) ne '') {
1457: $offloadto = [$rule_in_effect];
1458: }
1459: }
1460: return $offloadto;
1461: }
1462:
1463: sub internet_dom_servers {
1464: my ($dom) = @_;
1465: my (%uniqservers,%servers);
1466: my $primaryserver = &hostname(&domain($dom,'primary'));
1467: my @machinedoms = &machine_domains($primaryserver);
1468: foreach my $mdom (@machinedoms) {
1469: my %currservers = %servers;
1470: my %server = &get_servers($mdom);
1471: %servers = (%currservers,%server);
1472: }
1473: my %by_hostname;
1474: foreach my $id (keys(%servers)) {
1475: push(@{$by_hostname{$servers{$id}}},$id);
1476: }
1477: foreach my $hostname (sort(keys(%by_hostname))) {
1478: if (@{$by_hostname{$hostname}} > 1) {
1479: my $match = 0;
1480: foreach my $id (@{$by_hostname{$hostname}}) {
1481: if (&host_domain($id) eq $dom) {
1482: $uniqservers{$id} = $hostname;
1483: $match = 1;
1484: }
1485: }
1486: unless ($match) {
1487: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1488: }
1489: } else {
1490: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1491: }
1492: }
1493: return %uniqservers;
1494: }
1495:
1496: # ---------------------- Find the homebase for a user from domain's lib servers
1497:
1498: my %homecache;
1499: sub homeserver {
1500: my ($uname,$udom,$ignoreBadCache)=@_;
1501: my $index="$uname:$udom";
1502:
1503: if (exists($homecache{$index})) { return $homecache{$index}; }
1504:
1505: my %servers = &get_servers($udom,'library');
1506: foreach my $tryserver (keys(%servers)) {
1507: next if ($ignoreBadCache ne 'true' &&
1508: exists($badServerCache{$tryserver}));
1509:
1510: my $answer=reply("home:$udom:$uname",$tryserver);
1511: if ($answer eq 'found') {
1512: delete($badServerCache{$tryserver});
1513: return $homecache{$index}=$tryserver;
1514: } elsif ($answer eq 'no_host') {
1515: $badServerCache{$tryserver}=1;
1516: }
1517: }
1518: return 'no_host';
1519: }
1520:
1521: # ------------------------------------- Find the usernames behind a list of IDs
1522:
1523: sub idget {
1524: my ($udom,@ids)=@_;
1525: my %returnhash=();
1526:
1527: my %servers = &get_servers($udom,'library');
1528: foreach my $tryserver (keys(%servers)) {
1529: my $idlist=join('&',@ids);
1530: $idlist=~tr/A-Z/a-z/;
1531: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1532: my @answer=();
1533: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1534: @answer=split(/\&/,$reply);
1535: } ;
1536: my $i;
1537: for ($i=0;$i<=$#ids;$i++) {
1538: if ($answer[$i]) {
1539: $returnhash{$ids[$i]}=$answer[$i];
1540: }
1541: }
1542: }
1543: return %returnhash;
1544: }
1545:
1546: # ------------------------------------- Find the IDs behind a list of usernames
1547:
1548: sub idrget {
1549: my ($udom,@unames)=@_;
1550: my %returnhash=();
1551: foreach my $uname (@unames) {
1552: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1553: }
1554: return %returnhash;
1555: }
1556:
1557: # ------------------------------- Store away a list of names and associated IDs
1558:
1559: sub idput {
1560: my ($udom,%ids)=@_;
1561: my %servers=();
1562: foreach my $uname (keys(%ids)) {
1563: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1564: my $uhom=&homeserver($uname,$udom);
1565: if ($uhom ne 'no_host') {
1566: my $id=&escape($ids{$uname});
1567: $id=~tr/A-Z/a-z/;
1568: my $esc_unam=&escape($uname);
1569: if ($servers{$uhom}) {
1570: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1571: } else {
1572: $servers{$uhom}=$id.'='.$esc_unam;
1573: }
1574: }
1575: }
1576: foreach my $server (keys(%servers)) {
1577: &critical('idput:'.$udom.':'.$servers{$server},$server);
1578: }
1579: }
1580:
1581: # ------------------------------dump from db file owned by domainconfig user
1582: sub dump_dom {
1583: my ($namespace, $udom, $regexp) = @_;
1584:
1585: $udom ||= $env{'user.domain'};
1586:
1587: return () unless $udom;
1588:
1589: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1590: }
1591:
1592: # ------------------------------------------ get items from domain db files
1593:
1594: sub get_dom {
1595: my ($namespace,$storearr,$udom,$uhome)=@_;
1596: my $items='';
1597: foreach my $item (@$storearr) {
1598: $items.=&escape($item).'&';
1599: }
1600: $items=~s/\&$//;
1601: if (!$udom) {
1602: $udom=$env{'user.domain'};
1603: if (defined(&domain($udom,'primary'))) {
1604: $uhome=&domain($udom,'primary');
1605: } else {
1606: undef($uhome);
1607: }
1608: } else {
1609: if (!$uhome) {
1610: if (defined(&domain($udom,'primary'))) {
1611: $uhome=&domain($udom,'primary');
1612: }
1613: }
1614: }
1615: if ($udom && $uhome && ($uhome ne 'no_host')) {
1616: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1617: my %returnhash;
1618: if ($rep eq '' || $rep =~ /^error: 2 /) {
1619: return %returnhash;
1620: }
1621: my @pairs=split(/\&/,$rep);
1622: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1623: return @pairs;
1624: }
1625: my $i=0;
1626: foreach my $item (@$storearr) {
1627: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1628: $i++;
1629: }
1630: return %returnhash;
1631: } else {
1632: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1633: }
1634: }
1635:
1636: # -------------------------------------------- put items in domain db files
1637:
1638: sub put_dom {
1639: my ($namespace,$storehash,$udom,$uhome)=@_;
1640: if (!$udom) {
1641: $udom=$env{'user.domain'};
1642: if (defined(&domain($udom,'primary'))) {
1643: $uhome=&domain($udom,'primary');
1644: } else {
1645: undef($uhome);
1646: }
1647: } else {
1648: if (!$uhome) {
1649: if (defined(&domain($udom,'primary'))) {
1650: $uhome=&domain($udom,'primary');
1651: }
1652: }
1653: }
1654: if ($udom && $uhome && ($uhome ne 'no_host')) {
1655: my $items='';
1656: foreach my $item (keys(%$storehash)) {
1657: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1658: }
1659: $items=~s/\&$//;
1660: return &reply("putdom:$udom:$namespace:$items",$uhome);
1661: } else {
1662: &logthis("put_dom failed - no homeserver and/or domain");
1663: }
1664: }
1665:
1666: # --------------------- newput for items in db file owned by domainconfig user
1667: sub newput_dom {
1668: my ($namespace,$storehash,$udom) = @_;
1669: my $result;
1670: if (!$udom) {
1671: $udom=$env{'user.domain'};
1672: }
1673: if ($udom) {
1674: my $uname = &get_domainconfiguser($udom);
1675: $result = &newput($namespace,$storehash,$udom,$uname);
1676: }
1677: return $result;
1678: }
1679:
1680: # --------------------- delete for items in db file owned by domainconfig user
1681: sub del_dom {
1682: my ($namespace,$storearr,$udom)=@_;
1683: if (ref($storearr) eq 'ARRAY') {
1684: if (!$udom) {
1685: $udom=$env{'user.domain'};
1686: }
1687: if ($udom) {
1688: my $uname = &get_domainconfiguser($udom);
1689: return &del($namespace,$storearr,$udom,$uname);
1690: }
1691: }
1692: }
1693:
1694: # ----------------------------------construct domainconfig user for a domain
1695: sub get_domainconfiguser {
1696: my ($udom) = @_;
1697: return $udom.'-domainconfig';
1698: }
1699:
1700: sub retrieve_inst_usertypes {
1701: my ($udom) = @_;
1702: my (%returnhash,@order);
1703: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1704: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1705: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1706: %returnhash = %{$domdefs{'inststatustypes'}};
1707: @order = @{$domdefs{'inststatusorder'}};
1708: } else {
1709: if (defined(&domain($udom,'primary'))) {
1710: my $uhome=&domain($udom,'primary');
1711: my $rep=&reply("inst_usertypes:$udom",$uhome);
1712: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1713: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1714: return (\%returnhash,\@order);
1715: }
1716: my ($hashitems,$orderitems) = split(/:/,$rep);
1717: my @pairs=split(/\&/,$hashitems);
1718: foreach my $item (@pairs) {
1719: my ($key,$value)=split(/=/,$item,2);
1720: $key = &unescape($key);
1721: next if ($key =~ /^error: 2 /);
1722: $returnhash{$key}=&thaw_unescape($value);
1723: }
1724: my @esc_order = split(/\&/,$orderitems);
1725: foreach my $item (@esc_order) {
1726: push(@order,&unescape($item));
1727: }
1728: } else {
1729: &logthis("get_dom failed - no primary domain server for $udom");
1730: }
1731: }
1732: return (\%returnhash,\@order);
1733: }
1734:
1735: sub is_domainimage {
1736: my ($url) = @_;
1737: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1738: if (&domain($1) ne '') {
1739: return '1';
1740: }
1741: }
1742: return;
1743: }
1744:
1745: sub inst_directory_query {
1746: my ($srch) = @_;
1747: my $udom = $srch->{'srchdomain'};
1748: my %results;
1749: my $homeserver = &domain($udom,'primary');
1750: my $outcome;
1751: if ($homeserver ne '') {
1752: my $queryid=&reply("querysend:instdirsearch:".
1753: &escape($srch->{'srchby'}).':'.
1754: &escape($srch->{'srchterm'}).':'.
1755: &escape($srch->{'srchtype'}),$homeserver);
1756: my $host=&hostname($homeserver);
1757: if ($queryid !~/^\Q$host\E\_/) {
1758: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1759: return;
1760: }
1761: my $response = &get_query_reply($queryid);
1762: my $maxtries = 5;
1763: my $tries = 1;
1764: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1765: $response = &get_query_reply($queryid);
1766: $tries ++;
1767: }
1768:
1769: if (!&error($response) && $response ne 'refused') {
1770: if ($response eq 'unavailable') {
1771: $outcome = $response;
1772: } else {
1773: $outcome = 'ok';
1774: my @matches = split(/\n/,$response);
1775: foreach my $match (@matches) {
1776: my ($key,$value) = split(/=/,$match);
1777: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1778: }
1779: }
1780: }
1781: }
1782: return ($outcome,%results);
1783: }
1784:
1785: sub usersearch {
1786: my ($srch) = @_;
1787: my $dom = $srch->{'srchdomain'};
1788: my %results;
1789: my %libserv = &all_library();
1790: my $query = 'usersearch';
1791: foreach my $tryserver (keys(%libserv)) {
1792: if (&host_domain($tryserver) eq $dom) {
1793: my $host=&hostname($tryserver);
1794: my $queryid=
1795: &reply("querysend:".&escape($query).':'.
1796: &escape($srch->{'srchby'}).':'.
1797: &escape($srch->{'srchtype'}).':'.
1798: &escape($srch->{'srchterm'}),$tryserver);
1799: if ($queryid !~/^\Q$host\E\_/) {
1800: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1801: next;
1802: }
1803: my $reply = &get_query_reply($queryid);
1804: my $maxtries = 1;
1805: my $tries = 1;
1806: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1807: $reply = &get_query_reply($queryid);
1808: $tries ++;
1809: }
1810: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1811: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1812: } else {
1813: my @matches;
1814: if ($reply =~ /\n/) {
1815: @matches = split(/\n/,$reply);
1816: } else {
1817: @matches = split(/\&/,$reply);
1818: }
1819: foreach my $match (@matches) {
1820: my ($uname,$udom,%userhash);
1821: foreach my $entry (split(/:/,$match)) {
1822: my ($key,$value) =
1823: map {&unescape($_);} split(/=/,$entry);
1824: $userhash{$key} = $value;
1825: if ($key eq 'username') {
1826: $uname = $value;
1827: } elsif ($key eq 'domain') {
1828: $udom = $value;
1829: }
1830: }
1831: $results{$uname.':'.$udom} = \%userhash;
1832: }
1833: }
1834: }
1835: }
1836: return %results;
1837: }
1838:
1839: sub get_instuser {
1840: my ($udom,$uname,$id) = @_;
1841: my $homeserver = &domain($udom,'primary');
1842: my ($outcome,%results);
1843: if ($homeserver ne '') {
1844: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1845: &escape($id).':'.&escape($udom),$homeserver);
1846: my $host=&hostname($homeserver);
1847: if ($queryid !~/^\Q$host\E\_/) {
1848: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1849: return;
1850: }
1851: my $response = &get_query_reply($queryid);
1852: my $maxtries = 5;
1853: my $tries = 1;
1854: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1855: $response = &get_query_reply($queryid);
1856: $tries ++;
1857: }
1858: if (!&error($response) && $response ne 'refused') {
1859: if ($response eq 'unavailable') {
1860: $outcome = $response;
1861: } else {
1862: $outcome = 'ok';
1863: my @matches = split(/\n/,$response);
1864: foreach my $match (@matches) {
1865: my ($key,$value) = split(/=/,$match);
1866: $results{&unescape($key)} = &thaw_unescape($value);
1867: }
1868: }
1869: }
1870: }
1871: my %userinfo;
1872: if (ref($results{$uname}) eq 'HASH') {
1873: %userinfo = %{$results{$uname}};
1874: }
1875: return ($outcome,%userinfo);
1876: }
1877:
1878: sub inst_rulecheck {
1879: my ($udom,$uname,$id,$item,$rules) = @_;
1880: my %returnhash;
1881: if ($udom ne '') {
1882: if (ref($rules) eq 'ARRAY') {
1883: @{$rules} = map {&escape($_);} (@{$rules});
1884: my $rulestr = join(':',@{$rules});
1885: my $homeserver=&domain($udom,'primary');
1886: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1887: my $response;
1888: if ($item eq 'username') {
1889: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1890: ':'.&escape($uname).':'.$rulestr,
1891: $homeserver));
1892: } elsif ($item eq 'id') {
1893: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1894: ':'.&escape($id).':'.$rulestr,
1895: $homeserver));
1896: } elsif ($item eq 'selfcreate') {
1897: $response=&unescape(&reply('instselfcreatecheck:'.
1898: &escape($udom).':'.&escape($uname).
1899: ':'.$rulestr,$homeserver));
1900: }
1901: if ($response ne 'refused') {
1902: my @pairs=split(/\&/,$response);
1903: foreach my $item (@pairs) {
1904: my ($key,$value)=split(/=/,$item,2);
1905: $key = &unescape($key);
1906: next if ($key =~ /^error: 2 /);
1907: $returnhash{$key}=&thaw_unescape($value);
1908: }
1909: }
1910: }
1911: }
1912: }
1913: return %returnhash;
1914: }
1915:
1916: sub inst_userrules {
1917: my ($udom,$check) = @_;
1918: my (%ruleshash,@ruleorder);
1919: if ($udom ne '') {
1920: my $homeserver=&domain($udom,'primary');
1921: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1922: my $response;
1923: if ($check eq 'id') {
1924: $response=&reply('instidrules:'.&escape($udom),
1925: $homeserver);
1926: } elsif ($check eq 'email') {
1927: $response=&reply('instemailrules:'.&escape($udom),
1928: $homeserver);
1929: } else {
1930: $response=&reply('instuserrules:'.&escape($udom),
1931: $homeserver);
1932: }
1933: if (($response ne 'refused') && ($response ne 'error') &&
1934: ($response ne 'unknown_cmd') &&
1935: ($response ne 'no_such_host')) {
1936: my ($hashitems,$orderitems) = split(/:/,$response);
1937: my @pairs=split(/\&/,$hashitems);
1938: foreach my $item (@pairs) {
1939: my ($key,$value)=split(/=/,$item,2);
1940: $key = &unescape($key);
1941: next if ($key =~ /^error: 2 /);
1942: $ruleshash{$key}=&thaw_unescape($value);
1943: }
1944: my @esc_order = split(/\&/,$orderitems);
1945: foreach my $item (@esc_order) {
1946: push(@ruleorder,&unescape($item));
1947: }
1948: }
1949: }
1950: }
1951: return (\%ruleshash,\@ruleorder);
1952: }
1953:
1954: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1955:
1956: sub get_domain_defaults {
1957: my ($domain) = @_;
1958: my $cachetime = 60*60*24;
1959: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1960: if (defined($cached)) {
1961: if (ref($result) eq 'HASH') {
1962: return %{$result};
1963: }
1964: }
1965: my %domdefaults;
1966: my %domconfig =
1967: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1968: 'requestcourses','inststatus',
1969: 'coursedefaults','usersessions',
1970: 'requestauthor'],$domain);
1971: if (ref($domconfig{'defaults'}) eq 'HASH') {
1972: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1973: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1974: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1975: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1976: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1977: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1978: } else {
1979: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1980: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1981: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1982: }
1983: if (ref($domconfig{'quotas'}) eq 'HASH') {
1984: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1985: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1986: } else {
1987: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1988: }
1989: my @usertools = ('aboutme','blog','webdav','portfolio');
1990: foreach my $item (@usertools) {
1991: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1992: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1993: }
1994: }
1995: }
1996: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1997: foreach my $item ('official','unofficial','community') {
1998: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1999: }
2000: }
2001: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2002: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2003: }
2004: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2005: foreach my $item ('inststatustypes','inststatusorder') {
2006: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2007: }
2008: }
2009: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
2010: foreach my $item ('canuse_pdfforms') {
2011: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
2012: }
2013: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2014: $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
2015: $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
2016: }
2017: }
2018: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2019: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2020: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2021: }
2022: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2023: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2024: }
2025: }
2026: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
2027: return %domdefaults;
2028: }
2029:
2030: # --------------------------------------------------- Assign a key to a student
2031:
2032: sub assign_access_key {
2033: #
2034: # a valid key looks like uname:udom#comments
2035: # comments are being appended
2036: #
2037: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2038: $kdom=
2039: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
2040: $knum=
2041: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
2042: $cdom=
2043: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2044: $cnum=
2045: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2046: $udom=$env{'user.name'} unless (defined($udom));
2047: $uname=$env{'user.domain'} unless (defined($uname));
2048: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
2049: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
2050: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
2051: # assigned to this person
2052: # - this should not happen,
2053: # unless something went wrong
2054: # the first time around
2055: # ready to assign
2056: $logentry=$1.'; '.$logentry;
2057: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
2058: $kdom,$knum) eq 'ok') {
2059: # key now belongs to user
2060: my $envkey='key.'.$cdom.'_'.$cnum;
2061: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2062: &appenv({'environment.'.$envkey => $ckey});
2063: return 'ok';
2064: } else {
2065: return
2066: 'error: Count not permanently assign key, will need to be re-entered later.';
2067: }
2068: } else {
2069: return 'error: Could not assign key, try again later.';
2070: }
2071: } elsif (!$existing{$ckey}) {
2072: # the key does not exist
2073: return 'error: The key does not exist';
2074: } else {
2075: # the key is somebody else's
2076: return 'error: The key is already in use';
2077: }
2078: }
2079:
2080: # ------------------------------------------ put an additional comment on a key
2081:
2082: sub comment_access_key {
2083: #
2084: # a valid key looks like uname:udom#comments
2085: # comments are being appended
2086: #
2087: my ($ckey,$cdom,$cnum,$logentry)=@_;
2088: $cdom=
2089: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2090: $cnum=
2091: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2092: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2093: if ($existing{$ckey}) {
2094: $existing{$ckey}.='; '.$logentry;
2095: # ready to assign
2096: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2097: $cdom,$cnum) eq 'ok') {
2098: return 'ok';
2099: } else {
2100: return 'error: Count not store comment.';
2101: }
2102: } else {
2103: # the key does not exist
2104: return 'error: The key does not exist';
2105: }
2106: }
2107:
2108: # ------------------------------------------------------ Generate a set of keys
2109:
2110: sub generate_access_keys {
2111: my ($number,$cdom,$cnum,$logentry)=@_;
2112: $cdom=
2113: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2114: $cnum=
2115: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2116: unless (&allowed('mky',$cdom)) { return 0; }
2117: unless (($cdom) && ($cnum)) { return 0; }
2118: if ($number>10000) { return 0; }
2119: sleep(2); # make sure don't get same seed twice
2120: srand(time()^($$+($$<<15))); # from "Programming Perl"
2121: my $total=0;
2122: for (my $i=1;$i<=$number;$i++) {
2123: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2124: sprintf("%lx",int(100000*rand)).'-'.
2125: sprintf("%lx",int(100000*rand));
2126: $newkey=~s/1/g/g; # folks mix up 1 and l
2127: $newkey=~s/0/h/g; # and also 0 and O
2128: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2129: if ($existing{$newkey}) {
2130: $i--;
2131: } else {
2132: if (&put('accesskeys',
2133: { $newkey => '# generated '.localtime().
2134: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2135: '; '.$logentry },
2136: $cdom,$cnum) eq 'ok') {
2137: $total++;
2138: }
2139: }
2140: }
2141: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2142: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2143: return $total;
2144: }
2145:
2146: # ------------------------------------------------------- Validate an accesskey
2147:
2148: sub validate_access_key {
2149: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2150: $cdom=
2151: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2152: $cnum=
2153: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2154: $udom=$env{'user.domain'} unless (defined($udom));
2155: $uname=$env{'user.name'} unless (defined($uname));
2156: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2157: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2158: }
2159:
2160: # ------------------------------------- Find the section of student in a course
2161: sub devalidate_getsection_cache {
2162: my ($udom,$unam,$courseid)=@_;
2163: my $hashid="$udom:$unam:$courseid";
2164: &devalidate_cache_new('getsection',$hashid);
2165: }
2166:
2167: sub courseid_to_courseurl {
2168: my ($courseid) = @_;
2169: #already url style courseid
2170: return $courseid if ($courseid =~ m{^/});
2171:
2172: if (exists($env{'course.'.$courseid.'.num'})) {
2173: my $cnum = $env{'course.'.$courseid.'.num'};
2174: my $cdom = $env{'course.'.$courseid.'.domain'};
2175: return "/$cdom/$cnum";
2176: }
2177:
2178: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2179: if (exists($courseinfo{'num'})) {
2180: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2181: }
2182:
2183: return undef;
2184: }
2185:
2186: sub getsection {
2187: my ($udom,$unam,$courseid)=@_;
2188: my $cachetime=1800;
2189:
2190: my $hashid="$udom:$unam:$courseid";
2191: my ($result,$cached)=&is_cached_new('getsection',$hashid);
2192: if (defined($cached)) { return $result; }
2193:
2194: my %Pending;
2195: my %Expired;
2196: #
2197: # Each role can either have not started yet (pending), be active,
2198: # or have expired.
2199: #
2200: # If there is an active role, we are done.
2201: #
2202: # If there is more than one role which has not started yet,
2203: # choose the one which will start sooner
2204: # If there is one role which has not started yet, return it.
2205: #
2206: # If there is more than one expired role, choose the one which ended last.
2207: # If there is a role which has expired, return it.
2208: #
2209: $courseid = &courseid_to_courseurl($courseid);
2210: my %roleshash = &dump('roles',$udom,$unam,$courseid);
2211: foreach my $key (keys(%roleshash)) {
2212: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
2213: my $section=$1;
2214: if ($key eq $courseid.'_st') { $section=''; }
2215: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
2216: my $now=time;
2217: if (defined($end) && $end && ($now > $end)) {
2218: $Expired{$end}=$section;
2219: next;
2220: }
2221: if (defined($start) && $start && ($now < $start)) {
2222: $Pending{$start}=$section;
2223: next;
2224: }
2225: return &do_cache_new('getsection',$hashid,$section,$cachetime);
2226: }
2227: #
2228: # Presumedly there will be few matching roles from the above
2229: # loop and the sorting time will be negligible.
2230: if (scalar(keys(%Pending))) {
2231: my ($time) = sort {$a <=> $b} keys(%Pending);
2232: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
2233: }
2234: if (scalar(keys(%Expired))) {
2235: my @sorted = sort {$a <=> $b} keys(%Expired);
2236: my $time = pop(@sorted);
2237: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
2238: }
2239: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
2240: }
2241:
2242: sub save_cache {
2243: &purge_remembered();
2244: #&Apache::loncommon::validate_page();
2245: undef(%env);
2246: undef($env_loaded);
2247: }
2248:
2249: my $to_remember=-1;
2250: my %remembered;
2251: my %accessed;
2252: my $kicks=0;
2253: my $hits=0;
2254: sub make_key {
2255: my ($name,$id) = @_;
2256: if (length($id) > 65
2257: && length(&escape($id)) > 200) {
2258: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2259: }
2260: return &escape($name.':'.$id);
2261: }
2262:
2263: sub devalidate_cache_new {
2264: my ($name,$id,$debug) = @_;
2265: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
2266: $id=&make_key($name,$id);
2267: $memcache->delete($id);
2268: delete($remembered{$id});
2269: delete($accessed{$id});
2270: }
2271:
2272: sub is_cached_new {
2273: my ($name,$id,$debug) = @_;
2274: $id=&make_key($name,$id);
2275: if (exists($remembered{$id})) {
2276: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
2277: $accessed{$id}=[&gettimeofday()];
2278: $hits++;
2279: return ($remembered{$id},1);
2280: }
2281: my $value = $memcache->get($id);
2282: if (!(defined($value))) {
2283: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
2284: return (undef,undef);
2285: }
2286: if ($value eq '__undef__') {
2287: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2288: $value=undef;
2289: }
2290: &make_room($id,$value,$debug);
2291: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2292: return ($value,1);
2293: }
2294:
2295: sub do_cache_new {
2296: my ($name,$id,$value,$time,$debug) = @_;
2297: $id=&make_key($name,$id);
2298: my $setvalue=$value;
2299: if (!defined($setvalue)) {
2300: $setvalue='__undef__';
2301: }
2302: if (!defined($time) ) {
2303: $time=600;
2304: }
2305: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
2306: my $result = $memcache->set($id,$setvalue,$time);
2307: if (! $result) {
2308: &logthis("caching of id -> $id failed");
2309: $memcache->disconnect_all();
2310: }
2311: # need to make a copy of $value
2312: &make_room($id,$value,$debug);
2313: return $value;
2314: }
2315:
2316: sub make_room {
2317: my ($id,$value,$debug)=@_;
2318:
2319: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2320: : $value;
2321: if ($to_remember<0) { return; }
2322: $accessed{$id}=[&gettimeofday()];
2323: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2324: my $to_kick;
2325: my $max_time=0;
2326: foreach my $other (keys(%accessed)) {
2327: if (&tv_interval($accessed{$other}) > $max_time) {
2328: $to_kick=$other;
2329: $max_time=&tv_interval($accessed{$other});
2330: }
2331: }
2332: delete($remembered{$to_kick});
2333: delete($accessed{$to_kick});
2334: $kicks++;
2335: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
2336: return;
2337: }
2338:
2339: sub purge_remembered {
2340: #&logthis("Tossing ".scalar(keys(%remembered)));
2341: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
2342: undef(%remembered);
2343: undef(%accessed);
2344: }
2345: # ------------------------------------- Read an entry from a user's environment
2346:
2347: sub userenvironment {
2348: my ($udom,$unam,@what)=@_;
2349: my $items;
2350: foreach my $item (@what) {
2351: $items.=&escape($item).'&';
2352: }
2353: $items=~s/\&$//;
2354: my %returnhash=();
2355: my $uhome = &homeserver($unam,$udom);
2356: unless ($uhome eq 'no_host') {
2357: my @answer=split(/\&/,
2358: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
2359: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2360: return %returnhash;
2361: }
2362: my $i;
2363: for ($i=0;$i<=$#what;$i++) {
2364: $returnhash{$what[$i]}=&unescape($answer[$i]);
2365: }
2366: }
2367: return %returnhash;
2368: }
2369:
2370: # ---------------------------------------------------------- Get a studentphoto
2371: sub studentphoto {
2372: my ($udom,$unam,$ext) = @_;
2373: my $home=&Apache::lonnet::homeserver($unam,$udom);
2374: if (defined($env{'request.course.id'})) {
2375: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
2376: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2377: return(&retrievestudentphoto($udom,$unam,$ext));
2378: } else {
2379: my ($result,$perm_reqd)=
2380: &Apache::lonnet::auto_photo_permission($unam,$udom);
2381: if ($result eq 'ok') {
2382: if (!($perm_reqd eq 'yes')) {
2383: return(&retrievestudentphoto($udom,$unam,$ext));
2384: }
2385: }
2386: }
2387: }
2388: } else {
2389: my ($result,$perm_reqd) =
2390: &Apache::lonnet::auto_photo_permission($unam,$udom);
2391: if ($result eq 'ok') {
2392: if (!($perm_reqd eq 'yes')) {
2393: return(&retrievestudentphoto($udom,$unam,$ext));
2394: }
2395: }
2396: }
2397: return '/adm/lonKaputt/lonlogo_broken.gif';
2398: }
2399:
2400: sub retrievestudentphoto {
2401: my ($udom,$unam,$ext,$type) = @_;
2402: my $home=&Apache::lonnet::homeserver($unam,$udom);
2403: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2404: if ($ret eq 'ok') {
2405: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2406: if ($type eq 'thumbnail') {
2407: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2408: }
2409: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2410: return $tokenurl;
2411: } else {
2412: if ($type eq 'thumbnail') {
2413: return '/adm/lonKaputt/genericstudent_tn.gif';
2414: } else {
2415: return '/adm/lonKaputt/lonlogo_broken.gif';
2416: }
2417: }
2418: }
2419:
2420: # -------------------------------------------------------------------- New chat
2421:
2422: sub chatsend {
2423: my ($newentry,$anon,$group)=@_;
2424: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2425: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2426: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2427: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2428: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2429: &escape($newentry)).':'.$group,$chome);
2430: }
2431:
2432: # ------------------------------------------ Find current version of a resource
2433:
2434: sub getversion {
2435: my $fname=&clutter(shift);
2436: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
2437: return ¤tversion(&filelocation('',$fname));
2438: }
2439:
2440: sub currentversion {
2441: my $fname=shift;
2442: my $author=$fname;
2443: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2444: my ($udom,$uname)=split(/\//,$author);
2445: my $home=&homeserver($uname,$udom);
2446: if ($home eq 'no_host') {
2447: return -1;
2448: }
2449: my $answer=&reply("currentversion:$fname",$home);
2450: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2451: return -1;
2452: }
2453: return $answer;
2454: }
2455:
2456: #
2457: # Return special version number of resource if set by override, empty otherwise
2458: #
2459: sub usedversion {
2460: my $fname=shift;
2461: unless ($fname) { $fname=$env{'request.uri'}; }
2462: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2463: if ($urlversion) { return $urlversion; }
2464: return '';
2465: }
2466:
2467: # ----------------------------- Subscribe to a resource, return URL if possible
2468:
2469: sub subscribe {
2470: my $fname=shift;
2471: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
2472: $fname=~s/[\n\r]//g;
2473: my $author=$fname;
2474: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2475: my ($udom,$uname)=split(/\//,$author);
2476: my $home=homeserver($uname,$udom);
2477: if ($home eq 'no_host') {
2478: return 'not_found';
2479: }
2480: my $answer=reply("sub:$fname",$home);
2481: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2482: $answer.=' by '.$home;
2483: }
2484: return $answer;
2485: }
2486:
2487: # -------------------------------------------------------------- Replicate file
2488:
2489: sub repcopy {
2490: my $filename=shift;
2491: $filename=~s/\/+/\//g;
2492: my $londocroot = $perlvar{'lonDocRoot'};
2493: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
2494: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
2495: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2496: $filename=~m{^/*(uploaded|editupload)/}) {
2497: return &repcopy_userfile($filename);
2498: }
2499: $filename=~s/[\n\r]//g;
2500: my $transname="$filename.in.transfer";
2501: # FIXME: this should flock
2502: if ((-e $filename) || (-e $transname)) { return 'ok'; }
2503: my $remoteurl=subscribe($filename);
2504: if ($remoteurl =~ /^con_lost by/) {
2505: &logthis("Subscribe returned $remoteurl: $filename");
2506: return 'unavailable';
2507: } elsif ($remoteurl eq 'not_found') {
2508: #&logthis("Subscribe returned not_found: $filename");
2509: return 'not_found';
2510: } elsif ($remoteurl =~ /^rejected by/) {
2511: &logthis("Subscribe returned $remoteurl: $filename");
2512: return 'forbidden';
2513: } elsif ($remoteurl eq 'directory') {
2514: return 'ok';
2515: } else {
2516: my $author=$filename;
2517: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2518: my ($udom,$uname)=split(/\//,$author);
2519: my $home=homeserver($uname,$udom);
2520: unless ($home eq $perlvar{'lonHostID'}) {
2521: my @parts=split(/\//,$filename);
2522: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2523: if ($path ne "$londocroot/res") {
2524: &logthis("Malconfiguration for replication: $filename");
2525: return 'bad_request';
2526: }
2527: my $count;
2528: for ($count=5;$count<$#parts;$count++) {
2529: $path.="/$parts[$count]";
2530: if ((-e $path)!=1) {
2531: mkdir($path,0777);
2532: }
2533: }
2534: my $ua=new LWP::UserAgent;
2535: my $request=new HTTP::Request('GET',"$remoteurl");
2536: my $response=$ua->request($request,$transname);
2537: if ($response->is_error()) {
2538: unlink($transname);
2539: my $message=$response->status_line;
2540: &logthis("<font color=\"blue\">WARNING:"
2541: ." LWP get: $message: $filename</font>");
2542: return 'unavailable';
2543: } else {
2544: if ($remoteurl!~/\.meta$/) {
2545: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2546: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2547: if ($mresponse->is_error()) {
2548: unlink($filename.'.meta');
2549: &logthis(
2550: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
2551: }
2552: }
2553: rename($transname,$filename);
2554: return 'ok';
2555: }
2556: }
2557: }
2558: }
2559:
2560: # ------------------------------------------------ Get server side include body
2561: sub ssi_body {
2562: my ($filelink,%form)=@_;
2563: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2564: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2565: }
2566: my $output='';
2567: my $response;
2568: if ($filelink=~/^https?\:/) {
2569: ($output,$response)=&externalssi($filelink);
2570: } else {
2571: $filelink .= $filelink=~/\?/ ? '&' : '?';
2572: $filelink .= 'inhibitmenu=yes';
2573: ($output,$response)=&ssi($filelink,%form);
2574: }
2575: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
2576: $output=~s/^.*?\<body[^\>]*\>//si;
2577: $output=~s/\<\/body\s*\>.*?$//si;
2578: if (wantarray) {
2579: return ($output, $response);
2580: } else {
2581: return $output;
2582: }
2583: }
2584:
2585: # --------------------------------------------------------- Server Side Include
2586:
2587: sub absolute_url {
2588: my ($host_name) = @_;
2589: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2590: if ($host_name eq '') {
2591: $host_name = $ENV{'SERVER_NAME'};
2592: }
2593: return $protocol.$host_name;
2594: }
2595:
2596: #
2597: # Server side include.
2598: # Parameters:
2599: # fn Possibly encrypted resource name/id.
2600: # form Hash that describes how the rendering should be done
2601: # and other things.
2602: # Returns:
2603: # Scalar context: The content of the response.
2604: # Array context: 2 element list of the content and the full response object.
2605: #
2606: sub ssi {
2607:
2608: my ($fn,%form)=@_;
2609: my $ua=new LWP::UserAgent;
2610: my $request;
2611:
2612: $form{'no_update_last_known'}=1;
2613: &Apache::lonenc::check_encrypt(\$fn);
2614: if (%form) {
2615: $request=new HTTP::Request('POST',&absolute_url().$fn);
2616: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
2617: } else {
2618: $request=new HTTP::Request('GET',&absolute_url().$fn);
2619: }
2620:
2621: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2622: my $response= $ua->request($request);
2623: my $content = $response->content;
2624:
2625:
2626: if (wantarray) {
2627: return ($content, $response);
2628: } else {
2629: return $content;
2630: }
2631: }
2632:
2633: sub externalssi {
2634: my ($url)=@_;
2635: my $ua=new LWP::UserAgent;
2636: my $request=new HTTP::Request('GET',$url);
2637: my $response=$ua->request($request);
2638: if (wantarray) {
2639: return ($response->content, $response);
2640: } else {
2641: return $response->content;
2642: }
2643: }
2644:
2645: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2646:
2647: sub allowuploaded {
2648: my ($srcurl,$url)=@_;
2649: $url=&clutter(&declutter($url));
2650: my $dir=$url;
2651: $dir=~s/\/[^\/]+$//;
2652: my %httpref=();
2653: my $httpurl=&hreflocation('',$url);
2654: $httpref{'httpref.'.$httpurl}=$srcurl;
2655: &Apache::lonnet::appenv(\%httpref);
2656: }
2657:
2658: #
2659: # Determine if the current user should be able to edit a particular resource,
2660: # when viewing in course context.
2661: # (a) When viewing resource used to determine if "Edit" item is included in
2662: # Functions.
2663: # (b) When displaying folder contents in course editor, used to determine if
2664: # "Edit" link will be displayed alongside resource.
2665: #
2666: # input: six args -- filename (decluttered), course number, course domain,
2667: # url, symb (if registered) and group (if this is a group
2668: # item -- e.g., bulletin board, group page etc.).
2669: # output: array of five scalars --
2670: # $cfile -- url for file editing if editable on current server
2671: # $home -- homeserver of resource (i.e., for author if published,
2672: # or course if uploaded.).
2673: # $switchserver -- 1 if server switch will be needed.
2674: # $forceedit -- 1 if icon/link should be to go to edit mode
2675: # $forceview -- 1 if icon/link should be to go to view mode
2676: #
2677:
2678: sub can_edit_resource {
2679: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2680: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2681: #
2682: # For aboutme pages user can only edit his/her own.
2683: #
2684: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2685: my ($sdom,$sname) = ($1,$2);
2686: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2687: $home = $env{'user.home'};
2688: $cfile = $resurl;
2689: if ($env{'form.forceedit'}) {
2690: $forceview = 1;
2691: } else {
2692: $forceedit = 1;
2693: }
2694: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2695: } else {
2696: return;
2697: }
2698: }
2699:
2700: if ($env{'request.course.id'}) {
2701: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2702: if ($group ne '') {
2703: # if this is a group homepage or group bulletin board, check group privs
2704: my $allowed = 0;
2705: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2706: if ((&allowed('mdg',$env{'request.course.id'}.
2707: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2708: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2709: $allowed = 1;
2710: }
2711: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2712: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2713: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2714: $allowed = 1;
2715: }
2716: }
2717: if ($allowed) {
2718: $home=&homeserver($cnum,$cdom);
2719: if ($env{'form.forceedit'}) {
2720: $forceview = 1;
2721: } else {
2722: $forceedit = 1;
2723: }
2724: $cfile = $resurl;
2725: } else {
2726: return;
2727: }
2728: } else {
2729: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2730: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2731: return;
2732: }
2733: } elsif (!$crsedit) {
2734: #
2735: # No edit allowed where CC has switched to student role.
2736: #
2737: return;
2738: }
2739: }
2740: }
2741:
2742: if ($file ne '') {
2743: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2744: if (&is_course_upload($file,$cnum,$cdom)) {
2745: $uploaded = 1;
2746: $incourse = 1;
2747: if ($file =~/\.(htm|html|css|js|txt)$/) {
2748: $cfile = &hreflocation('',$file);
2749: if ($env{'form.forceedit'}) {
2750: $forceview = 1;
2751: } else {
2752: $forceedit = 1;
2753: }
2754: }
2755: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2756: $incourse = 1;
2757: if ($env{'form.forceedit'}) {
2758: $forceview = 1;
2759: } else {
2760: $forceedit = 1;
2761: }
2762: $cfile = $resurl;
2763: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2764: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2765: $incourse = 1;
2766: if ($env{'form.forceedit'}) {
2767: $forceview = 1;
2768: } else {
2769: $forceedit = 1;
2770: }
2771: $cfile = $resurl;
2772: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2773: $incourse = 1;
2774: $cfile = $resurl.'/smpedit';
2775: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2776: $incourse = 1;
2777: if ($env{'form.forceedit'}) {
2778: $forceview = 1;
2779: } else {
2780: $forceedit = 1;
2781: }
2782: $cfile = $resurl;
2783: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2784: $incourse = 1;
2785: if ($env{'form.forceedit'}) {
2786: $forceview = 1;
2787: } else {
2788: $forceedit = 1;
2789: }
2790: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
2791: }
2792: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2793: my $template = '/res/lib/templates/simpleproblem.problem';
2794: if (&is_on_map($template)) {
2795: $incourse = 1;
2796: $forceview = 1;
2797: $cfile = $template;
2798: }
2799: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2800: $incourse = 1;
2801: if ($env{'form.forceedit'}) {
2802: $forceview = 1;
2803: } else {
2804: $forceedit = 1;
2805: }
2806: $cfile = $resurl;
2807: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2808: $incourse = 1;
2809: $forceview = 1;
2810: if ($symb) {
2811: my ($map,$id,$res)=&decode_symb($symb);
2812: $env{'request.symb'} = $symb;
2813: $cfile = &clutter($res);
2814: } else {
2815: $cfile = $env{'form.suppurl'};
2816: $cfile =~ s{^http://}{};
2817: $cfile = '/adm/wrapper/ext/'.$cfile;
2818: }
2819: }
2820: }
2821: if ($uploaded || $incourse) {
2822: $home=&homeserver($cnum,$cdom);
2823: } elsif ($file !~ m{/$}) {
2824: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2825: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2826: # Check that the user has permission to edit this resource
2827: my $setpriv = 1;
2828: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2829: if (defined($cfudom)) {
2830: $home=&homeserver($cfuname,$cfudom);
2831: $cfile=$file;
2832: }
2833: }
2834: if (($cfile ne '') && (!$incourse || $uploaded) &&
2835: (($home ne '') && ($home ne 'no_host'))) {
2836: my @ids=¤t_machine_ids();
2837: unless (grep(/^\Q$home\E$/,@ids)) {
2838: $switchserver=1;
2839: }
2840: }
2841: }
2842: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2843: }
2844:
2845: sub is_course_upload {
2846: my ($file,$cnum,$cdom) = @_;
2847: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2848: $uploadpath =~ s{^\/}{};
2849: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2850: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
2851: return 1;
2852: }
2853: return;
2854: }
2855:
2856: sub in_course {
2857: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2858: if ($hideprivileged) {
2859: my $skipuser;
2860: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2861: my @possdoms = ($cdom);
2862: if ($coursehash{'checkforpriv'}) {
2863: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2864: }
2865: if (&privileged($uname,$udom,\@possdoms)) {
2866: $skipuser = 1;
2867: if ($coursehash{'nothideprivileged'}) {
2868: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2869: my $user;
2870: if ($item =~ /:/) {
2871: $user = $item;
2872: } else {
2873: $user = join(':',split(/[\@]/,$item));
2874: }
2875: if ($user eq $uname.':'.$udom) {
2876: undef($skipuser);
2877: last;
2878: }
2879: }
2880: }
2881: if ($skipuser) {
2882: return 0;
2883: }
2884: }
2885: }
2886: $type ||= 'any';
2887: if (!defined($cdom) || !defined($cnum)) {
2888: my $cid = $env{'request.course.id'};
2889: $cdom = $env{'course.'.$cid.'.domain'};
2890: $cnum = $env{'course.'.$cid.'.num'};
2891: }
2892: my $typesref;
2893: if (($type eq 'any') || ($type eq 'all')) {
2894: $typesref = ['active','previous','future'];
2895: } elsif ($type eq 'previous' || $type eq 'future') {
2896: $typesref = [$type];
2897: }
2898: my %roles = &get_my_roles($uname,$udom,'userroles',
2899: $typesref,undef,[$cdom]);
2900: my ($tmp) = keys(%roles);
2901: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2902: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2903: if (@course_roles > 0) {
2904: return 1;
2905: }
2906: return 0;
2907: }
2908:
2909: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
2910: # input: action, courseID, current domain, intended
2911: # path to file, source of file, instruction to parse file for objects,
2912: # ref to hash for embedded objects,
2913: # ref to hash for codebase of java objects.
2914: # reference to scalar to accommodate mime type determined
2915: # from File::MMagic if $parser = parse.
2916: #
2917: # output: url to file (if action was uploaddoc),
2918: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
2919: #
2920: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2921: # course.
2922: #
2923: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2924: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2925: # course's home server.
2926: #
2927: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2928: # be copied from $source (current location) to
2929: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2930: # and will then be copied to
2931: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2932: # course's home server.
2933: #
2934: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2935: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
2936: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2937: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2938: # in course's home server.
2939: #
2940:
2941: sub process_coursefile {
2942: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2943: $mimetype)=@_;
2944: my $fetchresult;
2945: my $home=&homeserver($docuname,$docudom);
2946: if ($action eq 'propagate') {
2947: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2948: $home);
2949: } else {
2950: my $fpath = '';
2951: my $fname = $file;
2952: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2953: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2954: my $filepath = &build_filepath($fpath);
2955: if ($action eq 'copy') {
2956: if ($source eq '') {
2957: $fetchresult = 'no source file';
2958: return $fetchresult;
2959: } else {
2960: my $destination = $filepath.'/'.$fname;
2961: rename($source,$destination);
2962: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2963: $home);
2964: }
2965: } elsif ($action eq 'uploaddoc') {
2966: open(my $fh,'>'.$filepath.'/'.$fname);
2967: print $fh $env{'form.'.$source};
2968: close($fh);
2969: if ($parser eq 'parse') {
2970: my $mm = new File::MMagic;
2971: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2972: if ($type eq 'text/html') {
2973: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2974: unless ($parse_result eq 'ok') {
2975: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2976: }
2977: }
2978: if (ref($mimetype)) {
2979: $$mimetype = $type;
2980: }
2981: }
2982: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2983: $home);
2984: if ($fetchresult eq 'ok') {
2985: return '/uploaded/'.$fpath.'/'.$fname;
2986: } else {
2987: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2988: ' to host '.$home.': '.$fetchresult);
2989: return '/adm/notfound.html';
2990: }
2991: }
2992: }
2993: unless ( $fetchresult eq 'ok') {
2994: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2995: ' to host '.$home.': '.$fetchresult);
2996: }
2997: return $fetchresult;
2998: }
2999:
3000: sub build_filepath {
3001: my ($fpath) = @_;
3002: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3003: unless ($fpath eq '') {
3004: my @parts=split('/',$fpath);
3005: foreach my $part (@parts) {
3006: $filepath.= '/'.$part;
3007: if ((-e $filepath)!=1) {
3008: mkdir($filepath,0777);
3009: }
3010: }
3011: }
3012: return $filepath;
3013: }
3014:
3015: sub store_edited_file {
3016: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
3017: my $file = $primary_url;
3018: $file =~ s#^/uploaded/$docudom/$docuname/##;
3019: my $fpath = '';
3020: my $fname = $file;
3021: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3022: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3023: my $filepath = &build_filepath($fpath);
3024: open(my $fh,'>'.$filepath.'/'.$fname);
3025: print $fh $content;
3026: close($fh);
3027: my $home=&homeserver($docuname,$docudom);
3028: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3029: $home);
3030: if ($$fetchresult eq 'ok') {
3031: return '/uploaded/'.$fpath.'/'.$fname;
3032: } else {
3033: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3034: ' to host '.$home.': '.$$fetchresult);
3035: return '/adm/notfound.html';
3036: }
3037: }
3038:
3039: sub clean_filename {
3040: my ($fname,$args)=@_;
3041: # Replace Windows backslashes by forward slashes
3042: $fname=~s/\\/\//g;
3043: if (!$args->{'keep_path'}) {
3044: # Get rid of everything but the actual filename
3045: $fname=~s/^.*\/([^\/]+)$/$1/;
3046: }
3047: # Replace spaces by underscores
3048: $fname=~s/\s+/\_/g;
3049: # Replace all other weird characters by nothing
3050: $fname=~s{[^/\w\.\-]}{}g;
3051: # Replace all .\d. sequences with _\d. so they no longer look like version
3052: # numbers
3053: $fname=~s/\.(\d+)(?=\.)/_$1/g;
3054: return $fname;
3055: }
3056: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3057: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3058: # image with the same aspect ratio as the original, but with dimensions which do
3059: # not exceed $resizewidth and $resizeheight.
3060:
3061: sub resizeImage {
3062: my ($img_path,$resizewidth,$resizeheight) = @_;
3063: my $ima = Image::Magick->new;
3064: my $resized;
3065: if (-e $img_path) {
3066: $ima->Read($img_path);
3067: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3068: my $width = $ima->Get('width');
3069: my $height = $ima->Get('height');
3070: if ($width > $resizewidth) {
3071: my $factor = $width/$resizewidth;
3072: my $newheight = $height/$factor;
3073: $ima->Scale(width=>$resizewidth,height=>$newheight);
3074: $resized = 1;
3075: }
3076: }
3077: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3078: my $width = $ima->Get('width');
3079: my $height = $ima->Get('height');
3080: if ($height > $resizeheight) {
3081: my $factor = $height/$resizeheight;
3082: my $newwidth = $width/$factor;
3083: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3084: $resized = 1;
3085: }
3086: }
3087: if ($resized) {
3088: $ima->Write($img_path);
3089: }
3090: }
3091: return;
3092: }
3093:
3094: # --------------- Take an uploaded file and put it into the userfiles directory
3095: # input: $formname - the contents of the file are in $env{"form.$formname"}
3096: # the desired filename is in $env{"form.$formname.filename"}
3097: # $context - possible values: coursedoc, existingfile, overwrite,
3098: # canceloverwrite, or ''.
3099: # if 'coursedoc': upload to the current course
3100: # if 'existingfile': write file to tmp/overwrites directory
3101: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3102: # $context is passed as argument to &finishuserfileupload
3103: # $subdir - directory in userfile to store the file into
3104: # $parser - instruction to parse file for objects ($parser = parse)
3105: # $allfiles - reference to hash for embedded objects
3106: # $codebase - reference to hash for codebase of java objects
3107: # $desuname - username for permanent storage of uploaded file
3108: # $dsetudom - domain for permanaent storage of uploaded file
3109: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3110: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
3111: # $resizewidth - width (pixels) to which to resize uploaded image
3112: # $resizeheight - height (pixels) to which to resize uploaded image
3113: # $mimetype - reference to scalar to accommodate mime type determined
3114: # from File::MMagic.
3115: #
3116: # output: url of file in userspace, or error: <message>
3117: # or /adm/notfound.html if failure to upload occurse
3118:
3119: sub userfileupload {
3120: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
3121: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
3122: if (!defined($subdir)) { $subdir='unknown'; }
3123: my $fname=$env{'form.'.$formname.'.filename'};
3124: $fname=&clean_filename($fname);
3125: # See if there is anything left
3126: unless ($fname) { return 'error: no uploaded file'; }
3127: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3128: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3129: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3130: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3131: my $now = time;
3132: my $filepath;
3133: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
3134: $filepath = 'tmp/helprequests/'.$now;
3135: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3136: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3137: '_'.$env{'user.domain'}.'/pending';
3138: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3139: my ($docuname,$docudom);
3140: if ($destudom) {
3141: $docudom = $destudom;
3142: } else {
3143: $docudom = $env{'user.domain'};
3144: }
3145: if ($destuname) {
3146: $docuname = $destuname;
3147: } else {
3148: $docuname = $env{'user.name'};
3149: }
3150: if (exists($env{'form.group'})) {
3151: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3152: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3153: }
3154: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3155: if ($context eq 'canceloverwrite') {
3156: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3157: if (-e $tempfile) {
3158: my @info = stat($tempfile);
3159: if ($info[9] eq $env{'form.timestamp'}) {
3160: unlink($tempfile);
3161: }
3162: }
3163: return;
3164: }
3165: }
3166: # Create the directory if not present
3167: my @parts=split(/\//,$filepath);
3168: my $fullpath = $perlvar{'lonDaemons'};
3169: for (my $i=0;$i<@parts;$i++) {
3170: $fullpath .= '/'.$parts[$i];
3171: if ((-e $fullpath)!=1) {
3172: mkdir($fullpath,0777);
3173: }
3174: }
3175: open(my $fh,'>'.$fullpath.'/'.$fname);
3176: print $fh $env{'form.'.$formname};
3177: close($fh);
3178: if ($context eq 'existingfile') {
3179: my @info = stat($fullpath.'/'.$fname);
3180: return ($fullpath.'/'.$fname,$info[9]);
3181: } else {
3182: return $fullpath.'/'.$fname;
3183: }
3184: }
3185: if ($subdir eq 'scantron') {
3186: $fname = 'scantron_orig_'.$fname;
3187: } else {
3188: $fname="$subdir/$fname";
3189: }
3190: if ($context eq 'coursedoc') {
3191: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3192: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3193: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
3194: return &finishuserfileupload($docuname,$docudom,
3195: $formname,$fname,$parser,$allfiles,
3196: $codebase,$thumbwidth,$thumbheight,
3197: $resizewidth,$resizeheight,$context,$mimetype);
3198: } else {
3199: if ($env{'form.folder'}) {
3200: $fname=$env{'form.folder'}.'/'.$fname;
3201: }
3202: return &process_coursefile('uploaddoc',$docuname,$docudom,
3203: $fname,$formname,$parser,
3204: $allfiles,$codebase,$mimetype);
3205: }
3206: } elsif (defined($destuname)) {
3207: my $docuname=$destuname;
3208: my $docudom=$destudom;
3209: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3210: $parser,$allfiles,$codebase,
3211: $thumbwidth,$thumbheight,
3212: $resizewidth,$resizeheight,$context,$mimetype);
3213: } else {
3214: my $docuname=$env{'user.name'};
3215: my $docudom=$env{'user.domain'};
3216: if (exists($env{'form.group'})) {
3217: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3218: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3219: }
3220: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3221: $parser,$allfiles,$codebase,
3222: $thumbwidth,$thumbheight,
3223: $resizewidth,$resizeheight,$context,$mimetype);
3224: }
3225: }
3226:
3227: sub finishuserfileupload {
3228: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
3229: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
3230: my $path=$docudom.'/'.$docuname.'/';
3231: my $filepath=$perlvar{'lonDocRoot'};
3232:
3233: my ($fnamepath,$file,$fetchthumb);
3234: $file=$fname;
3235: if ($fname=~m|/|) {
3236: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3237: $path.=$fnamepath.'/';
3238: }
3239: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
3240: my $count;
3241: for ($count=4;$count<=$#parts;$count++) {
3242: $filepath.="/$parts[$count]";
3243: if ((-e $filepath)!=1) {
3244: mkdir($filepath,0777);
3245: }
3246: }
3247:
3248: # Save the file
3249: {
3250: if (!open(FH,'>'.$filepath.'/'.$file)) {
3251: &logthis('Failed to create '.$filepath.'/'.$file);
3252: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3253: return '/adm/notfound.html';
3254: }
3255: if ($context eq 'overwrite') {
3256: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
3257: my $target = $filepath.'/'.$file;
3258: if (-e $source) {
3259: my @info = stat($source);
3260: if ($info[9] eq $env{'form.timestamp'}) {
3261: unless (&File::Copy::move($source,$target)) {
3262: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3263: return "Moving from $source failed";
3264: }
3265: } else {
3266: return "Temporary file: $source had unexpected date/time for last modification";
3267: }
3268: } else {
3269: return "Temporary file: $source missing";
3270: }
3271: } elsif (!print FH ($env{'form.'.$formname})) {
3272: &logthis('Failed to write to '.$filepath.'/'.$file);
3273: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3274: return '/adm/notfound.html';
3275: }
3276: close(FH);
3277: if ($resizewidth && $resizeheight) {
3278: my $mm = new File::MMagic;
3279: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3280: if ($mime_type =~ m{^image/}) {
3281: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3282: }
3283: }
3284: }
3285: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3286: if (ref($mimetype)) {
3287: if ($$mimetype eq '') {
3288: my $mm = new File::MMagic;
3289: my $type = $mm->checktype_filename($filepath.'/'.$file);
3290: $$mimetype = $type;
3291: }
3292: }
3293: }
3294: if ($parser eq 'parse') {
3295: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
3296: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3297: $allfiles,$codebase);
3298: unless ($parse_result eq 'ok') {
3299: &logthis('Failed to parse '.$filepath.$file.
3300: ' for embedded media: '.$parse_result);
3301: }
3302: }
3303: }
3304: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3305: my $input = $filepath.'/'.$file;
3306: my $output = $filepath.'/'.'tn-'.$file;
3307: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3308: system("convert -sample $thumbsize $input $output");
3309: if (-e $filepath.'/'.'tn-'.$file) {
3310: $fetchthumb = 1;
3311: }
3312: }
3313:
3314: # Notify homeserver to grep it
3315: #
3316: my $docuhome=&homeserver($docuname,$docudom);
3317: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
3318: if ($fetchresult eq 'ok') {
3319: if ($fetchthumb) {
3320: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3321: if ($thumbresult ne 'ok') {
3322: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3323: $docuhome.': '.$thumbresult);
3324: }
3325: }
3326: #
3327: # Return the URL to it
3328: return '/uploaded/'.$path.$file;
3329: } else {
3330: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3331: ': '.$fetchresult);
3332: return '/adm/notfound.html';
3333: }
3334: }
3335:
3336: sub extract_embedded_items {
3337: my ($fullpath,$allfiles,$codebase,$content) = @_;
3338: my @state = ();
3339: my (%lastids,%related,%shockwave,%flashvars);
3340: my %javafiles = (
3341: codebase => '',
3342: code => '',
3343: archive => ''
3344: );
3345: my %mediafiles = (
3346: src => '',
3347: movie => '',
3348: );
3349: my $p;
3350: if ($content) {
3351: $p = HTML::LCParser->new($content);
3352: } else {
3353: $p = HTML::LCParser->new($fullpath);
3354: }
3355: while (my $t=$p->get_token()) {
3356: if ($t->[0] eq 'S') {
3357: my ($tagname, $attr) = ($t->[1],$t->[2]);
3358: push(@state, $tagname);
3359: if (lc($tagname) eq 'allow') {
3360: &add_filetype($allfiles,$attr->{'src'},'src');
3361: }
3362: if (lc($tagname) eq 'img') {
3363: &add_filetype($allfiles,$attr->{'src'},'src');
3364: }
3365: if (lc($tagname) eq 'a') {
3366: &add_filetype($allfiles,$attr->{'href'},'href');
3367: }
3368: if (lc($tagname) eq 'script') {
3369: my $src;
3370: if ($attr->{'archive'} =~ /\.jar$/i) {
3371: &add_filetype($allfiles,$attr->{'archive'},'archive');
3372: } else {
3373: if ($attr->{'src'} ne '') {
3374: $src = $attr->{'src'};
3375: &add_filetype($allfiles,$src,'src');
3376: }
3377: }
3378: my $text = $p->get_trimmed_text();
3379: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3380: my @swfargs = split(/,/,$1);
3381: foreach my $item (@swfargs) {
3382: $item =~ s/["']//g;
3383: $item =~ s/^\s+//;
3384: $item =~ s/\s+$//;
3385: }
3386: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3387: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3388: push(@{$related{$swfargs[0]}},$swfargs[2]);
3389: } else {
3390: $related{$swfargs[0]} = [$swfargs[2]];
3391: }
3392: }
3393: }
3394: }
3395: if (lc($tagname) eq 'link') {
3396: if (lc($attr->{'rel'}) eq 'stylesheet') {
3397: &add_filetype($allfiles,$attr->{'href'},'href');
3398: }
3399: }
3400: if (lc($tagname) eq 'object' ||
3401: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3402: foreach my $item (keys(%javafiles)) {
3403: $javafiles{$item} = '';
3404: }
3405: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3406: $lastids{lc($tagname)} = $attr->{'id'};
3407: }
3408: }
3409: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3410: my $name = lc($attr->{'name'});
3411: foreach my $item (keys(%javafiles)) {
3412: if ($name eq $item) {
3413: $javafiles{$item} = $attr->{'value'};
3414: last;
3415: }
3416: }
3417: my $pathfrom;
3418: foreach my $item (keys(%mediafiles)) {
3419: if ($name eq $item) {
3420: $pathfrom = $attr->{'value'};
3421: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3422: &add_filetype($allfiles,$pathfrom,$name);
3423: last;
3424: }
3425: }
3426: if ($name eq 'flashvars') {
3427: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3428: }
3429: if ($pathfrom ne '') {
3430: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3431: $pathfrom);
3432: }
3433: }
3434: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3435: foreach my $item (keys(%javafiles)) {
3436: if ($attr->{$item}) {
3437: $javafiles{$item} = $attr->{$item};
3438: last;
3439: }
3440: }
3441: foreach my $item (keys(%mediafiles)) {
3442: if ($attr->{$item}) {
3443: &add_filetype($allfiles,$attr->{$item},$item);
3444: last;
3445: }
3446: }
3447: if (lc($tagname) eq 'embed') {
3448: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3449: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3450: $attr->{'src'});
3451: }
3452: }
3453: }
3454: if ($t->[4] =~ m{/>$}) {
3455: pop(@state);
3456: }
3457: } elsif ($t->[0] eq 'E') {
3458: my ($tagname) = ($t->[1]);
3459: if ($javafiles{'codebase'} ne '') {
3460: $javafiles{'codebase'} .= '/';
3461: }
3462: if (lc($tagname) eq 'applet' ||
3463: lc($tagname) eq 'object' ||
3464: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3465: ) {
3466: foreach my $item (keys(%javafiles)) {
3467: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3468: my $file=$javafiles{'codebase'}.$javafiles{$item};
3469: &add_filetype($allfiles,$file,$item);
3470: }
3471: }
3472: }
3473: pop @state;
3474: }
3475: }
3476: foreach my $id (sort(keys(%flashvars))) {
3477: if ($shockwave{$id} ne '') {
3478: my @pairs = split(/\&/,$flashvars{$id});
3479: foreach my $pair (@pairs) {
3480: my ($key,$value) = split(/\=/,$pair);
3481: if ($key eq 'thumb') {
3482: &add_filetype($allfiles,$value,$key);
3483: } elsif ($key eq 'content') {
3484: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3485: my ($ext) = ($value =~ /\.([^.]+)$/);
3486: if ($ext ne '') {
3487: &add_filetype($allfiles,$path.$value,$ext);
3488: }
3489: }
3490: }
3491: }
3492: }
3493: return 'ok';
3494: }
3495:
3496: sub add_filetype {
3497: my ($allfiles,$file,$type)=@_;
3498: if (exists($allfiles->{$file})) {
3499: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3500: push(@{$allfiles->{$file}}, &escape($type));
3501: }
3502: } else {
3503: @{$allfiles->{$file}} = (&escape($type));
3504: }
3505: }
3506:
3507: sub embedded_dependency {
3508: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3509: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3510: if (($identifier ne '') &&
3511: (ref($related->{$identifier}) eq 'ARRAY') &&
3512: ($pathfrom ne '')) {
3513: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3514: foreach my $dep (@{$related->{$identifier}}) {
3515: &add_filetype($allfiles,$path.$dep,'object');
3516: }
3517: }
3518: }
3519: return;
3520: }
3521:
3522: sub removeuploadedurl {
3523: my ($url)=@_;
3524: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
3525: return &removeuserfile($uname,$udom,$fname);
3526: }
3527:
3528: sub removeuserfile {
3529: my ($docuname,$docudom,$fname)=@_;
3530: my $home=&homeserver($docuname,$docudom);
3531: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
3532: if ($result eq 'ok') {
3533: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3534: my $metafile = $fname.'.meta';
3535: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
3536: my $url = "/uploaded/$docudom/$docuname/$fname";
3537: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3538: my $sqlresult =
3539: &update_portfolio_table($docuname,$docudom,$file,
3540: 'portfolio_metadata',$group,
3541: 'delete');
3542: }
3543: }
3544: return $result;
3545: }
3546:
3547: sub mkdiruserfile {
3548: my ($docuname,$docudom,$dir)=@_;
3549: my $home=&homeserver($docuname,$docudom);
3550: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3551: }
3552:
3553: sub renameuserfile {
3554: my ($docuname,$docudom,$old,$new)=@_;
3555: my $home=&homeserver($docuname,$docudom);
3556: my $result = &reply("renameuserfile:$docudom:$docuname:".
3557: &escape("$old").':'.&escape("$new"),$home);
3558: if ($result eq 'ok') {
3559: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3560: my $oldmeta = $old.'.meta';
3561: my $newmeta = $new.'.meta';
3562: my $metaresult =
3563: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
3564: my $url = "/uploaded/$docudom/$docuname/$old";
3565: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3566: my $sqlresult =
3567: &update_portfolio_table($docuname,$docudom,$file,
3568: 'portfolio_metadata',$group,
3569: 'delete');
3570: }
3571: }
3572: return $result;
3573: }
3574:
3575: # ------------------------------------------------------------------------- Log
3576:
3577: sub log {
3578: my ($dom,$nam,$hom,$what)=@_;
3579: return critical("log:$dom:$nam:$what",$hom);
3580: }
3581:
3582: # ------------------------------------------------------------------ Course Log
3583: #
3584: # This routine flushes several buffers of non-mission-critical nature
3585: #
3586:
3587: sub flushcourselogs {
3588: &logthis('Flushing log buffers');
3589: #
3590: # course logs
3591: # This is a log of all transactions in a course, which can be used
3592: # for data mining purposes
3593: #
3594: # It also collects the courseid database, which lists last transaction
3595: # times and course titles for all courseids
3596: #
3597: my %courseidbuffer=();
3598: foreach my $crsid (keys(%courselogs)) {
3599: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
3600: &escape($courselogs{$crsid}),
3601: $coursehombuf{$crsid}) eq 'ok') {
3602: delete $courselogs{$crsid};
3603: } else {
3604: &logthis('Failed to flush log buffer for '.$crsid);
3605: if (length($courselogs{$crsid})>40000) {
3606: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
3607: " exceeded maximum size, deleting.</font>");
3608: delete $courselogs{$crsid};
3609: }
3610: }
3611: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
3612: 'description' => $coursedescrbuf{$crsid},
3613: 'inst_code' => $courseinstcodebuf{$crsid},
3614: 'type' => $coursetypebuf{$crsid},
3615: 'owner' => $courseownerbuf{$crsid},
3616: };
3617: }
3618: #
3619: # Write course id database (reverse lookup) to homeserver of courses
3620: # Is used in pickcourse
3621: #
3622: foreach my $crs_home (keys(%courseidbuffer)) {
3623: my $response = &courseidput(&host_domain($crs_home),
3624: $courseidbuffer{$crs_home},
3625: $crs_home,'timeonly');
3626: }
3627: #
3628: # File accesses
3629: # Writes to the dynamic metadata of resources to get hit counts, etc.
3630: #
3631: foreach my $entry (keys(%accesshash)) {
3632: if ($entry =~ /___count$/) {
3633: my ($dom,$name);
3634: ($dom,$name,undef)=
3635: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
3636: if (! defined($dom) || $dom eq '' ||
3637: ! defined($name) || $name eq '') {
3638: my $cid = $env{'request.course.id'};
3639: $dom = $env{'request.'.$cid.'.domain'};
3640: $name = $env{'request.'.$cid.'.num'};
3641: }
3642: my $value = $accesshash{$entry};
3643: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3644: my %temphash=($url => $value);
3645: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3646: if ($result eq 'ok') {
3647: delete $accesshash{$entry};
3648: }
3649: } else {
3650: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
3651: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
3652: my %temphash=($entry => $accesshash{$entry});
3653: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3654: delete $accesshash{$entry};
3655: }
3656: }
3657: }
3658: #
3659: # Roles
3660: # Reverse lookup of user roles for course faculty/staff and co-authorship
3661: #
3662: foreach my $entry (keys(%userrolehash)) {
3663: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
3664: split(/\:/,$entry);
3665: if (&Apache::lonnet::put('nohist_userroles',
3666: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
3667: $rudom,$runame) eq 'ok') {
3668: delete $userrolehash{$entry};
3669: }
3670: }
3671: #
3672: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3673: #
3674: my %domrolebuffer = ();
3675: foreach my $entry (keys(%domainrolehash)) {
3676: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
3677: if ($domrolebuffer{$rudom}) {
3678: $domrolebuffer{$rudom}.='&'.&escape($entry).
3679: '='.&escape($domainrolehash{$entry});
3680: } else {
3681: $domrolebuffer{$rudom}.=&escape($entry).
3682: '='.&escape($domainrolehash{$entry});
3683: }
3684: delete $domainrolehash{$entry};
3685: }
3686: foreach my $dom (keys(%domrolebuffer)) {
3687: my %servers = &get_servers($dom,'library');
3688: foreach my $tryserver (keys(%servers)) {
3689: unless (&reply('domroleput:'.$dom.':'.
3690: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3691: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3692: }
3693: }
3694: }
3695: $dumpcount++;
3696: }
3697:
3698: sub courselog {
3699: my $what=shift;
3700: $what=time.':'.$what;
3701: unless ($env{'request.course.id'}) { return ''; }
3702: $coursedombuf{$env{'request.course.id'}}=
3703: $env{'course.'.$env{'request.course.id'}.'.domain'};
3704: $coursenumbuf{$env{'request.course.id'}}=
3705: $env{'course.'.$env{'request.course.id'}.'.num'};
3706: $coursehombuf{$env{'request.course.id'}}=
3707: $env{'course.'.$env{'request.course.id'}.'.home'};
3708: $coursedescrbuf{$env{'request.course.id'}}=
3709: $env{'course.'.$env{'request.course.id'}.'.description'};
3710: $courseinstcodebuf{$env{'request.course.id'}}=
3711: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3712: $courseownerbuf{$env{'request.course.id'}}=
3713: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
3714: $coursetypebuf{$env{'request.course.id'}}=
3715: $env{'course.'.$env{'request.course.id'}.'.type'};
3716: if (defined $courselogs{$env{'request.course.id'}}) {
3717: $courselogs{$env{'request.course.id'}}.='&'.$what;
3718: } else {
3719: $courselogs{$env{'request.course.id'}}.=$what;
3720: }
3721: if (length($courselogs{$env{'request.course.id'}})>4048) {
3722: &flushcourselogs();
3723: }
3724: }
3725:
3726: sub courseacclog {
3727: my $fnsymb=shift;
3728: unless ($env{'request.course.id'}) { return ''; }
3729: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
3730: if ($fnsymb=~/$LONCAPA::assess_re/) {
3731: $what.=':POST';
3732: # FIXME: Probably ought to escape things....
3733: foreach my $key (keys(%env)) {
3734: if ($key=~/^form\.(.*)/) {
3735: my $formitem = $1;
3736: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3737: $what.=':'.$formitem.'='.$env{$key};
3738: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3739: $what.=':'.$formitem.'='.$env{$key};
3740: }
3741: }
3742: }
3743: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3744: # FIXME: We should not be depending on a form parameter that someone
3745: # editing lonsearchcat.pm might change in the future.
3746: if ($env{'form.phase'} eq 'course_search') {
3747: $what.= ':POST';
3748: # FIXME: Probably ought to escape things....
3749: foreach my $element ('courseexp','crsfulltext','crsrelated',
3750: 'crsdiscuss') {
3751: $what.=':'.$element.'='.$env{'form.'.$element};
3752: }
3753: }
3754: }
3755: &courselog($what);
3756: }
3757:
3758: sub countacc {
3759: my $url=&declutter(shift);
3760: return if (! defined($url) || $url eq '');
3761: unless ($env{'request.course.id'}) { return ''; }
3762: #
3763: # Mark that this url was used in this course
3764: #
3765: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
3766: #
3767: # Increase the access count for this resource in this child process
3768: #
3769: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
3770: $accesshash{$key}++;
3771: }
3772:
3773: sub linklog {
3774: my ($from,$to)=@_;
3775: $from=&declutter($from);
3776: $to=&declutter($to);
3777: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3778: $accesshash{$to.'___'.$from.'___goto'}=1;
3779: }
3780:
3781: sub statslog {
3782: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3783: if ($users<2) { return; }
3784: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3785: 'course' => $env{'request.course.id'},
3786: 'sections' => '"all"',
3787: 'num_students' => $users,
3788: 'part' => $part,
3789: 'symb' => $symb,
3790: 'mean_tries' => $av_attempts,
3791: 'deg_of_diff' => $degdiff});
3792: foreach my $key (keys(%dynstore)) {
3793: $accesshash{$key}=$dynstore{$key};
3794: }
3795: }
3796:
3797: sub userrolelog {
3798: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
3799: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
3800: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3801: $userrolehash
3802: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3803: =$tend.':'.$tstart;
3804: }
3805: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
3806: $userrolehash
3807: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3808: =$tend.':'.$tstart;
3809: }
3810: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
3811: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3812: $domainrolehash
3813: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3814: = $tend.':'.$tstart;
3815: }
3816: }
3817:
3818: sub courserolelog {
3819: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3820: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3821: my $cdom = $1;
3822: my $cnum = $2;
3823: my $sec = $3;
3824: my $namespace = 'rolelog';
3825: my %storehash = (
3826: role => $trole,
3827: start => $tstart,
3828: end => $tend,
3829: selfenroll => $selfenroll,
3830: context => $context,
3831: );
3832: if ($trole eq 'gr') {
3833: $namespace = 'groupslog';
3834: $storehash{'group'} = $sec;
3835: } else {
3836: $storehash{'section'} = $sec;
3837: }
3838: &write_log('course',$namespace,\%storehash,$delflag,$username,
3839: $domain,$cnum,$cdom);
3840: if (($trole ne 'st') || ($sec ne '')) {
3841: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3842: }
3843: }
3844: return;
3845: }
3846:
3847: sub domainrolelog {
3848: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3849: if ($area =~ m{^/($match_domain)/$}) {
3850: my $cdom = $1;
3851: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3852: my $namespace = 'rolelog';
3853: my %storehash = (
3854: role => $trole,
3855: start => $tstart,
3856: end => $tend,
3857: context => $context,
3858: );
3859: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3860: $domain,$domconfiguser,$cdom);
3861: }
3862: return;
3863:
3864: }
3865:
3866: sub coauthorrolelog {
3867: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3868: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3869: my $audom = $1;
3870: my $auname = $2;
3871: my $namespace = 'rolelog';
3872: my %storehash = (
3873: role => $trole,
3874: start => $tstart,
3875: end => $tend,
3876: context => $context,
3877: );
3878: &write_log('author',$namespace,\%storehash,$delflag,$username,
3879: $domain,$auname,$audom);
3880: }
3881: return;
3882: }
3883:
3884: sub get_course_adv_roles {
3885: my ($cid,$codes) = @_;
3886: $cid=$env{'request.course.id'} unless (defined($cid));
3887: my %coursehash=&coursedescription($cid);
3888: my $crstype = &Apache::loncommon::course_type($cid);
3889: my %nothide=();
3890: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3891: if ($user !~ /:/) {
3892: $nothide{join(':',split(/[\@]/,$user))}=1;
3893: } else {
3894: $nothide{$user}=1;
3895: }
3896: }
3897: my @possdoms = ($coursehash{'domain'});
3898: if ($coursehash{'checkforpriv'}) {
3899: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3900: }
3901: my %returnhash=();
3902: my %dumphash=
3903: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3904: my $now=time;
3905: my %privileged;
3906: foreach my $entry (keys(%dumphash)) {
3907: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3908: if (($tstart) && ($tstart<0)) { next; }
3909: if (($tend) && ($tend<$now)) { next; }
3910: if (($tstart) && ($now<$tstart)) { next; }
3911: my ($role,$username,$domain,$section)=split(/\:/,$entry);
3912: if ($username eq '' || $domain eq '') { next; }
3913: if ((&privileged($username,$domain,\@possdoms)) &&
3914: (!$nothide{$username.':'.$domain})) { next; }
3915: if ($role eq 'cr') { next; }
3916: if ($codes) {
3917: if ($section) { $role .= ':'.$section; }
3918: if ($returnhash{$role}) {
3919: $returnhash{$role}.=','.$username.':'.$domain;
3920: } else {
3921: $returnhash{$role}=$username.':'.$domain;
3922: }
3923: } else {
3924: my $key=&plaintext($role,$crstype);
3925: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
3926: if ($returnhash{$key}) {
3927: $returnhash{$key}.=','.$username.':'.$domain;
3928: } else {
3929: $returnhash{$key}=$username.':'.$domain;
3930: }
3931: }
3932: }
3933: return %returnhash;
3934: }
3935:
3936: sub get_my_roles {
3937: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
3938: unless (defined($uname)) { $uname=$env{'user.name'}; }
3939: unless (defined($udom)) { $udom=$env{'user.domain'}; }
3940: my (%dumphash,%nothide);
3941: if ($context eq 'userroles') {
3942: %dumphash = &dump('roles',$udom,$uname);
3943: } else {
3944: %dumphash = &dump('nohist_userroles',$udom,$uname);
3945: if ($hidepriv) {
3946: my %coursehash=&coursedescription($udom.'_'.$uname);
3947: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3948: if ($user !~ /:/) {
3949: $nothide{join(':',split(/[\@]/,$user))} = 1;
3950: } else {
3951: $nothide{$user} = 1;
3952: }
3953: }
3954: }
3955: }
3956: my %returnhash=();
3957: my $now=time;
3958: my %privileged;
3959: foreach my $entry (keys(%dumphash)) {
3960: my ($role,$tend,$tstart);
3961: if ($context eq 'userroles') {
3962: next if ($entry =~ /^rolesdef/);
3963: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3964: } else {
3965: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3966: }
3967: if (($tstart) && ($tstart<0)) { next; }
3968: my $status = 'active';
3969: if (($tend) && ($tend<=$now)) {
3970: $status = 'previous';
3971: }
3972: if (($tstart) && ($now<$tstart)) {
3973: $status = 'future';
3974: }
3975: if (ref($types) eq 'ARRAY') {
3976: if (!grep(/^\Q$status\E$/,@{$types})) {
3977: next;
3978: }
3979: } else {
3980: if ($status ne 'active') {
3981: next;
3982: }
3983: }
3984: my ($rolecode,$username,$domain,$section,$area);
3985: if ($context eq 'userroles') {
3986: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
3987: (undef,$domain,$username,$section) = split(/\//,$area);
3988: } else {
3989: ($role,$username,$domain,$section) = split(/\:/,$entry);
3990: }
3991: if (ref($roledoms) eq 'ARRAY') {
3992: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3993: next;
3994: }
3995: }
3996: if (ref($roles) eq 'ARRAY') {
3997: if (!grep(/^\Q$role\E$/,@{$roles})) {
3998: if ($role =~ /^cr\//) {
3999: if (!grep(/^cr$/,@{$roles})) {
4000: next;
4001: }
4002: } elsif ($role =~ /^gr\//) {
4003: if (!grep(/^gr$/,@{$roles})) {
4004: next;
4005: }
4006: } else {
4007: next;
4008: }
4009: }
4010: }
4011: if ($hidepriv) {
4012: my @privroles = ('dc','su');
4013: if ($context eq 'userroles') {
4014: next if (grep(/^\Q$role\E$/,@privroles));
4015: } else {
4016: my $possdoms = [$domain];
4017: if (ref($roledoms) eq 'ARRAY') {
4018: push(@{$possdoms},@{$roledoms});
4019: }
4020: if (&privileged($username,$domain,$possdoms,\@privroles)) {
4021: if (!$nothide{$username.':'.$domain}) {
4022: next;
4023: }
4024: }
4025: }
4026: }
4027: if ($withsec) {
4028: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4029: $tstart.':'.$tend;
4030: } else {
4031: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4032: }
4033: }
4034: return %returnhash;
4035: }
4036:
4037: # ----------------------------------------------------- Frontpage Announcements
4038: #
4039: #
4040:
4041: sub postannounce {
4042: my ($server,$text)=@_;
4043: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
4044: unless ($text=~/\w/) { $text=''; }
4045: return &reply('setannounce:'.&escape($text),$server);
4046: }
4047:
4048: sub getannounce {
4049:
4050: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
4051: my $announcement='';
4052: while (my $line = <$fh>) { $announcement .= $line; }
4053: close($fh);
4054: if ($announcement=~/\w/) {
4055: return
4056: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
4057: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
4058: } else {
4059: return '';
4060: }
4061: } else {
4062: return '';
4063: }
4064: }
4065:
4066: # ---------------------------------------------------------- Course ID routines
4067: # Deal with domain's nohist_courseid.db files
4068: #
4069:
4070: sub courseidput {
4071: my ($domain,$storehash,$coursehome,$caller) = @_;
4072: return unless (ref($storehash) eq 'HASH');
4073: my $outcome;
4074: if ($caller eq 'timeonly') {
4075: my $cids = '';
4076: foreach my $item (keys(%$storehash)) {
4077: $cids.=&escape($item).'&';
4078: }
4079: $cids=~s/\&$//;
4080: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4081: $coursehome);
4082: } else {
4083: my $items = '';
4084: foreach my $item (keys(%$storehash)) {
4085: $items.= &escape($item).'='.
4086: &freeze_escape($$storehash{$item}).'&';
4087: }
4088: $items=~s/\&$//;
4089: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4090: $coursehome);
4091: }
4092: if ($outcome eq 'unknown_cmd') {
4093: my $what;
4094: foreach my $cid (keys(%$storehash)) {
4095: $what .= &escape($cid).'=';
4096: foreach my $item ('description','inst_code','owner','type') {
4097: $what .= &escape($storehash->{$cid}{$item}).':';
4098: }
4099: $what =~ s/\:$/&/;
4100: }
4101: $what =~ s/\&$//;
4102: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4103: } else {
4104: return $outcome;
4105: }
4106: }
4107:
4108: sub courseiddump {
4109: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
4110: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
4111: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
4112: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
4113: my $as_hash = 1;
4114: my %returnhash;
4115: if (!$domfilter) { $domfilter=''; }
4116: my %libserv = &all_library();
4117: foreach my $tryserver (keys(%libserv)) {
4118: if ( ( $hostidflag == 1
4119: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4120: || (!defined($hostidflag)) ) {
4121:
4122: if (($domfilter eq '') ||
4123: (&host_domain($tryserver) eq $domfilter)) {
4124: my $rep;
4125: if (grep { $_ eq $tryserver } current_machine_ids()) {
4126: $rep = LONCAPA::Lond::dump_course_id_handler(
4127: join(":", (&host_domain($tryserver), $sincefilter,
4128: &escape($descfilter), &escape($instcodefilter),
4129: &escape($ownerfilter), &escape($coursefilter),
4130: &escape($typefilter), &escape($regexp_ok),
4131: $as_hash, &escape($selfenrollonly),
4132: &escape($catfilter), $showhidden, $caller,
4133: &escape($cloner), &escape($cc_clone), $cloneonly,
4134: &escape($createdbefore), &escape($createdafter),
4135: &escape($creationcontext), $domcloner)));
4136: } else {
4137: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4138: $sincefilter.':'.&escape($descfilter).':'.
4139: &escape($instcodefilter).':'.&escape($ownerfilter).
4140: ':'.&escape($coursefilter).':'.&escape($typefilter).
4141: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4142: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4143: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4144: &escape($cc_clone).':'.$cloneonly.':'.
4145: &escape($createdbefore).':'.&escape($createdafter).':'.
4146: &escape($creationcontext).':'.$domcloner,
4147: $tryserver);
4148: }
4149:
4150: my @pairs=split(/\&/,$rep);
4151: foreach my $item (@pairs) {
4152: my ($key,$value)=split(/\=/,$item,2);
4153: $key = &unescape($key);
4154: next if ($key =~ /^error: 2 /);
4155: my $result = &thaw_unescape($value);
4156: if (ref($result) eq 'HASH') {
4157: $returnhash{$key}=$result;
4158: } else {
4159: my @responses = split(/:/,$value);
4160: my @items = ('description','inst_code','owner','type');
4161: for (my $i=0; $i<@responses; $i++) {
4162: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
4163: }
4164: }
4165: }
4166: }
4167: }
4168: }
4169: return %returnhash;
4170: }
4171:
4172: sub courselastaccess {
4173: my ($cdom,$cnum,$hostidref) = @_;
4174: my %returnhash;
4175: if ($cdom && $cnum) {
4176: my $chome = &homeserver($cnum,$cdom);
4177: if ($chome ne 'no_host') {
4178: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4179: &extract_lastaccess(\%returnhash,$rep);
4180: }
4181: } else {
4182: if (!$cdom) { $cdom=''; }
4183: my %libserv = &all_library();
4184: foreach my $tryserver (keys(%libserv)) {
4185: if (ref($hostidref) eq 'ARRAY') {
4186: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4187: }
4188: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4189: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4190: &extract_lastaccess(\%returnhash,$rep);
4191: }
4192: }
4193: }
4194: return %returnhash;
4195: }
4196:
4197: sub extract_lastaccess {
4198: my ($returnhash,$rep) = @_;
4199: if (ref($returnhash) eq 'HASH') {
4200: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4201: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4202: $rep eq '') {
4203: my @pairs=split(/\&/,$rep);
4204: foreach my $item (@pairs) {
4205: my ($key,$value)=split(/\=/,$item,2);
4206: $key = &unescape($key);
4207: next if ($key =~ /^error: 2 /);
4208: $returnhash->{$key} = &thaw_unescape($value);
4209: }
4210: }
4211: }
4212: return;
4213: }
4214:
4215: # ---------------------------------------------------------- DC e-mail
4216:
4217: sub dcmailput {
4218: my ($domain,$msgid,$message,$server)=@_;
4219: my $status = &Apache::lonnet::critical(
4220: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4221: &escape($message),$server);
4222: return $status;
4223: }
4224:
4225: sub dcmaildump {
4226: my ($dom,$startdate,$enddate,$senders) = @_;
4227: my %returnhash=();
4228:
4229: if (defined(&domain($dom,'primary'))) {
4230: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4231: &escape($enddate).':';
4232: my @esc_senders=map { &escape($_)} @$senders;
4233: $cmd.=&escape(join('&',@esc_senders));
4234: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
4235: my ($key,$value) = split(/\=/,$line,2);
4236: if (($key) && ($value)) {
4237: $returnhash{&unescape($key)} = &unescape($value);
4238: }
4239: }
4240: }
4241: return %returnhash;
4242: }
4243: # ---------------------------------------------------------- Domain roles
4244:
4245: sub get_domain_roles {
4246: my ($dom,$roles,$startdate,$enddate)=@_;
4247: if ((!defined($startdate)) || ($startdate eq '')) {
4248: $startdate = '.';
4249: }
4250: if ((!defined($enddate)) || ($enddate eq '')) {
4251: $enddate = '.';
4252: }
4253: my $rolelist;
4254: if (ref($roles) eq 'ARRAY') {
4255: $rolelist = join('&',@{$roles});
4256: }
4257: my %personnel = ();
4258:
4259: my %servers = &get_servers($dom,'library');
4260: foreach my $tryserver (keys(%servers)) {
4261: %{$personnel{$tryserver}}=();
4262: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4263: &escape($startdate).':'.
4264: &escape($enddate).':'.
4265: &escape($rolelist), $tryserver))) {
4266: my ($key,$value) = split(/\=/,$line,2);
4267: if (($key) && ($value)) {
4268: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4269: }
4270: }
4271: }
4272: return %personnel;
4273: }
4274:
4275: # ----------------------------------------------------------- Interval timing
4276:
4277: {
4278: # Caches needed for speedup of navmaps
4279: # We don't want to cache this for very long at all (5 seconds at most)
4280: #
4281: # The user for whom we cache
4282: my $cachedkey='';
4283: # The cached times for this user
4284: my %cachedtimes=();
4285: # When this was last done
4286: my $cachedtime=();
4287:
4288: sub load_all_first_access {
4289: my ($uname,$udom)=@_;
4290: if (($cachedkey eq $uname.':'.$udom) &&
4291: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
4292: return;
4293: }
4294: $cachedtime=time;
4295: $cachedkey=$uname.':'.$udom;
4296: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
4297: }
4298:
4299: sub get_first_access {
4300: my ($type,$argsymb,$argmap)=@_;
4301: my ($symb,$courseid,$udom,$uname)=&whichuser();
4302: if ($argsymb) { $symb=$argsymb; }
4303: my ($map,$id,$res)=&decode_symb($symb);
4304: if ($argmap) { $map = $argmap; }
4305: if ($type eq 'course') {
4306: $res='course';
4307: } elsif ($type eq 'map') {
4308: $res=&symbread($map);
4309: } else {
4310: $res=$symb;
4311: }
4312: &load_all_first_access($uname,$udom);
4313: return $cachedtimes{"$courseid\0$res"};
4314: }
4315:
4316: sub set_first_access {
4317: my ($type,$interval)=@_;
4318: my ($symb,$courseid,$udom,$uname)=&whichuser();
4319: my ($map,$id,$res)=&decode_symb($symb);
4320: if ($type eq 'course') {
4321: $res='course';
4322: } elsif ($type eq 'map') {
4323: $res=&symbread($map);
4324: } else {
4325: $res=$symb;
4326: }
4327: $cachedkey='';
4328: my $firstaccess=&get_first_access($type,$symb,$map);
4329: if (!$firstaccess) {
4330: my $start = time;
4331: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4332: $udom,$uname);
4333: if ($putres eq 'ok') {
4334: &put('timerinterval',{"$courseid\0$res"=>$interval},
4335: $udom,$uname);
4336: &appenv(
4337: {
4338: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4339: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4340: }
4341: );
4342: }
4343: return $putres;
4344: }
4345: return 'already_set';
4346: }
4347: }
4348: # --------------------------------------------- Set Expire Date for Spreadsheet
4349:
4350: sub expirespread {
4351: my ($uname,$udom,$stype,$usymb)=@_;
4352: my $cid=$env{'request.course.id'};
4353: if ($cid) {
4354: my $now=time;
4355: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
4356: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4357: $env{'course.'.$cid.'.num'}.
4358: ':nohist_expirationdates:'.
4359: &escape($key).'='.$now,
4360: $env{'course.'.$cid.'.home'})
4361: }
4362: return 'ok';
4363: }
4364:
4365: # ----------------------------------------------------- Devalidate Spreadsheets
4366:
4367: sub devalidate {
4368: my ($symb,$uname,$udom)=@_;
4369: my $cid=$env{'request.course.id'};
4370: if ($cid) {
4371: # delete the stored spreadsheets for
4372: # - the student level sheet of this user in course's homespace
4373: # - the assessment level sheet for this resource
4374: # for this user in user's homespace
4375: # - current conditional state info
4376: my $key=$uname.':'.$udom.':';
4377: my $status=
4378: &del('nohist_calculatedsheets',
4379: [$key.'studentcalc:'],
4380: $env{'course.'.$cid.'.domain'},
4381: $env{'course.'.$cid.'.num'})
4382: .' '.
4383: &del('nohist_calculatedsheets_'.$cid,
4384: [$key.'assesscalc:'.$symb],$udom,$uname);
4385: unless ($status eq 'ok ok') {
4386: &logthis('Could not devalidate spreadsheet '.
4387: $uname.' at '.$udom.' for '.
4388: $symb.': '.$status);
4389: }
4390: &delenv('user.state.'.$cid);
4391: }
4392: }
4393:
4394: sub get_scalar {
4395: my ($string,$end) = @_;
4396: my $value;
4397: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4398: $value = $1;
4399: } elsif ($$string =~ s/^([^&]*?)&//) {
4400: $value = $1;
4401: }
4402: return &unescape($value);
4403: }
4404:
4405: sub array2str {
4406: my (@array) = @_;
4407: my $result=&arrayref2str(\@array);
4408: $result=~s/^__ARRAY_REF__//;
4409: $result=~s/__END_ARRAY_REF__$//;
4410: return $result;
4411: }
4412:
4413: sub arrayref2str {
4414: my ($arrayref) = @_;
4415: my $result='__ARRAY_REF__';
4416: foreach my $elem (@$arrayref) {
4417: if(ref($elem) eq 'ARRAY') {
4418: $result.=&arrayref2str($elem).'&';
4419: } elsif(ref($elem) eq 'HASH') {
4420: $result.=&hashref2str($elem).'&';
4421: } elsif(ref($elem)) {
4422: #print("Got a ref of ".(ref($elem))." skipping.");
4423: } else {
4424: $result.=&escape($elem).'&';
4425: }
4426: }
4427: $result=~s/\&$//;
4428: $result .= '__END_ARRAY_REF__';
4429: return $result;
4430: }
4431:
4432: sub hash2str {
4433: my (%hash) = @_;
4434: my $result=&hashref2str(\%hash);
4435: $result=~s/^__HASH_REF__//;
4436: $result=~s/__END_HASH_REF__$//;
4437: return $result;
4438: }
4439:
4440: sub hashref2str {
4441: my ($hashref)=@_;
4442: my $result='__HASH_REF__';
4443: foreach my $key (sort(keys(%$hashref))) {
4444: if (ref($key) eq 'ARRAY') {
4445: $result.=&arrayref2str($key).'=';
4446: } elsif (ref($key) eq 'HASH') {
4447: $result.=&hashref2str($key).'=';
4448: } elsif (ref($key)) {
4449: $result.='=';
4450: #print("Got a ref of ".(ref($key))." skipping.");
4451: } else {
4452: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
4453: }
4454:
4455: if(ref($hashref->{$key}) eq 'ARRAY') {
4456: $result.=&arrayref2str($hashref->{$key}).'&';
4457: } elsif(ref($hashref->{$key}) eq 'HASH') {
4458: $result.=&hashref2str($hashref->{$key}).'&';
4459: } elsif(ref($hashref->{$key})) {
4460: $result.='&';
4461: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
4462: } else {
4463: $result.=&escape($hashref->{$key}).'&';
4464: }
4465: }
4466: $result=~s/\&$//;
4467: $result .= '__END_HASH_REF__';
4468: return $result;
4469: }
4470:
4471: sub str2hash {
4472: my ($string)=@_;
4473: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4474: return %$hash;
4475: }
4476:
4477: sub str2hashref {
4478: my ($string) = @_;
4479:
4480: my %hash;
4481:
4482: if($string !~ /^__HASH_REF__/) {
4483: if (! ($string eq '' || !defined($string))) {
4484: $hash{'error'}='Not hash reference';
4485: }
4486: return (\%hash, $string);
4487: }
4488:
4489: $string =~ s/^__HASH_REF__//;
4490:
4491: while($string !~ /^__END_HASH_REF__/) {
4492: #key
4493: my $key='';
4494: if($string =~ /^__HASH_REF__/) {
4495: ($key, $string)=&str2hashref($string);
4496: if(defined($key->{'error'})) {
4497: $hash{'error'}='Bad data';
4498: return (\%hash, $string);
4499: }
4500: } elsif($string =~ /^__ARRAY_REF__/) {
4501: ($key, $string)=&str2arrayref($string);
4502: if($key->[0] eq 'Array reference error') {
4503: $hash{'error'}='Bad data';
4504: return (\%hash, $string);
4505: }
4506: } else {
4507: $string =~ s/^(.*?)=//;
4508: $key=&unescape($1);
4509: }
4510: $string =~ s/^=//;
4511:
4512: #value
4513: my $value='';
4514: if($string =~ /^__HASH_REF__/) {
4515: ($value, $string)=&str2hashref($string);
4516: if(defined($value->{'error'})) {
4517: $hash{'error'}='Bad data';
4518: return (\%hash, $string);
4519: }
4520: } elsif($string =~ /^__ARRAY_REF__/) {
4521: ($value, $string)=&str2arrayref($string);
4522: if($value->[0] eq 'Array reference error') {
4523: $hash{'error'}='Bad data';
4524: return (\%hash, $string);
4525: }
4526: } else {
4527: $value=&get_scalar(\$string,'__END_HASH_REF__');
4528: }
4529: $string =~ s/^&//;
4530:
4531: $hash{$key}=$value;
4532: }
4533:
4534: $string =~ s/^__END_HASH_REF__//;
4535:
4536: return (\%hash, $string);
4537: }
4538:
4539: sub str2array {
4540: my ($string)=@_;
4541: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4542: return @$array;
4543: }
4544:
4545: sub str2arrayref {
4546: my ($string) = @_;
4547: my @array;
4548:
4549: if($string !~ /^__ARRAY_REF__/) {
4550: if (! ($string eq '' || !defined($string))) {
4551: $array[0]='Array reference error';
4552: }
4553: return (\@array, $string);
4554: }
4555:
4556: $string =~ s/^__ARRAY_REF__//;
4557:
4558: while($string !~ /^__END_ARRAY_REF__/) {
4559: my $value='';
4560: if($string =~ /^__HASH_REF__/) {
4561: ($value, $string)=&str2hashref($string);
4562: if(defined($value->{'error'})) {
4563: $array[0] ='Array reference error';
4564: return (\@array, $string);
4565: }
4566: } elsif($string =~ /^__ARRAY_REF__/) {
4567: ($value, $string)=&str2arrayref($string);
4568: if($value->[0] eq 'Array reference error') {
4569: $array[0] ='Array reference error';
4570: return (\@array, $string);
4571: }
4572: } else {
4573: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4574: }
4575: $string =~ s/^&//;
4576:
4577: push(@array, $value);
4578: }
4579:
4580: $string =~ s/^__END_ARRAY_REF__//;
4581:
4582: return (\@array, $string);
4583: }
4584:
4585: # -------------------------------------------------------------------Temp Store
4586:
4587: sub tmpreset {
4588: my ($symb,$namespace,$domain,$stuname) = @_;
4589: if (!$symb) {
4590: $symb=&symbread();
4591: if (!$symb) { $symb= $env{'request.url'}; }
4592: }
4593: $symb=escape($symb);
4594:
4595: if (!$namespace) { $namespace=$env{'request.state'}; }
4596: $namespace=~s/\//\_/g;
4597: $namespace=~s/\W//g;
4598:
4599: if (!$domain) { $domain=$env{'user.domain'}; }
4600: if (!$stuname) { $stuname=$env{'user.name'}; }
4601: if ($domain eq 'public' && $stuname eq 'public') {
4602: $stuname=$ENV{'REMOTE_ADDR'};
4603: }
4604: my $path=LONCAPA::tempdir();
4605: my %hash;
4606: if (tie(%hash,'GDBM_File',
4607: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4608: &GDBM_WRCREAT(),0640)) {
4609: foreach my $key (keys(%hash)) {
4610: if ($key=~ /:$symb/) {
4611: delete($hash{$key});
4612: }
4613: }
4614: }
4615: }
4616:
4617: sub tmpstore {
4618: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4619:
4620: if (!$symb) {
4621: $symb=&symbread();
4622: if (!$symb) { $symb= $env{'request.url'}; }
4623: }
4624: $symb=escape($symb);
4625:
4626: if (!$namespace) {
4627: # I don't think we would ever want to store this for a course.
4628: # it seems this will only be used if we don't have a course.
4629: #$namespace=$env{'request.course.id'};
4630: #if (!$namespace) {
4631: $namespace=$env{'request.state'};
4632: #}
4633: }
4634: $namespace=~s/\//\_/g;
4635: $namespace=~s/\W//g;
4636: if (!$domain) { $domain=$env{'user.domain'}; }
4637: if (!$stuname) { $stuname=$env{'user.name'}; }
4638: if ($domain eq 'public' && $stuname eq 'public') {
4639: $stuname=$ENV{'REMOTE_ADDR'};
4640: }
4641: my $now=time;
4642: my %hash;
4643: my $path=LONCAPA::tempdir();
4644: if (tie(%hash,'GDBM_File',
4645: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4646: &GDBM_WRCREAT(),0640)) {
4647: $hash{"version:$symb"}++;
4648: my $version=$hash{"version:$symb"};
4649: my $allkeys='';
4650: foreach my $key (keys(%$storehash)) {
4651: $allkeys.=$key.':';
4652: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
4653: }
4654: $hash{"$version:$symb:timestamp"}=$now;
4655: $allkeys.='timestamp';
4656: $hash{"$version:keys:$symb"}=$allkeys;
4657: if (untie(%hash)) {
4658: return 'ok';
4659: } else {
4660: return "error:$!";
4661: }
4662: } else {
4663: return "error:$!";
4664: }
4665: }
4666:
4667: # -----------------------------------------------------------------Temp Restore
4668:
4669: sub tmprestore {
4670: my ($symb,$namespace,$domain,$stuname) = @_;
4671:
4672: if (!$symb) {
4673: $symb=&symbread();
4674: if (!$symb) { $symb= $env{'request.url'}; }
4675: }
4676: $symb=escape($symb);
4677:
4678: if (!$namespace) { $namespace=$env{'request.state'}; }
4679:
4680: if (!$domain) { $domain=$env{'user.domain'}; }
4681: if (!$stuname) { $stuname=$env{'user.name'}; }
4682: if ($domain eq 'public' && $stuname eq 'public') {
4683: $stuname=$ENV{'REMOTE_ADDR'};
4684: }
4685: my %returnhash;
4686: $namespace=~s/\//\_/g;
4687: $namespace=~s/\W//g;
4688: my %hash;
4689: my $path=LONCAPA::tempdir();
4690: if (tie(%hash,'GDBM_File',
4691: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4692: &GDBM_READER(),0640)) {
4693: my $version=$hash{"version:$symb"};
4694: $returnhash{'version'}=$version;
4695: my $scope;
4696: for ($scope=1;$scope<=$version;$scope++) {
4697: my $vkeys=$hash{"$scope:keys:$symb"};
4698: my @keys=split(/:/,$vkeys);
4699: my $key;
4700: $returnhash{"$scope:keys"}=$vkeys;
4701: foreach $key (@keys) {
4702: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4703: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4704: }
4705: }
4706: if (!(untie(%hash))) {
4707: return "error:$!";
4708: }
4709: } else {
4710: return "error:$!";
4711: }
4712: return %returnhash;
4713: }
4714:
4715: # ----------------------------------------------------------------------- Store
4716:
4717: sub store {
4718: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4719: my $home='';
4720:
4721: if ($stuname) { $home=&homeserver($stuname,$domain); }
4722:
4723: $symb=&symbclean($symb);
4724: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4725:
4726: if (!$domain) { $domain=$env{'user.domain'}; }
4727: if (!$stuname) { $stuname=$env{'user.name'}; }
4728:
4729: &devalidate($symb,$stuname,$domain);
4730:
4731: $symb=escape($symb);
4732: if (!$namespace) {
4733: unless ($namespace=$env{'request.course.id'}) {
4734: return '';
4735: }
4736: }
4737: if (!$home) { $home=$env{'user.home'}; }
4738:
4739: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4740: $$storehash{'host'}=$perlvar{'lonHostID'};
4741:
4742: my $namevalue='';
4743: foreach my $key (keys(%$storehash)) {
4744: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4745: }
4746: $namevalue=~s/\&$//;
4747: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
4748: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4749: }
4750:
4751: # -------------------------------------------------------------- Critical Store
4752:
4753: sub cstore {
4754: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4755: my $home='';
4756:
4757: if ($stuname) { $home=&homeserver($stuname,$domain); }
4758:
4759: $symb=&symbclean($symb);
4760: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4761:
4762: if (!$domain) { $domain=$env{'user.domain'}; }
4763: if (!$stuname) { $stuname=$env{'user.name'}; }
4764:
4765: &devalidate($symb,$stuname,$domain);
4766:
4767: $symb=escape($symb);
4768: if (!$namespace) {
4769: unless ($namespace=$env{'request.course.id'}) {
4770: return '';
4771: }
4772: }
4773: if (!$home) { $home=$env{'user.home'}; }
4774:
4775: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4776: $$storehash{'host'}=$perlvar{'lonHostID'};
4777:
4778: my $namevalue='';
4779: foreach my $key (keys(%$storehash)) {
4780: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4781: }
4782: $namevalue=~s/\&$//;
4783: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
4784: return critical
4785: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4786: }
4787:
4788: # --------------------------------------------------------------------- Restore
4789:
4790: sub restore {
4791: my ($symb,$namespace,$domain,$stuname) = @_;
4792: my $home='';
4793:
4794: if ($stuname) { $home=&homeserver($stuname,$domain); }
4795:
4796: if (!$symb) {
4797: unless ($symb=escape(&symbread())) { return ''; }
4798: } else {
4799: $symb=&escape(&symbclean($symb));
4800: }
4801: if (!$namespace) {
4802: unless ($namespace=$env{'request.course.id'}) {
4803: return '';
4804: }
4805: }
4806: if (!$domain) { $domain=$env{'user.domain'}; }
4807: if (!$stuname) { $stuname=$env{'user.name'}; }
4808: if (!$home) { $home=$env{'user.home'}; }
4809: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4810:
4811: my %returnhash=();
4812: foreach my $line (split(/\&/,$answer)) {
4813: my ($name,$value)=split(/\=/,$line);
4814: $returnhash{&unescape($name)}=&thaw_unescape($value);
4815: }
4816: my $version;
4817: for ($version=1;$version<=$returnhash{'version'};$version++) {
4818: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4819: $returnhash{$item}=$returnhash{$version.':'.$item};
4820: }
4821: }
4822: return %returnhash;
4823: }
4824:
4825: # ---------------------------------------------------------- Course Description
4826: #
4827: #
4828:
4829: sub coursedescription {
4830: my ($courseid,$args)=@_;
4831: $courseid=~s/^\///;
4832: $courseid=~s/\_/\//g;
4833: my ($cdomain,$cnum)=split(/\//,$courseid);
4834: my $chome=&homeserver($cnum,$cdomain);
4835: my $normalid=$cdomain.'_'.$cnum;
4836: # need to always cache even if we get errors otherwise we keep
4837: # trying and trying and trying to get the course description.
4838: my %envhash=();
4839: my %returnhash=();
4840:
4841: my $expiretime=600;
4842: if ($env{'request.course.id'} eq $normalid) {
4843: $expiretime=120;
4844: }
4845:
4846: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4847: if (!$args->{'freshen_cache'}
4848: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4849: foreach my $key (keys(%env)) {
4850: next if ($key !~ /^\Q$prefix\E(.*)/);
4851: my ($setting) = $1;
4852: $returnhash{$setting} = $env{$key};
4853: }
4854: return %returnhash;
4855: }
4856:
4857: # get the data again
4858:
4859: if (!$args->{'one_time'}) {
4860: $envhash{'course.'.$normalid.'.last_cache'}=time;
4861: }
4862:
4863: if ($chome ne 'no_host') {
4864: %returnhash=&dump('environment',$cdomain,$cnum);
4865: if (!exists($returnhash{'con_lost'})) {
4866: my $username = $env{'user.name'}; # Defult username
4867: if(defined $args->{'user'}) {
4868: $username = $args->{'user'};
4869: }
4870: $returnhash{'home'}= $chome;
4871: $returnhash{'domain'} = $cdomain;
4872: $returnhash{'num'} = $cnum;
4873: if (!defined($returnhash{'type'})) {
4874: $returnhash{'type'} = 'Course';
4875: }
4876: while (my ($name,$value) = each %returnhash) {
4877: $envhash{'course.'.$normalid.'.'.$name}=$value;
4878: }
4879: $returnhash{'url'}=&clutter($returnhash{'url'});
4880: $returnhash{'fn'}=LONCAPA::tempdir() .
4881: $username.'_'.$cdomain.'_'.$cnum;
4882: $envhash{'course.'.$normalid.'.home'}=$chome;
4883: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4884: $envhash{'course.'.$normalid.'.num'}=$cnum;
4885: }
4886: }
4887: if (!$args->{'one_time'}) {
4888: &appenv(\%envhash);
4889: }
4890: return %returnhash;
4891: }
4892:
4893: sub update_released_required {
4894: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4895: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4896: $cid = $env{'request.course.id'};
4897: $cdom = $env{'course.'.$cid.'.domain'};
4898: $cnum = $env{'course.'.$cid.'.num'};
4899: $chome = $env{'course.'.$cid.'.home'};
4900: }
4901: if ($needsrelease) {
4902: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4903: my $needsupdate;
4904: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4905: $needsupdate = 1;
4906: } else {
4907: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4908: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4909: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4910: $needsupdate = 1;
4911: }
4912: }
4913: if ($needsupdate) {
4914: my %needshash = (
4915: 'internal.releaserequired' => $needsrelease,
4916: );
4917: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4918: if ($putresult eq 'ok') {
4919: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4920: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4921: if (ref($crsinfo{$cid}) eq 'HASH') {
4922: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4923: &courseidput($cdom,\%crsinfo,$chome,'notime');
4924: }
4925: }
4926: }
4927: }
4928: return;
4929: }
4930:
4931: # -------------------------------------------------See if a user is privileged
4932:
4933: sub privileged {
4934: my ($username,$domain,$possdomains,$possroles)=@_;
4935: my $now = time;
4936: my $roles;
4937: if (ref($possroles) eq 'ARRAY') {
4938: $roles = $possroles;
4939: } else {
4940: $roles = ['dc','su'];
4941: }
4942: if (ref($possdomains) eq 'ARRAY') {
4943: my %privileged = &privileged_by_domain($possdomains,$roles);
4944: foreach my $dom (@{$possdomains}) {
4945: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
4946: (ref($privileged{$dom}) eq 'HASH')) {
4947: foreach my $role (@{$roles}) {
4948: if (ref($privileged{$dom}{$role}) eq 'HASH') {
4949: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
4950: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
4951: return 1 unless (($end && $end < $now) ||
4952: ($start && $start > $now));
4953: }
4954: }
4955: }
4956: }
4957: }
4958: } else {
4959: my %rolesdump = &dump("roles", $domain, $username) or return 0;
4960: my $now = time;
4961:
4962: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
4963: my ($trole, $tend, $tstart) = split(/_/, $role);
4964: if (grep(/^\Q$trole\E$/,@{$roles})) {
4965: return 1 unless ($tend && $tend < $now)
4966: or ($tstart && $tstart > $now);
4967: }
4968: }
4969: }
4970: return 0;
4971: }
4972:
4973: sub privileged_by_domain {
4974: my ($domains,$roles) = @_;
4975: my %privileged = ();
4976: my $cachetime = 60*60*24;
4977: my $now = time;
4978: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
4979: return %privileged;
4980: }
4981: foreach my $dom (@{$domains}) {
4982: next if (ref($privileged{$dom}) eq 'HASH');
4983: my $needroles;
4984: foreach my $role (@{$roles}) {
4985: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
4986: if (defined($cached)) {
4987: if (ref($result) eq 'HASH') {
4988: $privileged{$dom}{$role} = $result;
4989: }
4990: } else {
4991: $needroles = 1;
4992: }
4993: }
4994: if ($needroles) {
4995: my %dompersonnel = &get_domain_roles($dom,$roles);
4996: $privileged{$dom} = {};
4997: foreach my $server (keys(%dompersonnel)) {
4998: if (ref($dompersonnel{$server}) eq 'HASH') {
4999: foreach my $item (keys(%{$dompersonnel{$server}})) {
5000: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5001: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5002: next if ($end && $end < $now);
5003: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5004: $dompersonnel{$server}{$item};
5005: }
5006: }
5007: }
5008: if (ref($privileged{$dom}) eq 'HASH') {
5009: foreach my $role (@{$roles}) {
5010: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5011: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5012: } else {
5013: my %hash = ();
5014: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5015: }
5016: }
5017: }
5018: }
5019: }
5020: return %privileged;
5021: }
5022:
5023: # -------------------------------------------------------- Get user privileges
5024:
5025: sub rolesinit {
5026: my ($domain, $username) = @_;
5027: my %userroles = ('user.login.time' => time);
5028: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5029:
5030: # firstaccess and timerinterval are related to timed maps/resources.
5031: # also, blocking can be triggered by an activating timer
5032: # it's saved in the user's %env.
5033: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5034: my %timerinterval = &dump('timerinterval', $domain, $username);
5035: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5036: %timerintchk, %timerintenv);
5037:
5038: foreach my $key (keys(%firstaccess)) {
5039: my ($cid, $rest) = split(/\0/, $key);
5040: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5041: }
5042:
5043: foreach my $key (keys(%timerinterval)) {
5044: my ($cid,$rest) = split(/\0/,$key);
5045: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5046: }
5047:
5048: my %allroles=();
5049: my %allgroups=();
5050:
5051: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5052: my $role = $rolesdump{$area};
5053: $area =~ s/\_\w\w$//;
5054:
5055: my ($trole, $tend, $tstart, $group_privs);
5056:
5057: if ($role =~ /^cr/) {
5058: # Custom role, defined by a user
5059: # e.g., user.role.cr/msu/smith/mynewrole
5060: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5061: $trole = $1;
5062: ($tend, $tstart) = split('_', $2);
5063: } else {
5064: $trole = $role;
5065: }
5066: } elsif ($role =~ m|^gr/|) {
5067: # Role of member in a group, defined within a course/community
5068: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5069: ($trole, $tend, $tstart) = split(/_/, $role);
5070: next if $tstart eq '-1';
5071: ($trole, $group_privs) = split(/\//, $trole);
5072: $group_privs = &unescape($group_privs);
5073: } else {
5074: # Just a normal role, defined in roles.tab
5075: ($trole, $tend, $tstart) = split(/_/,$role);
5076: }
5077:
5078: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5079: $username);
5080: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5081:
5082: # role expired or not available yet?
5083: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5084: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5085:
5086: next if $area eq '' or $trole eq '';
5087:
5088: my $spec = "$trole.$area";
5089: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5090:
5091: if ($trole =~ /^cr\//) {
5092: # Custom role, defined by a user
5093: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5094: } elsif ($trole eq 'gr') {
5095: # Role of a member in a group, defined within a course/community
5096: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5097: next;
5098: } else {
5099: # Normal role, defined in roles.tab
5100: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5101: }
5102:
5103: my $cid = $tdomain.'_'.$trest;
5104: unless ($firstaccchk{$cid}) {
5105: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5106: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5107: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5108: $coursetimerstarts{$cid}{$item};
5109: }
5110: }
5111: $firstaccchk{$cid} = 1;
5112: }
5113: unless ($timerintchk{$cid}) {
5114: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5115: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5116: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5117: $coursetimerintervals{$cid}{$item};
5118: }
5119: }
5120: $timerintchk{$cid} = 1;
5121: }
5122: }
5123:
5124: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5125: \%allroles, \%allgroups);
5126: $env{'user.adv'} = $userroles{'user.adv'};
5127:
5128: return (\%userroles,\%firstaccenv,\%timerintenv);
5129: }
5130:
5131: sub set_arearole {
5132: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5133: unless ($nolog) {
5134: # log the associated role with the area
5135: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5136: }
5137: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
5138: }
5139:
5140: sub custom_roleprivs {
5141: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5142: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
5143: my $homsvr=homeserver($rauthor,$rdomain);
5144: if (&hostname($homsvr) ne '') {
5145: my ($rdummy,$roledef)=
5146: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5147: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5148: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5149: if (defined($syspriv)) {
5150: if ($trest =~ /^$match_community$/) {
5151: $syspriv =~ s/bre\&S//;
5152: }
5153: $$allroles{'cm./'}.=':'.$syspriv;
5154: $$allroles{$spec.'./'}.=':'.$syspriv;
5155: }
5156: if ($tdomain ne '') {
5157: if (defined($dompriv)) {
5158: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5159: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5160: }
5161: if (($trest ne '') && (defined($coursepriv))) {
5162: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5163: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5164: }
5165: }
5166: }
5167: }
5168: }
5169:
5170: sub group_roleprivs {
5171: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5172: my $access = 1;
5173: my $now = time;
5174: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5175: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5176: if ($access) {
5177: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
5178: $$allgroups{$course}{$group} .=':'.$group_privs;
5179: }
5180: }
5181:
5182: sub standard_roleprivs {
5183: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5184: if (defined($pr{$trole.':s'})) {
5185: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5186: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5187: }
5188: if ($tdomain ne '') {
5189: if (defined($pr{$trole.':d'})) {
5190: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5191: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5192: }
5193: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5194: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5195: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5196: }
5197: }
5198: }
5199:
5200: sub set_userprivs {
5201: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
5202: my $author=0;
5203: my $adv=0;
5204: my %grouproles = ();
5205: if (keys(%{$allgroups}) > 0) {
5206: my @groupkeys;
5207: foreach my $role (keys(%{$allroles})) {
5208: push(@groupkeys,$role);
5209: }
5210: if (ref($groups_roles) eq 'HASH') {
5211: foreach my $key (keys(%{$groups_roles})) {
5212: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5213: push(@groupkeys,$key);
5214: }
5215: }
5216: }
5217: if (@groupkeys > 0) {
5218: foreach my $role (@groupkeys) {
5219: my ($trole,$area,$sec,$extendedarea);
5220: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5221: $trole = $1;
5222: $area = $2;
5223: $sec = $3;
5224: $extendedarea = $area.$sec;
5225: if (exists($$allgroups{$area})) {
5226: foreach my $group (keys(%{$$allgroups{$area}})) {
5227: my $spec = $trole.'.'.$extendedarea;
5228: $grouproles{$spec.'.'.$area.'/'.$group} =
5229: $$allgroups{$area}{$group};
5230: }
5231: }
5232: }
5233: }
5234: }
5235: }
5236: foreach my $group (keys(%grouproles)) {
5237: $$allroles{$group} = $grouproles{$group};
5238: }
5239: foreach my $role (keys(%{$allroles})) {
5240: my %thesepriv;
5241: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
5242: foreach my $item (split(/:/,$$allroles{$role})) {
5243: if ($item ne '') {
5244: my ($privilege,$restrictions)=split(/&/,$item);
5245: if ($restrictions eq '') {
5246: $thesepriv{$privilege}='F';
5247: } elsif ($thesepriv{$privilege} ne 'F') {
5248: $thesepriv{$privilege}.=$restrictions;
5249: }
5250: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5251: }
5252: }
5253: my $thesestr='';
5254: foreach my $priv (sort(keys(%thesepriv))) {
5255: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5256: }
5257: $userroles->{'user.priv.'.$role} = $thesestr;
5258: }
5259: return ($author,$adv);
5260: }
5261:
5262: sub role_status {
5263: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
5264: my @pwhere = ();
5265: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
5266: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
5267: unless (!defined($$role) || $$role eq '') {
5268: $$where=join('.',@pwhere);
5269: $$trolecode=$$role.'.'.$$where;
5270: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5271: $$tstatus='is';
5272: if ($$tstart && $$tstart>$update) {
5273: $$tstatus='future';
5274: if ($$tstart<$now) {
5275: if ($$tstart && $$tstart>$refresh) {
5276: if (($$where ne '') && ($$role ne '')) {
5277: my (%allroles,%allgroups,$group_privs,
5278: %groups_roles,@rolecodes);
5279: my %userroles = (
5280: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5281: );
5282: @rolecodes = ('cm');
5283: my $spec=$$role.'.'.$$where;
5284: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5285: if ($$role =~ /^cr\//) {
5286: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
5287: push(@rolecodes,'cr');
5288: } elsif ($$role eq 'gr') {
5289: push(@rolecodes,$$role);
5290: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5291: $env{'user.name'});
5292: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
5293: (undef,my $group_privs) = split(/\//,$trole);
5294: $group_privs = &unescape($group_privs);
5295: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
5296: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
5297: &get_groups_roles($tdomain,$trest,
5298: \%course_roles,\@rolecodes,
5299: \%groups_roles);
5300: } else {
5301: push(@rolecodes,$$role);
5302: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5303: }
5304: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5305: &appenv(\%userroles,\@rolecodes);
5306: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5307: }
5308: }
5309: $$tstatus = 'is';
5310: }
5311: }
5312: if ($$tend) {
5313: if ($$tend<$update) {
5314: $$tstatus='expired';
5315: } elsif ($$tend<$now) {
5316: $$tstatus='will_not';
5317: }
5318: }
5319: }
5320: }
5321: }
5322:
5323: sub get_groups_roles {
5324: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5325: return unless((ref($cdom_courseroles) eq 'HASH') &&
5326: (ref($rolecodes) eq 'ARRAY') &&
5327: (ref($groups_roles) eq 'HASH'));
5328: if (keys(%{$cdom_courseroles}) > 0) {
5329: my ($cnum) = ($rest =~ /^($match_courseid)/);
5330: if ($cdom ne '' && $cnum ne '') {
5331: foreach my $key (keys(%{$cdom_courseroles})) {
5332: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5333: my $crsrole = $1;
5334: my $crssec = $2;
5335: if ($crsrole =~ /^cr/) {
5336: unless (grep(/^cr$/,@{$rolecodes})) {
5337: push(@{$rolecodes},'cr');
5338: }
5339: } else {
5340: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5341: push(@{$rolecodes},$crsrole);
5342: }
5343: }
5344: my $rolekey = "$crsrole./$cdom/$cnum";
5345: if ($crssec ne '') {
5346: $rolekey .= "/$crssec";
5347: }
5348: $rolekey .= './';
5349: $groups_roles->{$rolekey} = $rolecodes;
5350: }
5351: }
5352: }
5353: }
5354: return;
5355: }
5356:
5357: sub delete_env_groupprivs {
5358: my ($where,$courseroles,$possroles) = @_;
5359: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5360: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5361: unless (ref($courseroles->{$udom}) eq 'HASH') {
5362: %{$courseroles->{$udom}} =
5363: &get_my_roles('','','userroles',['active'],
5364: $possroles,[$udom],1);
5365: }
5366: if (ref($courseroles->{$udom}) eq 'HASH') {
5367: foreach my $item (keys(%{$courseroles->{$udom}})) {
5368: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5369: my $area = '/'.$cdom.'/'.$cnum;
5370: my $privkey = "user.priv.$crsrole.$area";
5371: if ($crssec ne '') {
5372: $privkey .= '/'.$crssec;
5373: }
5374: $privkey .= ".$area/$group";
5375: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5376: }
5377: }
5378: return;
5379: }
5380:
5381: sub check_adhoc_privs {
5382: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
5383: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
5384: my $setprivs;
5385: if ($env{$cckey}) {
5386: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
5387: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
5388: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
5389: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
5390: $setprivs = 1;
5391: }
5392: } else {
5393: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
5394: $setprivs = 1;
5395: }
5396: return $setprivs;
5397: }
5398:
5399: sub set_adhoc_privileges {
5400: # role can be cc or ca
5401: my ($dcdom,$pickedcourse,$role,$caller) = @_;
5402: my $area = '/'.$dcdom.'/'.$pickedcourse;
5403: my $spec = $role.'.'.$area;
5404: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
5405: $env{'user.name'},1);
5406: my %ccrole = ();
5407: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5408: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5409: &appenv(\%userroles,[$role,'cm']);
5410: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5411: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5412: &appenv( {'request.role' => $spec,
5413: 'request.role.domain' => $dcdom,
5414: 'request.course.sec' => ''
5415: }
5416: );
5417: my $tadv=0;
5418: if (&allowed('adv') eq 'F') { $tadv=1; }
5419: &appenv({'request.role.adv' => $tadv});
5420: }
5421: }
5422:
5423: # --------------------------------------------------------------- get interface
5424:
5425: sub get {
5426: my ($namespace,$storearr,$udomain,$uname)=@_;
5427: my $items='';
5428: foreach my $item (@$storearr) {
5429: $items.=&escape($item).'&';
5430: }
5431: $items=~s/\&$//;
5432: if (!$udomain) { $udomain=$env{'user.domain'}; }
5433: if (!$uname) { $uname=$env{'user.name'}; }
5434: my $uhome=&homeserver($uname,$udomain);
5435:
5436: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
5437: my @pairs=split(/\&/,$rep);
5438: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5439: return @pairs;
5440: }
5441: my %returnhash=();
5442: my $i=0;
5443: foreach my $item (@$storearr) {
5444: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5445: $i++;
5446: }
5447: return %returnhash;
5448: }
5449:
5450: # --------------------------------------------------------------- del interface
5451:
5452: sub del {
5453: my ($namespace,$storearr,$udomain,$uname)=@_;
5454: my $items='';
5455: foreach my $item (@$storearr) {
5456: $items.=&escape($item).'&';
5457: }
5458:
5459: $items=~s/\&$//;
5460: if (!$udomain) { $udomain=$env{'user.domain'}; }
5461: if (!$uname) { $uname=$env{'user.name'}; }
5462: my $uhome=&homeserver($uname,$udomain);
5463: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
5464: }
5465:
5466: # -------------------------------------------------------------- dump interface
5467:
5468: sub unserialize {
5469: my ($rep, $escapedkeys) = @_;
5470:
5471: return {} if $rep =~ /^error/;
5472:
5473: my %returnhash=();
5474: foreach my $item (split /\&/, $rep) {
5475: my ($key, $value) = split(/=/, $item, 2);
5476: $key = unescape($key) unless $escapedkeys;
5477: next if $key =~ /^error: 2 /;
5478: $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
5479: }
5480: #return %returnhash;
5481: return \%returnhash;
5482: }
5483:
5484: # see Lond::dump_with_regexp
5485: # if $escapedkeys hash keys won't get unescaped.
5486: sub dump {
5487: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
5488: if (!$udomain) { $udomain=$env{'user.domain'}; }
5489: if (!$uname) { $uname=$env{'user.name'}; }
5490: my $uhome=&homeserver($uname,$udomain);
5491:
5492: my $reply;
5493: if (grep { $_ eq $uhome } current_machine_ids()) {
5494: # user is hosted on this machine
5495: $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
5496: $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
5497: return %{unserialize($reply, $escapedkeys)};
5498: }
5499: if ($regexp) {
5500: $regexp=&escape($regexp);
5501: } else {
5502: $regexp='.';
5503: }
5504: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5505: my @pairs=split(/\&/,$rep);
5506: my %returnhash=();
5507: if (!($rep =~ /^error/ )) {
5508: foreach my $item (@pairs) {
5509: my ($key,$value)=split(/=/,$item,2);
5510: $key = unescape($key) unless $escapedkeys;
5511: #$key = &unescape($key);
5512: next if ($key =~ /^error: 2 /);
5513: $returnhash{$key}=&thaw_unescape($value);
5514: }
5515: }
5516: return %returnhash;
5517: }
5518:
5519:
5520: # --------------------------------------------------------- dumpstore interface
5521:
5522: sub dumpstore {
5523: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
5524: # same as dump but keys must be escaped. They may contain colon separated
5525: # lists of values that may themself contain colons (e.g. symbs).
5526: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
5527: }
5528:
5529: # -------------------------------------------------------------- keys interface
5530:
5531: sub getkeys {
5532: my ($namespace,$udomain,$uname)=@_;
5533: if (!$udomain) { $udomain=$env{'user.domain'}; }
5534: if (!$uname) { $uname=$env{'user.name'}; }
5535: my $uhome=&homeserver($uname,$udomain);
5536: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5537: my @keyarray=();
5538: foreach my $key (split(/\&/,$rep)) {
5539: next if ($key =~ /^error: 2 /);
5540: push(@keyarray,&unescape($key));
5541: }
5542: return @keyarray;
5543: }
5544:
5545: # --------------------------------------------------------------- currentdump
5546: sub currentdump {
5547: my ($courseid,$sdom,$sname)=@_;
5548: $courseid = $env{'request.course.id'} if (! defined($courseid));
5549: $sdom = $env{'user.domain'} if (! defined($sdom));
5550: $sname = $env{'user.name'} if (! defined($sname));
5551: my $uhome = &homeserver($sname,$sdom);
5552: my $rep;
5553:
5554: if (grep { $_ eq $uhome } current_machine_ids()) {
5555: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5556: $courseid)));
5557: } else {
5558: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5559: }
5560:
5561: return if ($rep =~ /^(error:|no_such_host)/);
5562: #
5563: my %returnhash=();
5564: #
5565: if ($rep eq "unknown_cmd") {
5566: # an old lond will not know currentdump
5567: # Do a dump and make it look like a currentdump
5568: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
5569: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5570: my %hash = @tmp;
5571: @tmp=();
5572: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
5573: } else {
5574: my @pairs=split(/\&/,$rep);
5575: foreach my $pair (@pairs) {
5576: my ($key,$value)=split(/=/,$pair,2);
5577: my ($symb,$param) = split(/:/,$key);
5578: $returnhash{&unescape($symb)}->{&unescape($param)} =
5579: &thaw_unescape($value);
5580: }
5581: }
5582: return %returnhash;
5583: }
5584:
5585: sub convert_dump_to_currentdump{
5586: my %hash = %{shift()};
5587: my %returnhash;
5588: # Code ripped from lond, essentially. The only difference
5589: # here is the unescaping done by lonnet::dump(). Conceivably
5590: # we might run in to problems with parameter names =~ /^v\./
5591: while (my ($key,$value) = each(%hash)) {
5592: my ($v,$symb,$param) = split(/:/,$key);
5593: $symb = &unescape($symb);
5594: $param = &unescape($param);
5595: next if ($v eq 'version' || $symb eq 'keys');
5596: next if (exists($returnhash{$symb}) &&
5597: exists($returnhash{$symb}->{$param}) &&
5598: $returnhash{$symb}->{'v.'.$param} > $v);
5599: $returnhash{$symb}->{$param}=$value;
5600: $returnhash{$symb}->{'v.'.$param}=$v;
5601: }
5602: #
5603: # Remove all of the keys in the hashes which keep track of
5604: # the version of the parameter.
5605: while (my ($symb,$param_hash) = each(%returnhash)) {
5606: # use a foreach because we are going to delete from the hash.
5607: foreach my $key (keys(%$param_hash)) {
5608: delete($param_hash->{$key}) if ($key =~ /^v\./);
5609: }
5610: }
5611: return \%returnhash;
5612: }
5613:
5614: # ------------------------------------------------------ critical inc interface
5615:
5616: sub cinc {
5617: return &inc(@_,'critical');
5618: }
5619:
5620: # --------------------------------------------------------------- inc interface
5621:
5622: sub inc {
5623: my ($namespace,$store,$udomain,$uname,$critical) = @_;
5624: if (!$udomain) { $udomain=$env{'user.domain'}; }
5625: if (!$uname) { $uname=$env{'user.name'}; }
5626: my $uhome=&homeserver($uname,$udomain);
5627: my $items='';
5628: if (! ref($store)) {
5629: # got a single value, so use that instead
5630: $items = &escape($store).'=&';
5631: } elsif (ref($store) eq 'SCALAR') {
5632: $items = &escape($$store).'=&';
5633: } elsif (ref($store) eq 'ARRAY') {
5634: $items = join('=&',map {&escape($_);} @{$store});
5635: } elsif (ref($store) eq 'HASH') {
5636: while (my($key,$value) = each(%{$store})) {
5637: $items.= &escape($key).'='.&escape($value).'&';
5638: }
5639: }
5640: $items=~s/\&$//;
5641: if ($critical) {
5642: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5643: } else {
5644: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5645: }
5646: }
5647:
5648: # --------------------------------------------------------------- put interface
5649:
5650: sub put {
5651: my ($namespace,$storehash,$udomain,$uname)=@_;
5652: if (!$udomain) { $udomain=$env{'user.domain'}; }
5653: if (!$uname) { $uname=$env{'user.name'}; }
5654: my $uhome=&homeserver($uname,$udomain);
5655: my $items='';
5656: foreach my $item (keys(%$storehash)) {
5657: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5658: }
5659: $items=~s/\&$//;
5660: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5661: }
5662:
5663: # ------------------------------------------------------------ newput interface
5664:
5665: sub newput {
5666: my ($namespace,$storehash,$udomain,$uname)=@_;
5667: if (!$udomain) { $udomain=$env{'user.domain'}; }
5668: if (!$uname) { $uname=$env{'user.name'}; }
5669: my $uhome=&homeserver($uname,$udomain);
5670: my $items='';
5671: foreach my $key (keys(%$storehash)) {
5672: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5673: }
5674: $items=~s/\&$//;
5675: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5676: }
5677:
5678: # --------------------------------------------------------- putstore interface
5679:
5680: sub putstore {
5681: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5682: if (!$udomain) { $udomain=$env{'user.domain'}; }
5683: if (!$uname) { $uname=$env{'user.name'}; }
5684: my $uhome=&homeserver($uname,$udomain);
5685: my $items='';
5686: foreach my $key (keys(%$storehash)) {
5687: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5688: }
5689: $items=~s/\&$//;
5690: my $esc_symb=&escape($symb);
5691: my $esc_v=&escape($version);
5692: my $reply =
5693: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
5694: $uhome);
5695: if ($reply eq 'unknown_cmd') {
5696: # gfall back to way things use to be done
5697: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5698: $uname);
5699: }
5700: return $reply;
5701: }
5702:
5703: sub old_putstore {
5704: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5705: if (!$udomain) { $udomain=$env{'user.domain'}; }
5706: if (!$uname) { $uname=$env{'user.name'}; }
5707: my $uhome=&homeserver($uname,$udomain);
5708: my %newstorehash;
5709: foreach my $item (keys(%$storehash)) {
5710: my $key = $version.':'.&escape($symb).':'.$item;
5711: $newstorehash{$key} = $storehash->{$item};
5712: }
5713: my $items='';
5714: my %allitems = ();
5715: foreach my $item (keys(%newstorehash)) {
5716: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
5717: my $key = $1.':keys:'.$2;
5718: $allitems{$key} .= $3.':';
5719: }
5720: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
5721: }
5722: foreach my $item (keys(%allitems)) {
5723: $allitems{$item} =~ s/\:$//;
5724: $items.= $item.'='.$allitems{$item}.'&';
5725: }
5726: $items=~s/\&$//;
5727: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5728: }
5729:
5730: # ------------------------------------------------------ critical put interface
5731:
5732: sub cput {
5733: my ($namespace,$storehash,$udomain,$uname)=@_;
5734: if (!$udomain) { $udomain=$env{'user.domain'}; }
5735: if (!$uname) { $uname=$env{'user.name'}; }
5736: my $uhome=&homeserver($uname,$udomain);
5737: my $items='';
5738: foreach my $item (keys(%$storehash)) {
5739: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5740: }
5741: $items=~s/\&$//;
5742: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
5743: }
5744:
5745: # -------------------------------------------------------------- eget interface
5746:
5747: sub eget {
5748: my ($namespace,$storearr,$udomain,$uname)=@_;
5749: my $items='';
5750: foreach my $item (@$storearr) {
5751: $items.=&escape($item).'&';
5752: }
5753: $items=~s/\&$//;
5754: if (!$udomain) { $udomain=$env{'user.domain'}; }
5755: if (!$uname) { $uname=$env{'user.name'}; }
5756: my $uhome=&homeserver($uname,$udomain);
5757: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
5758: my @pairs=split(/\&/,$rep);
5759: my %returnhash=();
5760: my $i=0;
5761: foreach my $item (@$storearr) {
5762: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5763: $i++;
5764: }
5765: return %returnhash;
5766: }
5767:
5768: # ------------------------------------------------------------ tmpput interface
5769: sub tmpput {
5770: my ($storehash,$server,$context)=@_;
5771: my $items='';
5772: foreach my $item (keys(%$storehash)) {
5773: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5774: }
5775: $items=~s/\&$//;
5776: if (defined($context)) {
5777: $items .= ':'.&escape($context);
5778: }
5779: return &reply("tmpput:$items",$server);
5780: }
5781:
5782: # ------------------------------------------------------------ tmpget interface
5783: sub tmpget {
5784: my ($token,$server)=@_;
5785: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5786: my $rep=&reply("tmpget:$token",$server);
5787: my %returnhash;
5788: foreach my $item (split(/\&/,$rep)) {
5789: my ($key,$value)=split(/=/,$item);
5790: next if ($key =~ /^error: 2 /);
5791: $returnhash{&unescape($key)}=&thaw_unescape($value);
5792: }
5793: return %returnhash;
5794: }
5795:
5796: # ------------------------------------------------------------ tmpdel interface
5797: sub tmpdel {
5798: my ($token,$server)=@_;
5799: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5800: return &reply("tmpdel:$token",$server);
5801: }
5802:
5803: # ------------------------------------------------------------ get_timebased_id
5804:
5805: sub get_timebased_id {
5806: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5807: $maxtries) = @_;
5808: my ($newid,$error,$dellock);
5809: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5810: return ('','ok','invalid call to get suffix');
5811: }
5812:
5813: # set defaults for any optional args for which values were not supplied
5814: if ($who eq '') {
5815: $who = $env{'user.name'}.':'.$env{'user.domain'};
5816: }
5817: if (!$locktries) {
5818: $locktries = 3;
5819: }
5820: if (!$maxtries) {
5821: $maxtries = 10;
5822: }
5823:
5824: if (($cdom eq '') || ($cnum eq '')) {
5825: if ($env{'request.course.id'}) {
5826: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5827: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5828: }
5829: if (($cdom eq '') || ($cnum eq '')) {
5830: return ('','ok','call to get suffix not in course context');
5831: }
5832: }
5833:
5834: # construct locking item
5835: my $lockhash = {
5836: $prefix."\0".'locked_'.$keyid => $who,
5837: };
5838: my $tries = 0;
5839:
5840: # attempt to get lock on nohist_$namespace file
5841: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5842: while (($gotlock ne 'ok') && $tries <$locktries) {
5843: $tries ++;
5844: sleep 1;
5845: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5846: }
5847:
5848: # attempt to get unique identifier, based on current timestamp
5849: if ($gotlock eq 'ok') {
5850: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5851: my $id = time;
5852: $newid = $id;
5853: my $idtries = 0;
5854: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5855: if ($idtype eq 'concat') {
5856: $newid = $id.$idtries;
5857: } else {
5858: $newid ++;
5859: }
5860: $idtries ++;
5861: }
5862: if (!exists($inuse{$prefix."\0".$newid})) {
5863: my %new_item = (
5864: $prefix."\0".$newid => $who,
5865: );
5866: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
5867: $cdom,$cnum);
5868: if ($putresult ne 'ok') {
5869: undef($newid);
5870: $error = 'error saving new item: '.$putresult;
5871: }
5872: } else {
5873: $error = ('error: no unique suffix available for the new item ');
5874: }
5875: # remove lock
5876: my @del_lock = ($prefix."\0".'locked_'.$keyid);
5877: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
5878: } else {
5879: $error = "error: could not obtain lockfile\n";
5880: $dellock = 'ok';
5881: }
5882: return ($newid,$dellock,$error);
5883: }
5884:
5885: # -------------------------------------------------- portfolio access checking
5886:
5887: sub portfolio_access {
5888: my ($requrl) = @_;
5889: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5890: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
5891: if ($result) {
5892: my %setters;
5893: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5894: my ($startblock,$endblock) =
5895: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5896: if ($startblock && $endblock) {
5897: return 'B';
5898: }
5899: } else {
5900: my ($startblock,$endblock) =
5901: &Apache::loncommon::blockcheck(\%setters,'port');
5902: if ($startblock && $endblock) {
5903: return 'B';
5904: }
5905: }
5906: }
5907: if ($result eq 'ok') {
5908: return 'F';
5909: } elsif ($result =~ /^[^:]+:guest_/) {
5910: return 'A';
5911: }
5912: return '';
5913: }
5914:
5915: sub get_portfolio_access {
5916: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5917:
5918: if (!ref($access_hash)) {
5919: my $current_perms = &get_portfile_permissions($udom,$unum);
5920: my %access_controls = &get_access_controls($current_perms,$group,
5921: $file_name);
5922: $access_hash = $access_controls{$file_name};
5923: }
5924:
5925: my ($public,$guest,@domains,@users,@courses,@groups);
5926: my $now = time;
5927: if (ref($access_hash) eq 'HASH') {
5928: foreach my $key (keys(%{$access_hash})) {
5929: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5930: if ($start > $now) {
5931: next;
5932: }
5933: if ($end && $end<$now) {
5934: next;
5935: }
5936: if ($scope eq 'public') {
5937: $public = $key;
5938: last;
5939: } elsif ($scope eq 'guest') {
5940: $guest = $key;
5941: } elsif ($scope eq 'domains') {
5942: push(@domains,$key);
5943: } elsif ($scope eq 'users') {
5944: push(@users,$key);
5945: } elsif ($scope eq 'course') {
5946: push(@courses,$key);
5947: } elsif ($scope eq 'group') {
5948: push(@groups,$key);
5949: }
5950: }
5951: if ($public) {
5952: return 'ok';
5953: }
5954: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5955: if ($guest) {
5956: return $guest;
5957: }
5958: } else {
5959: if (@domains > 0) {
5960: foreach my $domkey (@domains) {
5961: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5962: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5963: return 'ok';
5964: }
5965: }
5966: }
5967: }
5968: if (@users > 0) {
5969: foreach my $userkey (@users) {
5970: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5971: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5972: if (ref($item) eq 'HASH') {
5973: if (($item->{'uname'} eq $env{'user.name'}) &&
5974: ($item->{'udom'} eq $env{'user.domain'})) {
5975: return 'ok';
5976: }
5977: }
5978: }
5979: }
5980: }
5981: }
5982: my %roleshash;
5983: my @courses_and_groups = @courses;
5984: push(@courses_and_groups,@groups);
5985: if (@courses_and_groups > 0) {
5986: my (%allgroups,%allroles);
5987: my ($start,$end,$role,$sec,$group);
5988: foreach my $envkey (%env) {
5989: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
5990: my $cid = $2.'_'.$3;
5991: if ($1 eq 'gr') {
5992: $group = $4;
5993: $allgroups{$cid}{$group} = $env{$envkey};
5994: } else {
5995: if ($4 eq '') {
5996: $sec = 'none';
5997: } else {
5998: $sec = $4;
5999: }
6000: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6001: }
6002: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
6003: my $cid = $2.'_'.$3;
6004: if ($4 eq '') {
6005: $sec = 'none';
6006: } else {
6007: $sec = $4;
6008: }
6009: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6010: }
6011: }
6012: if (keys(%allroles) == 0) {
6013: return;
6014: }
6015: foreach my $key (@courses_and_groups) {
6016: my %content = %{$$access_hash{$key}};
6017: my $cnum = $content{'number'};
6018: my $cdom = $content{'domain'};
6019: my $cid = $cdom.'_'.$cnum;
6020: if (!exists($allroles{$cid})) {
6021: next;
6022: }
6023: foreach my $role_id (keys(%{$content{'roles'}})) {
6024: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6025: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6026: my @status = @{$content{'roles'}{$role_id}{'access'}};
6027: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6028: foreach my $role (keys(%{$allroles{$cid}})) {
6029: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6030: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6031: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6032: if (grep/^all$/,@sections) {
6033: return 'ok';
6034: } else {
6035: if (grep/^$sec$/,@sections) {
6036: return 'ok';
6037: }
6038: }
6039: }
6040: }
6041: if (keys(%{$allgroups{$cid}}) == 0) {
6042: if (grep/^none$/,@groups) {
6043: return 'ok';
6044: }
6045: } else {
6046: if (grep/^all$/,@groups) {
6047: return 'ok';
6048: }
6049: foreach my $group (keys(%{$allgroups{$cid}})) {
6050: if (grep/^$group$/,@groups) {
6051: return 'ok';
6052: }
6053: }
6054: }
6055: }
6056: }
6057: }
6058: }
6059: }
6060: if ($guest) {
6061: return $guest;
6062: }
6063: }
6064: }
6065: return;
6066: }
6067:
6068: sub course_group_datechecker {
6069: my ($dates,$now,$status) = @_;
6070: my ($start,$end) = split(/\./,$dates);
6071: if (!$start && !$end) {
6072: return 'ok';
6073: }
6074: if (grep/^active$/,@{$status}) {
6075: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6076: return 'ok';
6077: }
6078: }
6079: if (grep/^previous$/,@{$status}) {
6080: if ($end > $now ) {
6081: return 'ok';
6082: }
6083: }
6084: if (grep/^future$/,@{$status}) {
6085: if ($start > $now) {
6086: return 'ok';
6087: }
6088: }
6089: return;
6090: }
6091:
6092: sub parse_portfolio_url {
6093: my ($url) = @_;
6094:
6095: my ($type,$udom,$unum,$group,$file_name);
6096:
6097: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
6098: $type = 1;
6099: $udom = $1;
6100: $unum = $2;
6101: $file_name = $3;
6102: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
6103: $type = 2;
6104: $udom = $1;
6105: $unum = $2;
6106: $group = $3;
6107: $file_name = $3.'/'.$4;
6108: }
6109: if (wantarray) {
6110: return ($type,$udom,$unum,$file_name,$group);
6111: }
6112: return $type;
6113: }
6114:
6115: sub is_portfolio_url {
6116: my ($url) = @_;
6117: return scalar(&parse_portfolio_url($url));
6118: }
6119:
6120: sub is_portfolio_file {
6121: my ($file) = @_;
6122: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
6123: return 1;
6124: }
6125: return;
6126: }
6127:
6128: sub usertools_access {
6129: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
6130: my ($access,%tools);
6131: if ($context eq '') {
6132: $context = 'tools';
6133: }
6134: if ($context eq 'requestcourses') {
6135: %tools = (
6136: official => 1,
6137: unofficial => 1,
6138: community => 1,
6139: );
6140: } elsif ($context eq 'requestauthor') {
6141: %tools = (
6142: requestauthor => 1,
6143: );
6144: } else {
6145: %tools = (
6146: aboutme => 1,
6147: blog => 1,
6148: webdav => 1,
6149: portfolio => 1,
6150: );
6151: }
6152: return if (!defined($tools{$tool}));
6153:
6154: if ((!defined($udom)) || (!defined($uname))) {
6155: $udom = $env{'user.domain'};
6156: $uname = $env{'user.name'};
6157: }
6158:
6159: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6160: if ($action ne 'reload') {
6161: if ($context eq 'requestcourses') {
6162: return $env{'environment.canrequest.'.$tool};
6163: } elsif ($context eq 'requestauthor') {
6164: return $env{'environment.canrequest.author'};
6165: } else {
6166: return $env{'environment.availabletools.'.$tool};
6167: }
6168: }
6169: }
6170:
6171: my ($toolstatus,$inststatus,$envkey);
6172: if ($context eq 'requestauthor') {
6173: $envkey = $context;
6174: } else {
6175: $envkey = $context.'.'.$tool;
6176: }
6177:
6178: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6179: ($action ne 'reload')) {
6180: $toolstatus = $env{'environment.'.$envkey};
6181: $inststatus = $env{'environment.inststatus'};
6182: } else {
6183: if (ref($userenvref) eq 'HASH') {
6184: $toolstatus = $userenvref->{$envkey};
6185: $inststatus = $userenvref->{'inststatus'};
6186: } else {
6187: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6188: $toolstatus = $userenv{$envkey};
6189: $inststatus = $userenv{'inststatus'};
6190: }
6191: }
6192:
6193: if ($toolstatus ne '') {
6194: if ($toolstatus) {
6195: $access = 1;
6196: } else {
6197: $access = 0;
6198: }
6199: return $access;
6200: }
6201:
6202: my ($is_adv,%domdef);
6203: if (ref($is_advref) eq 'HASH') {
6204: $is_adv = $is_advref->{'is_adv'};
6205: } else {
6206: $is_adv = &is_advanced_user($udom,$uname);
6207: }
6208: if (ref($domdefref) eq 'HASH') {
6209: %domdef = %{$domdefref};
6210: } else {
6211: %domdef = &get_domain_defaults($udom);
6212: }
6213: if (ref($domdef{$tool}) eq 'HASH') {
6214: if ($is_adv) {
6215: if ($domdef{$tool}{'_LC_adv'} ne '') {
6216: if ($domdef{$tool}{'_LC_adv'}) {
6217: $access = 1;
6218: } else {
6219: $access = 0;
6220: }
6221: return $access;
6222: }
6223: }
6224: if ($inststatus ne '') {
6225: my ($hasaccess,$hasnoaccess);
6226: foreach my $affiliation (split(/:/,$inststatus)) {
6227: if ($domdef{$tool}{$affiliation} ne '') {
6228: if ($domdef{$tool}{$affiliation}) {
6229: $hasaccess = 1;
6230: } else {
6231: $hasnoaccess = 1;
6232: }
6233: }
6234: }
6235: if ($hasaccess || $hasnoaccess) {
6236: if ($hasaccess) {
6237: $access = 1;
6238: } elsif ($hasnoaccess) {
6239: $access = 0;
6240: }
6241: return $access;
6242: }
6243: } else {
6244: if ($domdef{$tool}{'default'} ne '') {
6245: if ($domdef{$tool}{'default'}) {
6246: $access = 1;
6247: } elsif ($domdef{$tool}{'default'} == 0) {
6248: $access = 0;
6249: }
6250: return $access;
6251: }
6252: }
6253: } else {
6254: if (($context eq 'tools') && ($tool ne 'webdav')) {
6255: $access = 1;
6256: } else {
6257: $access = 0;
6258: }
6259: return $access;
6260: }
6261: }
6262:
6263: sub is_course_owner {
6264: my ($cdom,$cnum,$udom,$uname) = @_;
6265: if (($udom eq '') || ($uname eq '')) {
6266: $udom = $env{'user.domain'};
6267: $uname = $env{'user.name'};
6268: }
6269: unless (($udom eq '') || ($uname eq '')) {
6270: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6271: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6272: return 1;
6273: } else {
6274: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6275: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6276: return 1;
6277: }
6278: }
6279: }
6280: }
6281: return;
6282: }
6283:
6284: sub is_advanced_user {
6285: my ($udom,$uname) = @_;
6286: if ($udom ne '' && $uname ne '') {
6287: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6288: if (wantarray) {
6289: return ($env{'user.adv'},$env{'user.author'});
6290: } else {
6291: return $env{'user.adv'};
6292: }
6293: }
6294: }
6295: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6296: my %allroles;
6297: my ($is_adv,$is_author);
6298: foreach my $role (keys(%roleshash)) {
6299: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6300: my $area = '/'.$tdomain.'/'.$trest;
6301: if ($sec ne '') {
6302: $area .= '/'.$sec;
6303: }
6304: if (($area ne '') && ($trole ne '')) {
6305: my $spec=$trole.'.'.$area;
6306: if ($trole =~ /^cr\//) {
6307: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6308: } elsif ($trole ne 'gr') {
6309: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6310: }
6311: if ($trole eq 'au') {
6312: $is_author = 1;
6313: }
6314: }
6315: }
6316: foreach my $role (keys(%allroles)) {
6317: last if ($is_adv);
6318: foreach my $item (split(/:/,$allroles{$role})) {
6319: if ($item ne '') {
6320: my ($privilege,$restrictions)=split(/&/,$item);
6321: if ($privilege eq 'adv') {
6322: $is_adv = 1;
6323: last;
6324: }
6325: }
6326: }
6327: }
6328: if (wantarray) {
6329: return ($is_adv,$is_author);
6330: }
6331: return $is_adv;
6332: }
6333:
6334: sub check_can_request {
6335: my ($dom,$can_request,$request_domains) = @_;
6336: my $canreq = 0;
6337: my ($types,$typename) = &Apache::loncommon::course_types();
6338: my @options = ('approval','validate','autolimit');
6339: my $optregex = join('|',@options);
6340: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6341: foreach my $type (@{$types}) {
6342: if (&usertools_access($env{'user.name'},
6343: $env{'user.domain'},
6344: $type,undef,'requestcourses')) {
6345: $canreq ++;
6346: if (ref($request_domains) eq 'HASH') {
6347: push(@{$request_domains->{$type}},$env{'user.domain'});
6348: }
6349: if ($dom eq $env{'user.domain'}) {
6350: $can_request->{$type} = 1;
6351: }
6352: }
6353: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6354: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6355: if (@curr > 0) {
6356: foreach my $item (@curr) {
6357: if (ref($request_domains) eq 'HASH') {
6358: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6359: if ($otherdom ne '') {
6360: if (ref($request_domains->{$type}) eq 'ARRAY') {
6361: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6362: push(@{$request_domains->{$type}},$otherdom);
6363: }
6364: } else {
6365: push(@{$request_domains->{$type}},$otherdom);
6366: }
6367: }
6368: }
6369: }
6370: unless($dom eq $env{'user.domain'}) {
6371: $canreq ++;
6372: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6373: $can_request->{$type} = 1;
6374: }
6375: }
6376: }
6377: }
6378: }
6379: }
6380: return $canreq;
6381: }
6382:
6383: # ---------------------------------------------- Custom access rule evaluation
6384:
6385: sub customaccess {
6386: my ($priv,$uri)=@_;
6387: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
6388: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
6389: $udom = &LONCAPA::clean_domain($udom);
6390: $ucrs = &LONCAPA::clean_username($ucrs);
6391: my $access=0;
6392: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
6393: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6394: if ($type eq 'user') {
6395: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6396: my ($tdom,$tuname)=split(m{/},$scope);
6397: if ($tdom) {
6398: if ($tdom ne $env{'user.domain'}) { next; }
6399: }
6400: if ($tuname) {
6401: if ($tuname ne $env{'user.name'}) { next; }
6402: }
6403: $access=($effect eq 'allow');
6404: last;
6405: }
6406: } else {
6407: if ($role) {
6408: if ($role ne $urole) { next; }
6409: }
6410: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6411: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6412: if ($tdom) {
6413: if ($tdom ne $udom) { next; }
6414: }
6415: if ($tcrs) {
6416: if ($tcrs ne $ucrs) { next; }
6417: }
6418: if ($tsec) {
6419: if ($tsec ne $usec) { next; }
6420: }
6421: $access=($effect eq 'allow');
6422: last;
6423: }
6424: if ($realm eq '' && $role eq '') {
6425: $access=($effect eq 'allow');
6426: }
6427: }
6428: }
6429: return $access;
6430: }
6431:
6432: # ------------------------------------------------- Check for a user privilege
6433:
6434: sub allowed {
6435: my ($priv,$uri,$symb,$role)=@_;
6436: my $ver_orguri=$uri;
6437: $uri=&deversion($uri);
6438: my $orguri=$uri;
6439: $uri=&declutter($uri);
6440:
6441: if ($priv eq 'evb') {
6442: # Evade communication block restrictions for specified role in a course
6443: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6444: return $1;
6445: } else {
6446: return;
6447: }
6448: }
6449:
6450: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
6451: # Free bre access to adm and meta resources
6452: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
6453: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6454: && ($priv eq 'bre')) {
6455: return 'F';
6456: }
6457:
6458: # Free bre access to user's own portfolio contents
6459: my ($space,$domain,$name,@dir)=split('/',$uri);
6460: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
6461: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
6462: my %setters;
6463: my ($startblock,$endblock) =
6464: &Apache::loncommon::blockcheck(\%setters,'port');
6465: if ($startblock && $endblock) {
6466: return 'B';
6467: } else {
6468: return 'F';
6469: }
6470: }
6471:
6472: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
6473: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6474: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6475: if (exists($env{'request.course.id'})) {
6476: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6477: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6478: if (($domain eq $cdom) && ($name eq $cnum)) {
6479: my $courseprivid=$env{'request.course.id'};
6480: $courseprivid=~s/\_/\//;
6481: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6482: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6483: return $1;
6484: } else {
6485: if ($env{'request.course.sec'}) {
6486: $courseprivid.='/'.$env{'request.course.sec'};
6487: }
6488: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6489: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6490: return $2;
6491: }
6492: }
6493: }
6494: }
6495: }
6496:
6497: # Free bre to public access
6498:
6499: if ($priv eq 'bre') {
6500: my $copyright=&metadata($uri,'copyright');
6501: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
6502: return 'F';
6503: }
6504: if ($copyright eq 'priv') {
6505: $uri=~/([^\/]+)\/([^\/]+)\//;
6506: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
6507: return '';
6508: }
6509: }
6510: if ($copyright eq 'domain') {
6511: $uri=~/([^\/]+)\/([^\/]+)\//;
6512: unless (($env{'user.domain'} eq $1) ||
6513: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
6514: return '';
6515: }
6516: }
6517: if ($env{'request.role'}=~ /li\.\//) {
6518: # Library role, so allow browsing of resources in this domain.
6519: return 'F';
6520: }
6521: if ($copyright eq 'custom') {
6522: unless (&customaccess($priv,$uri)) { return ''; }
6523: }
6524: }
6525: # Domain coordinator is trying to create a course
6526: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
6527: # uri is the requested domain in this case.
6528: # comparison to 'request.role.domain' shows if the user has selected
6529: # a role of dc for the domain in question.
6530: return 'F' if ($uri eq $env{'request.role.domain'});
6531: }
6532:
6533: my $thisallowed='';
6534: my $statecond=0;
6535: my $courseprivid='';
6536:
6537: my $ownaccess;
6538: # Community Coordinator or Assistant Co-author browsing resource space.
6539: if (($priv eq 'bro') && ($env{'user.author'})) {
6540: if ($uri eq '') {
6541: $ownaccess = 1;
6542: } else {
6543: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6544: my $udom = $env{'user.domain'};
6545: my $uname = $env{'user.name'};
6546: if ($uri =~ m{^\Q$udom\E/?$}) {
6547: $ownaccess = 1;
6548: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
6549: unless ($uri =~ m{\.\./}) {
6550: $ownaccess = 1;
6551: }
6552: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6553: my $now = time;
6554: if ($uri =~ m{^([^/]+)/?$}) {
6555: my $adom = $1;
6556: foreach my $key (keys(%env)) {
6557: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
6558: my ($start,$end) = split('.',$env{$key});
6559: if (($now >= $start) && (!$end || $end < $now)) {
6560: $ownaccess = 1;
6561: last;
6562: }
6563: }
6564: }
6565: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6566: my $adom = $1;
6567: my $aname = $2;
6568: foreach my $role ('ca','aa') {
6569: if ($env{"user.role.$role./$adom/$aname"}) {
6570: my ($start,$end) =
6571: split('.',$env{"user.role.$role./$adom/$aname"});
6572: if (($now >= $start) && (!$end || $end < $now)) {
6573: $ownaccess = 1;
6574: last;
6575: }
6576: }
6577: }
6578: }
6579: }
6580: }
6581: }
6582: }
6583:
6584: # Course
6585:
6586: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
6587: unless (($priv eq 'bro') && (!$ownaccess)) {
6588: $thisallowed.=$1;
6589: }
6590: }
6591:
6592: # Domain
6593:
6594: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
6595: =~/\Q$priv\E\&([^\:]*)/) {
6596: unless (($priv eq 'bro') && (!$ownaccess)) {
6597: $thisallowed.=$1;
6598: }
6599: }
6600:
6601: # User who is not author or co-author might still be able to edit
6602: # resource of an author in the domain (e.g., if Domain Coordinator).
6603: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6604: (&allowed('mdc',$env{'request.course.id'}))) {
6605: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6606: $thisallowed.=$1;
6607: }
6608: }
6609:
6610: # Course: uri itself is a course
6611: my $courseuri=$uri;
6612: $courseuri=~s/\_(\d)/\/$1/;
6613: $courseuri=~s/^([^\/])/\/$1/;
6614:
6615: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
6616: =~/\Q$priv\E\&([^\:]*)/) {
6617: unless (($priv eq 'bro') && (!$ownaccess)) {
6618: $thisallowed.=$1;
6619: }
6620: }
6621:
6622: # URI is an uploaded document for this course, default permissions don't matter
6623: # not allowing 'edit' access (editupload) to uploaded course docs
6624: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
6625: $thisallowed='';
6626: my ($match)=&is_on_map($uri);
6627: if ($match) {
6628: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6629: =~/\Q$priv\E\&([^\:]*)/) {
6630: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6631: if (@blockers > 0) {
6632: $thisallowed = 'B';
6633: } else {
6634: $thisallowed.=$1;
6635: }
6636: }
6637: } else {
6638: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
6639: if ($refuri) {
6640: if ($refuri =~ m|^/adm/|) {
6641: $thisallowed='F';
6642: } else {
6643: $refuri=&declutter($refuri);
6644: my ($match) = &is_on_map($refuri);
6645: if ($match) {
6646: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6647: if (@blockers > 0) {
6648: $thisallowed = 'B';
6649: } else {
6650: $thisallowed='F';
6651: }
6652: }
6653: }
6654: }
6655: }
6656: }
6657:
6658: if ($priv eq 'bre'
6659: && $thisallowed ne 'F'
6660: && $thisallowed ne '2'
6661: && &is_portfolio_url($uri)) {
6662: $thisallowed = &portfolio_access($uri);
6663: }
6664:
6665: # Full access at system, domain or course-wide level? Exit.
6666: if ($thisallowed=~/F/) {
6667: return 'F';
6668: }
6669:
6670: # If this is generating or modifying users, exit with special codes
6671:
6672: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6673: if (($priv eq 'cca') || ($priv eq 'caa')) {
6674: my ($audom,$auname)=split('/',$uri);
6675: # no author name given, so this just checks on the general right to make a co-author in this domain
6676: unless ($auname) { return $thisallowed; }
6677: # an author name is given, so we are about to actually make a co-author for a certain account
6678: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6679: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6680: ($audom ne $env{'request.role.domain'}))) { return ''; }
6681: }
6682: return $thisallowed;
6683: }
6684: #
6685: # Gathered so far: system, domain and course wide privileges
6686: #
6687: # Course: See if uri or referer is an individual resource that is part of
6688: # the course
6689:
6690: if ($env{'request.course.id'}) {
6691:
6692: $courseprivid=$env{'request.course.id'};
6693: if ($env{'request.course.sec'}) {
6694: $courseprivid.='/'.$env{'request.course.sec'};
6695: }
6696: $courseprivid=~s/\_/\//;
6697: my $checkreferer=1;
6698: my ($match,$cond)=&is_on_map($uri);
6699: if ($match) {
6700: $statecond=$cond;
6701: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6702: =~/\Q$priv\E\&([^\:]*)/) {
6703: my $value = $1;
6704: if ($priv eq 'bre') {
6705: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6706: if (@blockers > 0) {
6707: $thisallowed = 'B';
6708: } else {
6709: $thisallowed.=$value;
6710: }
6711: } else {
6712: $thisallowed.=$value;
6713: }
6714: $checkreferer=0;
6715: }
6716: }
6717:
6718: if ($checkreferer) {
6719: my $refuri=$env{'httpref.'.$orguri};
6720: unless ($refuri) {
6721: foreach my $key (keys(%env)) {
6722: if ($key=~/^httpref\..*\*/) {
6723: my $pattern=$key;
6724: $pattern=~s/^httpref\.\/res\///;
6725: $pattern=~s/\*/\[\^\/\]\+/g;
6726: $pattern=~s/\//\\\//g;
6727: if ($orguri=~/$pattern/) {
6728: $refuri=$env{$key};
6729: }
6730: }
6731: }
6732: }
6733:
6734: if ($refuri) {
6735: $refuri=&declutter($refuri);
6736: my ($match,$cond)=&is_on_map($refuri);
6737: if ($match) {
6738: my $refstatecond=$cond;
6739: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6740: =~/\Q$priv\E\&([^\:]*)/) {
6741: my $value = $1;
6742: if ($priv eq 'bre') {
6743: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6744: if (@blockers > 0) {
6745: $thisallowed = 'B';
6746: } else {
6747: $thisallowed.=$value;
6748: }
6749: } else {
6750: $thisallowed.=$value;
6751: }
6752: $uri=$refuri;
6753: $statecond=$refstatecond;
6754: }
6755: }
6756: }
6757: }
6758: }
6759:
6760: #
6761: # Gathered now: all privileges that could apply, and condition number
6762: #
6763: #
6764: # Full or no access?
6765: #
6766:
6767: if ($thisallowed=~/F/) {
6768: return 'F';
6769: }
6770:
6771: unless ($thisallowed) {
6772: return '';
6773: }
6774:
6775: # Restrictions exist, deal with them
6776: #
6777: # C:according to course preferences
6778: # R:according to resource settings
6779: # L:unless locked
6780: # X:according to user session state
6781: #
6782:
6783: # Possibly locked functionality, check all courses
6784: # Locks might take effect only after 10 minutes cache expiration for other
6785: # courses, and 2 minutes for current course
6786:
6787: my $envkey;
6788: if ($thisallowed=~/L/) {
6789: foreach $envkey (keys(%env)) {
6790: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6791: my $courseid=$2;
6792: my $roleid=$1.'.'.$2;
6793: $courseid=~s/^\///;
6794: my $expiretime=600;
6795: if ($env{'request.role'} eq $roleid) {
6796: $expiretime=120;
6797: }
6798: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6799: my $prefix='course.'.$cdom.'_'.$cnum.'.';
6800: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
6801: &coursedescription($courseid,{'freshen_cache' => 1});
6802: }
6803: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6804: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6805: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6806: &log($env{'user.domain'},$env{'user.name'},
6807: $env{'user.home'},
6808: 'Locked by res: '.$priv.' for '.$uri.' due to '.
6809: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6810: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6811: return '';
6812: }
6813: }
6814: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6815: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6816: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6817: &log($env{'user.domain'},$env{'user.name'},
6818: $env{'user.home'},
6819: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
6820: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6821: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6822: return '';
6823: }
6824: }
6825: }
6826: }
6827: }
6828:
6829: #
6830: # Rest of the restrictions depend on selected course
6831: #
6832:
6833: unless ($env{'request.course.id'}) {
6834: if ($thisallowed eq 'A') {
6835: return 'A';
6836: } elsif ($thisallowed eq 'B') {
6837: return 'B';
6838: } else {
6839: return '1';
6840: }
6841: }
6842:
6843: #
6844: # Now user is definitely in a course
6845: #
6846:
6847:
6848: # Course preferences
6849:
6850: if ($thisallowed=~/C/) {
6851: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6852: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6853: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
6854: =~/\Q$rolecode\E/) {
6855: if (($priv ne 'pch') && ($priv ne 'plc')) {
6856: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6857: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6858: $env{'request.course.id'});
6859: }
6860: return '';
6861: }
6862:
6863: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
6864: =~/\Q$unamedom\E/) {
6865: if (($priv ne 'pch') && ($priv ne 'plc')) {
6866: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6867: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6868: $env{'request.course.id'});
6869: }
6870: return '';
6871: }
6872: }
6873:
6874: # Resource preferences
6875:
6876: if ($thisallowed=~/R/) {
6877: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6878: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
6879: if (($priv ne 'pch') && ($priv ne 'plc')) {
6880: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6881: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6882: }
6883: return '';
6884: }
6885: }
6886:
6887: # Restricted by state or randomout?
6888:
6889: if ($thisallowed=~/X/) {
6890: if ($env{'acc.randomout'}) {
6891: if (!$symb) { $symb=&symbread($uri,1); }
6892: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
6893: return '';
6894: }
6895: }
6896: if (&condval($statecond)) {
6897: return '2';
6898: } else {
6899: return '';
6900: }
6901: }
6902:
6903: if ($thisallowed eq 'A') {
6904: return 'A';
6905: } elsif ($thisallowed eq 'B') {
6906: return 'B';
6907: }
6908: return 'F';
6909: }
6910:
6911: # ------------------------------------------- Check construction space access
6912:
6913: sub constructaccess {
6914: my ($url,$setpriv)=@_;
6915:
6916: # We do not allow editing of previous versions of files
6917: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
6918:
6919: # Get username and domain from URL
6920: my ($ownername,$ownerdomain,$ownerhome);
6921:
6922: ($ownerdomain,$ownername) =
6923: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
6924:
6925: # The URL does not really point to any authorspace, forget it
6926: unless (($ownername) && ($ownerdomain)) { return ''; }
6927:
6928: # Now we need to see if the user has access to the authorspace of
6929: # $ownername at $ownerdomain
6930:
6931: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
6932: # Real author for this?
6933: $ownerhome = $env{'user.home'};
6934: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
6935: return ($ownername,$ownerdomain,$ownerhome);
6936: }
6937: } else {
6938: # Co-author for this?
6939: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
6940: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
6941: $ownerhome = &homeserver($ownername,$ownerdomain);
6942: return ($ownername,$ownerdomain,$ownerhome);
6943: }
6944: }
6945:
6946: # We don't have any access right now. If we are not possibly going to do anything about this,
6947: # we might as well leave
6948: unless ($setpriv) { return ''; }
6949:
6950: # Backdoor access?
6951: my $allowed=&allowed('eco',$ownerdomain);
6952: # Nope
6953: unless ($allowed) { return ''; }
6954: # Looks like we may have access, but could be locked by the owner of the construction space
6955: if ($allowed eq 'U') {
6956: my %blocked=&get('environment',['domcoord.author'],
6957: $ownerdomain,$ownername);
6958: # Is blocked by owner
6959: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
6960: }
6961: if (($allowed eq 'F') || ($allowed eq 'U')) {
6962: # Grant temporary access
6963: my $then=$env{'user.login.time'};
6964: my $update=$env{'user.update.time'};
6965: if (!$update) { $update = $then; }
6966: my $refresh=$env{'user.refresh.time'};
6967: if (!$refresh) { $refresh = $update; }
6968: my $now = time;
6969: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
6970: $now,'ca','constructaccess');
6971: $ownerhome = &homeserver($ownername,$ownerdomain);
6972: return($ownername,$ownerdomain,$ownerhome);
6973: }
6974: # No business here
6975: return '';
6976: }
6977:
6978: sub get_comm_blocks {
6979: my ($cdom,$cnum) = @_;
6980: if ($cdom eq '' || $cnum eq '') {
6981: return unless ($env{'request.course.id'});
6982: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6983: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6984: }
6985: my %commblocks;
6986: my $hashid=$cdom.'_'.$cnum;
6987: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
6988: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
6989: %commblocks = %{$blocksref};
6990: } else {
6991: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
6992: my $cachetime = 600;
6993: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
6994: }
6995: return %commblocks;
6996: }
6997:
6998: sub has_comm_blocking {
6999: my ($priv,$symb,$uri,$blocks) = @_;
7000: return unless ($env{'request.course.id'});
7001: return unless ($priv eq 'bre');
7002: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7003: my %commblocks;
7004: if (ref($blocks) eq 'HASH') {
7005: %commblocks = %{$blocks};
7006: } else {
7007: %commblocks = &get_comm_blocks();
7008: }
7009: return unless (keys(%commblocks) > 0);
7010: if (!$symb) { $symb=&symbread($uri,1); }
7011: my ($map,$resid,undef)=&decode_symb($symb);
7012: my %tocheck = (
7013: maps => $map,
7014: resources => $symb,
7015: );
7016: my @blockers;
7017: my $now = time;
7018: my $navmap = Apache::lonnavmaps::navmap->new();
7019: foreach my $block (keys(%commblocks)) {
7020: if ($block =~ /^(\d+)____(\d+)$/) {
7021: my ($start,$end) = ($1,$2);
7022: if ($start <= $now && $end >= $now) {
7023: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7024: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7025: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7026: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7027: unless (grep(/^\Q$block\E$/,@blockers)) {
7028: push(@blockers,$block);
7029: }
7030: }
7031: }
7032: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7033: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7034: unless (grep(/^\Q$block\E$/,@blockers)) {
7035: push(@blockers,$block);
7036: }
7037: }
7038: }
7039: }
7040: }
7041: }
7042: } elsif ($block =~ /^firstaccess____(.+)$/) {
7043: my $item = $1;
7044: my @to_test;
7045: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7046: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7047: my $check_interval;
7048: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7049: my @interval;
7050: my $type = 'map';
7051: if ($item eq 'course') {
7052: $type = 'course';
7053: @interval=&EXT("resource.0.interval");
7054: } else {
7055: if ($item =~ /___\d+___/) {
7056: $type = 'resource';
7057: @interval=&EXT("resource.0.interval",$item);
7058: if (ref($navmap)) {
7059: my $res = $navmap->getBySymb($item);
7060: push(@to_test,$res);
7061: }
7062: } else {
7063: my $mapsymb = &symbread($item,1);
7064: if ($mapsymb) {
7065: if (ref($navmap)) {
7066: my $mapres = $navmap->getBySymb($mapsymb);
7067: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7068: foreach my $res (@to_test) {
7069: my $symb = $res->symb();
7070: next if ($symb eq $mapsymb);
7071: if ($symb ne '') {
7072: @interval=&EXT("resource.0.interval",$symb);
7073: last;
7074: }
7075: }
7076: }
7077: }
7078: }
7079: }
7080: if ($interval[0] =~ /\d+/) {
7081: my $first_access;
7082: if ($type eq 'resource') {
7083: $first_access=&get_first_access($interval[1],$item);
7084: } elsif ($type eq 'map') {
7085: $first_access=&get_first_access($interval[1],undef,$item);
7086: } else {
7087: $first_access=&get_first_access($interval[1]);
7088: }
7089: if ($first_access) {
7090: my $timesup = $first_access+$interval[0];
7091: if ($timesup > $now) {
7092: foreach my $res (@to_test) {
7093: if ($res->is_problem()) {
7094: if ($res->completable()) {
7095: unless (grep(/^\Q$block\E$/,@blockers)) {
7096: push(@blockers,$block);
7097: }
7098: last;
7099: }
7100: }
7101: }
7102: }
7103: }
7104: }
7105: }
7106: }
7107: }
7108: }
7109: }
7110: return @blockers;
7111: }
7112:
7113: sub check_docs_block {
7114: my ($docsblock,$tocheck) =@_;
7115: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7116: return;
7117: }
7118: if (ref($docsblock->{'maps'}) eq 'HASH') {
7119: if ($tocheck->{'maps'}) {
7120: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7121: return 1;
7122: }
7123: }
7124: }
7125: if (ref($docsblock->{'resources'}) eq 'HASH') {
7126: if ($tocheck->{'resources'}) {
7127: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7128: return 1;
7129: }
7130: }
7131: }
7132: return;
7133: }
7134:
7135: #
7136: # Removes the versino from a URI and
7137: # splits it in to its filename and path to the filename.
7138: # Seems like File::Basename could have done this more clearly.
7139: # Parameters:
7140: # $uri - input URI
7141: # Returns:
7142: # Two element list consisting of
7143: # $pathname - the URI up to and excluding the trailing /
7144: # $filename - The part of the URI following the last /
7145: # NOTE:
7146: # Another realization of this is simply:
7147: # use File::Basename;
7148: # ...
7149: # $uri = shift;
7150: # $filename = basename($uri);
7151: # $path = dirname($uri);
7152: # return ($filename, $path);
7153: #
7154: # The implementation below is probably faster however.
7155: #
7156: sub split_uri_for_cond {
7157: my $uri=&deversion(&declutter(shift));
7158: my @uriparts=split(/\//,$uri);
7159: my $filename=pop(@uriparts);
7160: my $pathname=join('/',@uriparts);
7161: return ($pathname,$filename);
7162: }
7163: # --------------------------------------------------- Is a resource on the map?
7164:
7165: sub is_on_map {
7166: my ($pathname,$filename) = &split_uri_for_cond(shift);
7167: #Trying to find the conditional for the file
7168: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
7169: /\&\Q$filename\E\:([\d\|]+)\&/);
7170: if ($match) {
7171: return (1,$1);
7172: } else {
7173: return (0,0);
7174: }
7175: }
7176:
7177: # --------------------------------------------------------- Get symb from alias
7178:
7179: sub get_symb_from_alias {
7180: my $symb=shift;
7181: my ($map,$resid,$url)=&decode_symb($symb);
7182: # Already is a symb
7183: if ($url) { return $symb; }
7184: # Must be an alias
7185: my $aliassymb='';
7186: my %bighash;
7187: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7188: &GDBM_READER(),0640)) {
7189: my $rid=$bighash{'mapalias_'.$symb};
7190: if ($rid) {
7191: my ($mapid,$resid)=split(/\./,$rid);
7192: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7193: $resid,$bighash{'src_'.$rid});
7194: }
7195: untie %bighash;
7196: }
7197: return $aliassymb;
7198: }
7199:
7200: # ----------------------------------------------------------------- Define Role
7201:
7202: sub definerole {
7203: if (allowed('mcr','/')) {
7204: my ($rolename,$sysrole,$domrole,$courole)=@_;
7205: foreach my $role (split(':',$sysrole)) {
7206: my ($crole,$cqual)=split(/\&/,$role);
7207: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7208: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7209: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
7210: return "refused:s:$crole&$cqual";
7211: }
7212: }
7213: }
7214: foreach my $role (split(':',$domrole)) {
7215: my ($crole,$cqual)=split(/\&/,$role);
7216: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7217: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7218: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
7219: return "refused:d:$crole&$cqual";
7220: }
7221: }
7222: }
7223: foreach my $role (split(':',$courole)) {
7224: my ($crole,$cqual)=split(/\&/,$role);
7225: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7226: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7227: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
7228: return "refused:c:$crole&$cqual";
7229: }
7230: }
7231: }
7232: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7233: "$env{'user.domain'}:$env{'user.name'}:".
7234: "rolesdef_$rolename=".
7235: escape($sysrole.'_'.$domrole.'_'.$courole);
7236: return reply($command,$env{'user.home'});
7237: } else {
7238: return 'refused';
7239: }
7240: }
7241:
7242: # ---------------- Make a metadata query against the network of library servers
7243:
7244: sub metadata_query {
7245: my ($query,$custom,$customshow,$server_array)=@_;
7246: my %rhash;
7247: my %libserv = &all_library();
7248: my @server_list = (defined($server_array) ? @$server_array
7249: : keys(%libserv) );
7250: for my $server (@server_list) {
7251: unless ($custom or $customshow) {
7252: my $reply=&reply("querysend:".&escape($query),$server);
7253: $rhash{$server}=$reply;
7254: }
7255: else {
7256: my $reply=&reply("querysend:".&escape($query).':'.
7257: &escape($custom).':'.&escape($customshow),
7258: $server);
7259: $rhash{$server}=$reply;
7260: }
7261: }
7262: return \%rhash;
7263: }
7264:
7265: # ----------------------------------------- Send log queries and wait for reply
7266:
7267: sub log_query {
7268: my ($uname,$udom,$query,%filters)=@_;
7269: my $uhome=&homeserver($uname,$udom);
7270: if ($uhome eq 'no_host') { return 'error: no_host'; }
7271: my $uhost=&hostname($uhome);
7272: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
7273: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7274: $uhome);
7275: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
7276: return get_query_reply($queryid);
7277: }
7278:
7279: # -------------------------- Update MySQL table for portfolio file
7280:
7281: sub update_portfolio_table {
7282: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
7283: if ($group ne '') {
7284: $file_name =~s /^\Q$group\E//;
7285: }
7286: my $homeserver = &homeserver($uname,$udom);
7287: my $queryid=
7288: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7289: ':'.&escape($file_name).':'.$action,$homeserver);
7290: my $reply = &get_query_reply($queryid);
7291: return $reply;
7292: }
7293:
7294: # -------------------------- Update MySQL allusers table
7295:
7296: sub update_allusers_table {
7297: my ($uname,$udom,$names) = @_;
7298: my $homeserver = &homeserver($uname,$udom);
7299: my $queryid=
7300: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7301: 'lastname='.&escape($names->{'lastname'}).'%%'.
7302: 'firstname='.&escape($names->{'firstname'}).'%%'.
7303: 'middlename='.&escape($names->{'middlename'}).'%%'.
7304: 'generation='.&escape($names->{'generation'}).'%%'.
7305: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7306: 'id='.&escape($names->{'id'}),$homeserver);
7307: return;
7308: }
7309:
7310: # ------- Request retrieval of institutional classlists for course(s)
7311:
7312: sub fetch_enrollment_query {
7313: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
7314: my $homeserver;
7315: my $maxtries = 1;
7316: if ($context eq 'automated') {
7317: $homeserver = $perlvar{'lonHostID'};
7318: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
7319: } else {
7320: $homeserver = &homeserver($cnum,$dom);
7321: }
7322: my $host=&hostname($homeserver);
7323: my $cmd = '';
7324: foreach my $affiliate (keys(%{$affiliatesref})) {
7325: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
7326: }
7327: $cmd =~ s/%%$//;
7328: $cmd = &escape($cmd);
7329: my $query = 'fetchenrollment';
7330: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
7331: unless ($queryid=~/^\Q$host\E\_/) {
7332: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7333: return 'error: '.$queryid;
7334: }
7335: my $reply = &get_query_reply($queryid);
7336: my $tries = 1;
7337: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7338: $reply = &get_query_reply($queryid);
7339: $tries ++;
7340: }
7341: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7342: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7343: } else {
7344: my @responses = split(/:/,$reply);
7345: if ($homeserver eq $perlvar{'lonHostID'}) {
7346: foreach my $line (@responses) {
7347: my ($key,$value) = split(/=/,$line,2);
7348: $$replyref{$key} = $value;
7349: }
7350: } else {
7351: my $pathname = LONCAPA::tempdir();
7352: foreach my $line (@responses) {
7353: my ($key,$value) = split(/=/,$line);
7354: $$replyref{$key} = $value;
7355: if ($value > 0) {
7356: foreach my $item (@{$$affiliatesref{$key}}) {
7357: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
7358: my $destname = $pathname.'/'.$filename;
7359: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
7360: if ($xml_classlist =~ /^error/) {
7361: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7362: } else {
7363: if ( open(FILE,">$destname") ) {
7364: print FILE &unescape($xml_classlist);
7365: close(FILE);
7366: } else {
7367: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
7368: }
7369: }
7370: }
7371: }
7372: }
7373: }
7374: return 'ok';
7375: }
7376: return 'error';
7377: }
7378:
7379: sub get_query_reply {
7380: my $queryid=shift;
7381: my $replyfile=LONCAPA::tempdir().$queryid;
7382: my $reply='';
7383: for (1..100) {
7384: sleep 2;
7385: if (-e $replyfile.'.end') {
7386: if (open(my $fh,$replyfile)) {
7387: $reply = join('',<$fh>);
7388: close($fh);
7389: } else { return 'error: reply_file_error'; }
7390: return &unescape($reply);
7391: }
7392: }
7393: return 'timeout:'.$queryid;
7394: }
7395:
7396: sub courselog_query {
7397: #
7398: # possible filters:
7399: # url: url or symb
7400: # username
7401: # domain
7402: # action: view, submit, grade
7403: # start: timestamp
7404: # end: timestamp
7405: #
7406: my (%filters)=@_;
7407: unless ($env{'request.course.id'}) { return 'no_course'; }
7408: if ($filters{'url'}) {
7409: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7410: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7411: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7412: }
7413: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7414: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7415: return &log_query($cname,$cdom,'courselog',%filters);
7416: }
7417:
7418: sub userlog_query {
7419: #
7420: # possible filters:
7421: # action: log check role
7422: # start: timestamp
7423: # end: timestamp
7424: #
7425: my ($uname,$udom,%filters)=@_;
7426: return &log_query($uname,$udom,'userlog',%filters);
7427: }
7428:
7429: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7430:
7431: sub auto_run {
7432: my ($cnum,$cdom) = @_;
7433: my $response = 0;
7434: my $settings;
7435: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7436: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7437: $settings = $domconfig{'autoenroll'};
7438: if ($settings->{'run'} eq '1') {
7439: $response = 1;
7440: }
7441: } else {
7442: my $homeserver;
7443: if (&is_course($cdom,$cnum)) {
7444: $homeserver = &homeserver($cnum,$cdom);
7445: } else {
7446: $homeserver = &domain($cdom,'primary');
7447: }
7448: if ($homeserver ne 'no_host') {
7449: $response = &reply('autorun:'.$cdom,$homeserver);
7450: }
7451: }
7452: return $response;
7453: }
7454:
7455: sub auto_get_sections {
7456: my ($cnum,$cdom,$inst_coursecode) = @_;
7457: my $homeserver;
7458: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7459: $homeserver = &homeserver($cnum,$cdom);
7460: }
7461: if (!defined($homeserver)) {
7462: if ($cdom =~ /^$match_domain$/) {
7463: $homeserver = &domain($cdom,'primary');
7464: }
7465: }
7466: my @secs;
7467: if (defined($homeserver)) {
7468: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7469: unless ($response eq 'refused') {
7470: @secs = split(/:/,$response);
7471: }
7472: }
7473: return @secs;
7474: }
7475:
7476: sub auto_new_course {
7477: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
7478: my $homeserver = &homeserver($cnum,$cdom);
7479: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
7480: return $response;
7481: }
7482:
7483: sub auto_validate_courseID {
7484: my ($cnum,$cdom,$inst_course_id) = @_;
7485: my $homeserver = &homeserver($cnum,$cdom);
7486: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
7487: return $response;
7488: }
7489:
7490: sub auto_validate_instcode {
7491: my ($cnum,$cdom,$instcode,$owner) = @_;
7492: my ($homeserver,$response);
7493: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7494: $homeserver = &homeserver($cnum,$cdom);
7495: }
7496: if (!defined($homeserver)) {
7497: if ($cdom =~ /^$match_domain$/) {
7498: $homeserver = &domain($cdom,'primary');
7499: }
7500: }
7501: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7502: &escape($instcode).':'.&escape($owner),$homeserver));
7503: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7504: return ($outcome,$description,$defaultcredits);
7505: }
7506:
7507: sub auto_create_password {
7508: my ($cnum,$cdom,$authparam,$udom) = @_;
7509: my ($homeserver,$response);
7510: my $create_passwd = 0;
7511: my $authchk = '';
7512: if ($udom =~ /^$match_domain$/) {
7513: $homeserver = &domain($udom,'primary');
7514: }
7515: if ($homeserver eq '') {
7516: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7517: $homeserver = &homeserver($cnum,$cdom);
7518: }
7519: }
7520: if ($homeserver eq '') {
7521: $authchk = 'nodomain';
7522: } else {
7523: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7524: if ($response eq 'refused') {
7525: $authchk = 'refused';
7526: } else {
7527: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
7528: }
7529: }
7530: return ($authparam,$create_passwd,$authchk);
7531: }
7532:
7533: sub auto_photo_permission {
7534: my ($cnum,$cdom,$students) = @_;
7535: my $homeserver = &homeserver($cnum,$cdom);
7536: my ($outcome,$perm_reqd,$conditions) =
7537: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
7538: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7539: return (undef,undef);
7540: }
7541: return ($outcome,$perm_reqd,$conditions);
7542: }
7543:
7544: sub auto_checkphotos {
7545: my ($uname,$udom,$pid) = @_;
7546: my $homeserver = &homeserver($uname,$udom);
7547: my ($result,$resulttype);
7548: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
7549: &escape($uname).':'.&escape($pid),
7550: $homeserver));
7551: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7552: return (undef,undef);
7553: }
7554: if ($outcome) {
7555: ($result,$resulttype) = split(/:/,$outcome);
7556: }
7557: return ($result,$resulttype);
7558: }
7559:
7560: sub auto_photochoice {
7561: my ($cnum,$cdom) = @_;
7562: my $homeserver = &homeserver($cnum,$cdom);
7563: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
7564: &escape($cdom),
7565: $homeserver)));
7566: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7567: return (undef,undef);
7568: }
7569: return ($update,$comment);
7570: }
7571:
7572: sub auto_photoupdate {
7573: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7574: my $homeserver = &homeserver($cnum,$dom);
7575: my $host=&hostname($homeserver);
7576: my $cmd = '';
7577: my $maxtries = 1;
7578: foreach my $affiliate (keys(%{$affiliatesref})) {
7579: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
7580: }
7581: $cmd =~ s/%%$//;
7582: $cmd = &escape($cmd);
7583: my $query = 'institutionalphotos';
7584: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7585: unless ($queryid=~/^\Q$host\E\_/) {
7586: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7587: return 'error: '.$queryid;
7588: }
7589: my $reply = &get_query_reply($queryid);
7590: my $tries = 1;
7591: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7592: $reply = &get_query_reply($queryid);
7593: $tries ++;
7594: }
7595: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7596: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7597: } else {
7598: my @responses = split(/:/,$reply);
7599: my $outcome = shift(@responses);
7600: foreach my $item (@responses) {
7601: my ($key,$value) = split(/=/,$item);
7602: $$photo{$key} = $value;
7603: }
7604: return $outcome;
7605: }
7606: return 'error';
7607: }
7608:
7609: sub auto_instcode_format {
7610: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7611: $cat_order) = @_;
7612: my $courses = '';
7613: my @homeservers;
7614: if ($caller eq 'global') {
7615: my %servers = &get_servers($codedom,'library');
7616: foreach my $tryserver (keys(%servers)) {
7617: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7618: push(@homeservers,$tryserver);
7619: }
7620: }
7621: } elsif ($caller eq 'requests') {
7622: if ($codedom =~ /^$match_domain$/) {
7623: my $chome = &domain($codedom,'primary');
7624: unless ($chome eq 'no_host') {
7625: push(@homeservers,$chome);
7626: }
7627: }
7628: } else {
7629: push(@homeservers,&homeserver($caller,$codedom));
7630: }
7631: foreach my $code (keys(%{$instcodes})) {
7632: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
7633: }
7634: chop($courses);
7635: my $ok_response = 0;
7636: my $response;
7637: while (@homeservers > 0 && $ok_response == 0) {
7638: my $server = shift(@homeservers);
7639: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7640: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7641: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
7642: split(/:/,$response);
7643: %{$codes} = (%{$codes},&str2hash($codes_str));
7644: push(@{$codetitles},&str2array($codetitles_str));
7645: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7646: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7647: $ok_response = 1;
7648: }
7649: }
7650: if ($ok_response) {
7651: return 'ok';
7652: } else {
7653: return $response;
7654: }
7655: }
7656:
7657: sub auto_instcode_defaults {
7658: my ($domain,$returnhash,$code_order) = @_;
7659: my @homeservers;
7660:
7661: my %servers = &get_servers($domain,'library');
7662: foreach my $tryserver (keys(%servers)) {
7663: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7664: push(@homeservers,$tryserver);
7665: }
7666: }
7667:
7668: my $response;
7669: foreach my $server (@homeservers) {
7670: $response=&reply('autoinstcodedefaults:'.$domain,$server);
7671: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7672:
7673: foreach my $pair (split(/\&/,$response)) {
7674: my ($name,$value)=split(/\=/,$pair);
7675: if ($name eq 'code_order') {
7676: @{$code_order} = split(/\&/,&unescape($value));
7677: } else {
7678: $returnhash->{&unescape($name)}=&unescape($value);
7679: }
7680: }
7681: return 'ok';
7682: }
7683:
7684: return $response;
7685: }
7686:
7687: sub auto_possible_instcodes {
7688: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7689: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7690: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7691: return;
7692: }
7693: my (@homeservers,$uhome);
7694: if (defined(&domain($domain,'primary'))) {
7695: $uhome=&domain($domain,'primary');
7696: push(@homeservers,&domain($domain,'primary'));
7697: } else {
7698: my %servers = &get_servers($domain,'library');
7699: foreach my $tryserver (keys(%servers)) {
7700: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7701: push(@homeservers,$tryserver);
7702: }
7703: }
7704: }
7705: my $response;
7706: foreach my $server (@homeservers) {
7707: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7708: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7709: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7710: split(':',$response);
7711: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7712: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
7713: foreach my $item (split('&',$cat_title)) {
7714: my ($name,$value)=split('=',$item);
7715: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
7716: }
7717: foreach my $item (split('&',$cat_order)) {
7718: my ($name,$value)=split('=',$item);
7719: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
7720: }
7721: return 'ok';
7722: }
7723: return $response;
7724: }
7725:
7726: sub auto_courserequest_checks {
7727: my ($dom) = @_;
7728: my ($homeserver,%validations);
7729: if ($dom =~ /^$match_domain$/) {
7730: $homeserver = &domain($dom,'primary');
7731: }
7732: unless ($homeserver eq 'no_host') {
7733: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7734: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7735: my @items = split(/&/,$response);
7736: foreach my $item (@items) {
7737: my ($key,$value) = split('=',$item);
7738: $validations{&unescape($key)} = &thaw_unescape($value);
7739: }
7740: }
7741: }
7742: return %validations;
7743: }
7744:
7745: sub auto_courserequest_validation {
7746: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7747: my ($homeserver,$response);
7748: if ($dom =~ /^$match_domain$/) {
7749: $homeserver = &domain($dom,'primary');
7750: }
7751: unless ($homeserver eq 'no_host') {
7752:
7753: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
7754: ':'.&escape($crstype).':'.&escape($inststatuslist).
7755: ':'.&escape($instcode).':'.&escape($instseclist),
7756: $homeserver));
7757: }
7758: return $response;
7759: }
7760:
7761: sub auto_validate_class_sec {
7762: my ($cdom,$cnum,$owners,$inst_class) = @_;
7763: my $homeserver = &homeserver($cnum,$cdom);
7764: my $ownerlist;
7765: if (ref($owners) eq 'ARRAY') {
7766: $ownerlist = join(',',@{$owners});
7767: } else {
7768: $ownerlist = $owners;
7769: }
7770: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
7771: &escape($ownerlist).':'.$cdom,$homeserver);
7772: return $response;
7773: }
7774:
7775: # ------------------------------------------------------- Course Group routines
7776:
7777: sub get_coursegroups {
7778: my ($cdom,$cnum,$group,$namespace) = @_;
7779: return(&dump($namespace,$cdom,$cnum,$group));
7780: }
7781:
7782: sub modify_coursegroup {
7783: my ($cdom,$cnum,$groupsettings) = @_;
7784: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7785: }
7786:
7787: sub toggle_coursegroup_status {
7788: my ($cdom,$cnum,$group,$action) = @_;
7789: my ($from_namespace,$to_namespace);
7790: if ($action eq 'delete') {
7791: $from_namespace = 'coursegroups';
7792: $to_namespace = 'deleted_groups';
7793: } else {
7794: $from_namespace = 'deleted_groups';
7795: $to_namespace = 'coursegroups';
7796: }
7797: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
7798: if (my $tmp = &error(%curr_group)) {
7799: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7800: return ('read error',$tmp);
7801: } else {
7802: my %savedsettings = %curr_group;
7803: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
7804: my $deloutcome;
7805: if ($result eq 'ok') {
7806: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
7807: } else {
7808: return ('write error',$result);
7809: }
7810: if ($deloutcome eq 'ok') {
7811: return 'ok';
7812: } else {
7813: return ('delete error',$deloutcome);
7814: }
7815: }
7816: }
7817:
7818: sub modify_group_roles {
7819: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
7820: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7821: my $role = 'gr/'.&escape($userprivs);
7822: my ($uname,$udom) = split(/:/,$user);
7823: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
7824: if ($result eq 'ok') {
7825: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7826: }
7827: return $result;
7828: }
7829:
7830: sub modify_coursegroup_membership {
7831: my ($cdom,$cnum,$membership) = @_;
7832: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7833: return $result;
7834: }
7835:
7836: sub get_active_groups {
7837: my ($udom,$uname,$cdom,$cnum) = @_;
7838: my $now = time;
7839: my %groups = ();
7840: foreach my $key (keys(%env)) {
7841: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
7842: my ($start,$end) = split(/\./,$env{$key});
7843: if (($end!=0) && ($end<$now)) { next; }
7844: if (($start!=0) && ($start>$now)) { next; }
7845: if ($1 eq $cdom && $2 eq $cnum) {
7846: $groups{$3} = $env{$key} ;
7847: }
7848: }
7849: }
7850: return %groups;
7851: }
7852:
7853: sub get_group_membership {
7854: my ($cdom,$cnum,$group) = @_;
7855: return(&dump('groupmembership',$cdom,$cnum,$group));
7856: }
7857:
7858: sub get_users_groups {
7859: my ($udom,$uname,$courseid) = @_;
7860: my @usersgroups;
7861: my $cachetime=1800;
7862:
7863: my $hashid="$udom:$uname:$courseid";
7864: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7865: if (defined($cached)) {
7866: @usersgroups = split(/:/,$grouplist);
7867: } else {
7868: $grouplist = '';
7869: my $courseurl = &courseid_to_courseurl($courseid);
7870: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
7871: my $access_end = $env{'course.'.$courseid.
7872: '.default_enrollment_end_date'};
7873: my $now = time;
7874: foreach my $key (keys(%roleshash)) {
7875: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7876: my $group = $1;
7877: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7878: my $start = $2;
7879: my $end = $1;
7880: if ($start == -1) { next; } # deleted from group
7881: if (($start!=0) && ($start>$now)) { next; }
7882: if (($end!=0) && ($end<$now)) {
7883: if ($access_end && $access_end < $now) {
7884: if ($access_end - $end < 86400) {
7885: push(@usersgroups,$group);
7886: }
7887: }
7888: next;
7889: }
7890: push(@usersgroups,$group);
7891: }
7892: }
7893: }
7894: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7895: $grouplist = join(':',@usersgroups);
7896: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
7897: }
7898: return @usersgroups;
7899: }
7900:
7901: sub devalidate_getgroups_cache {
7902: my ($udom,$uname,$cdom,$cnum)=@_;
7903: my $courseid = $cdom.'_'.$cnum;
7904:
7905: my $hashid="$udom:$uname:$courseid";
7906: &devalidate_cache_new('getgroups',$hashid);
7907: }
7908:
7909: # ------------------------------------------------------------------ Plain Text
7910:
7911: sub plaintext {
7912: my ($short,$type,$cid,$forcedefault) = @_;
7913: if ($short =~ m{^cr/}) {
7914: return (split('/',$short))[-1];
7915: }
7916: if (!defined($cid)) {
7917: $cid = $env{'request.course.id'};
7918: }
7919: my %rolenames = (
7920: Course => 'std',
7921: Community => 'alt1',
7922: );
7923: if ($cid ne '') {
7924: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7925: unless ($forcedefault) {
7926: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7927: &Apache::lonlocal::mt_escape(\$roletext);
7928: return &Apache::lonlocal::mt($roletext);
7929: }
7930: }
7931: }
7932: if ((defined($type)) && (defined($rolenames{$type})) &&
7933: (defined($rolenames{$type})) &&
7934: (defined($prp{$short}{$rolenames{$type}}))) {
7935: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
7936: } elsif ($cid ne '') {
7937: my $crstype = $env{'course.'.$cid.'.type'};
7938: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7939: (defined($prp{$short}{$rolenames{$crstype}}))) {
7940: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7941: }
7942: }
7943: return &Apache::lonlocal::mt($prp{$short}{'std'});
7944: }
7945:
7946: # ----------------------------------------------------------------- Assign Role
7947:
7948: sub assignrole {
7949: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7950: $context)=@_;
7951: my $mrole;
7952: if ($role =~ /^cr\//) {
7953: my $cwosec=$url;
7954: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7955: unless (&allowed('ccr',$cwosec)) {
7956: my $refused = 1;
7957: if ($context eq 'requestcourses') {
7958: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7959: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7960: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7961: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7962: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7963: if ($crsenv{'internal.courseowner'} eq
7964: $env{'user.name'}.':'.$env{'user.domain'}) {
7965: $refused = '';
7966: }
7967: }
7968: }
7969: }
7970: }
7971: if ($refused) {
7972: &logthis('Refused custom assignrole: '.
7973: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7974: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7975: return 'refused';
7976: }
7977: }
7978: $mrole='cr';
7979: } elsif ($role =~ /^gr\//) {
7980: my $cwogrp=$url;
7981: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
7982: unless (&allowed('mdg',$cwogrp)) {
7983: &logthis('Refused group assignrole: '.
7984: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7985: $env{'user.name'}.' at '.$env{'user.domain'});
7986: return 'refused';
7987: }
7988: $mrole='gr';
7989: } else {
7990: my $cwosec=$url;
7991: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7992: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7993: my $refused;
7994: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7995: if (!(&allowed('c'.$role,$url))) {
7996: $refused = 1;
7997: }
7998: } else {
7999: $refused = 1;
8000: }
8001: if ($refused) {
8002: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8003: if (!$selfenroll && $context eq 'course') {
8004: my %crsenv;
8005: if ($role eq 'cc' || $role eq 'co') {
8006: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8007: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8008: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8009: if ($crsenv{'internal.courseowner'} eq
8010: $env{'user.name'}.':'.$env{'user.domain'}) {
8011: $refused = '';
8012: }
8013: }
8014: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8015: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8016: if ($crsenv{'internal.courseowner'} eq
8017: $env{'user.name'}.':'.$env{'user.domain'}) {
8018: $refused = '';
8019: }
8020: }
8021: }
8022: }
8023: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
8024: $refused = '';
8025: } elsif ($context eq 'requestcourses') {
8026: my @possroles = ('st','ta','ep','in','cc','co');
8027: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
8028: my $wrongcc;
8029: if ($cnum =~ /^$match_community$/) {
8030: $wrongcc = 1 if ($role eq 'cc');
8031: } else {
8032: $wrongcc = 1 if ($role eq 'co');
8033: }
8034: unless ($wrongcc) {
8035: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8036: if ($crsenv{'internal.courseowner'} eq
8037: $env{'user.name'}.':'.$env{'user.domain'}) {
8038: $refused = '';
8039: }
8040: }
8041: }
8042: } elsif ($context eq 'requestauthor') {
8043: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8044: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8045: if ($env{'environment.requestauthor'} eq 'automatic') {
8046: $refused = '';
8047: } else {
8048: my %domdefaults = &get_domain_defaults($udom);
8049: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8050: my $checkbystatus;
8051: if ($env{'user.adv'}) {
8052: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8053: if ($disposition eq 'automatic') {
8054: $refused = '';
8055: } elsif ($disposition eq '') {
8056: $checkbystatus = 1;
8057: }
8058: } else {
8059: $checkbystatus = 1;
8060: }
8061: if ($checkbystatus) {
8062: if ($env{'environment.inststatus'}) {
8063: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8064: foreach my $type (@inststatuses) {
8065: if (($type ne '') &&
8066: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8067: $refused = '';
8068: }
8069: }
8070: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8071: $refused = '';
8072: }
8073: }
8074: }
8075: }
8076: }
8077: }
8078: if ($refused) {
8079: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8080: ' '.$role.' '.$end.' '.$start.' by '.
8081: $env{'user.name'}.' at '.$env{'user.domain'});
8082: return 'refused';
8083: }
8084: }
8085: } elsif ($role eq 'au') {
8086: if ($url ne '/'.$udom.'/') {
8087: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8088: ' to assign author role for '.$uname.':'.$udom.
8089: ' in domain: '.$url.' refused (wrong domain).');
8090: return 'refused';
8091: }
8092: }
8093: $mrole=$role;
8094: }
8095: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
8096: "$udom:$uname:$url".'_'."$mrole=$role";
8097: if ($end) { $command.='_'.$end; }
8098: if ($start) {
8099: if ($end) {
8100: $command.='_'.$start;
8101: } else {
8102: $command.='_0_'.$start;
8103: }
8104: }
8105: my $origstart = $start;
8106: my $origend = $end;
8107: my $delflag;
8108: # actually delete
8109: if ($deleteflag) {
8110: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
8111: # modify command to delete the role
8112: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
8113: "$udom:$uname:$url".'_'."$mrole";
8114: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
8115: # set start and finish to negative values for userrolelog
8116: $start=-1;
8117: $end=-1;
8118: $delflag = 1;
8119: }
8120: }
8121: # send command
8122: my $answer=&reply($command,&homeserver($uname,$udom));
8123: # log new user role if status is ok
8124: if ($answer eq 'ok') {
8125: &userrolelog($role,$uname,$udom,$url,$start,$end);
8126: if (($role eq 'cc') || ($role eq 'in') ||
8127: ($role eq 'ep') || ($role eq 'ad') ||
8128: ($role eq 'ta') || ($role eq 'st') ||
8129: ($role=~/^cr/) || ($role eq 'gr') ||
8130: ($role eq 'co')) {
8131: # for course roles, perform group memberships changes triggered by role change.
8132: unless ($role =~ /^gr/) {
8133: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8134: $origstart,$selfenroll,$context);
8135: }
8136: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8137: $selfenroll,$context);
8138: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8139: ($role eq 'au') || ($role eq 'dc')) {
8140: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8141: $context);
8142: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8143: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8144: $context);
8145: }
8146: if ($role eq 'cc') {
8147: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8148: }
8149: }
8150: return $answer;
8151: }
8152:
8153: sub autoupdate_coowners {
8154: my ($url,$end,$start,$uname,$udom) = @_;
8155: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8156: if (($cdom ne '') && ($cnum ne '')) {
8157: my $now = time;
8158: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8159: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8160: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8161: my $instcode = $coursehash{'internal.coursecode'};
8162: if ($instcode ne '') {
8163: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8164: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
8165: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
8166: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8167: if ($result eq 'valid') {
8168: if ($coursehash{'internal.co-owners'}) {
8169: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8170: push(@newcoowners,$coowner);
8171: }
8172: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8173: push(@newcoowners,$uname.':'.$udom);
8174: }
8175: @newcoowners = sort(@newcoowners);
8176: } else {
8177: push(@newcoowners,$uname.':'.$udom);
8178: }
8179: } else {
8180: if ($coursehash{'internal.co-owners'}) {
8181: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8182: unless ($coowner eq $uname.':'.$udom) {
8183: push(@newcoowners,$coowner);
8184: }
8185: }
8186: unless (@newcoowners > 0) {
8187: $delcoowners = 1;
8188: $coowners = '';
8189: }
8190: }
8191: }
8192: if (@newcoowners || $delcoowners) {
8193: &store_coowners($cdom,$cnum,$coursehash{'home'},
8194: $delcoowners,@newcoowners);
8195: }
8196: }
8197: }
8198: }
8199: }
8200: }
8201: }
8202:
8203: sub store_coowners {
8204: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8205: my $cid = $cdom.'_'.$cnum;
8206: my ($coowners,$delresult,$putresult);
8207: if (@newcoowners) {
8208: $coowners = join(',',@newcoowners);
8209: my %coownershash = (
8210: 'internal.co-owners' => $coowners,
8211: );
8212: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8213: if ($putresult eq 'ok') {
8214: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8215: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8216: }
8217: }
8218: }
8219: if ($delcoowners) {
8220: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8221: if ($delresult eq 'ok') {
8222: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8223: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8224: }
8225: }
8226: }
8227: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8228: my %crsinfo =
8229: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8230: if (ref($crsinfo{$cid}) eq 'HASH') {
8231: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8232: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8233: }
8234: }
8235: }
8236:
8237: # -------------------------------------------------- Modify user authentication
8238: # Overrides without validation
8239:
8240: sub modifyuserauth {
8241: my ($udom,$uname,$umode,$upass)=@_;
8242: my $uhome=&homeserver($uname,$udom);
8243: unless (&allowed('mau',$udom)) { return 'refused'; }
8244: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
8245: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8246: ' in domain '.$env{'request.role.domain'});
8247: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8248: &escape($upass),$uhome);
8249: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
8250: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8251: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8252: &log($udom,,$uname,$uhome,
8253: 'Authentication changed by '.$env{'user.domain'}.', '.
8254: $env{'user.name'}.', '.$umode.
8255: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8256: unless ($reply eq 'ok') {
8257: &logthis('Authentication mode error: '.$reply);
8258: return 'error: '.$reply;
8259: }
8260: return 'ok';
8261: }
8262:
8263: # --------------------------------------------------------------- Modify a user
8264:
8265: sub modifyuser {
8266: my ($udom, $uname, $uid,
8267: $umode, $upass, $first,
8268: $middle, $last, $gene,
8269: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
8270: $udom= &LONCAPA::clean_domain($udom);
8271: $uname=&LONCAPA::clean_username($uname);
8272: my $showcandelete = 'none';
8273: if (ref($candelete) eq 'ARRAY') {
8274: if (@{$candelete} > 0) {
8275: $showcandelete = join(', ',@{$candelete});
8276: }
8277: }
8278: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
8279: $umode.', '.$first.', '.$middle.', '.
8280: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
8281: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8282: ' desiredhome not specified').
8283: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8284: ' in domain '.$env{'request.role.domain'});
8285: my $uhome=&homeserver($uname,$udom,'true');
8286: my $newuser;
8287: if ($uhome eq 'no_host') {
8288: $newuser = 1;
8289: }
8290: # ----------------------------------------------------------------- Create User
8291: if (($uhome eq 'no_host') &&
8292: (($umode && $upass) || ($umode eq 'localauth'))) {
8293: my $unhome='';
8294: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
8295: $unhome = $desiredhome;
8296: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8297: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
8298: } else { # load balancing routine for determining $unhome
8299: my $loadm=10000000;
8300: my %servers = &get_servers($udom,'library');
8301: foreach my $tryserver (keys(%servers)) {
8302: my $answer=reply('load',$tryserver);
8303: if (($answer=~/\d+/) && ($answer<$loadm)) {
8304: $loadm=$answer;
8305: $unhome=$tryserver;
8306: }
8307: }
8308: }
8309: if (($unhome eq '') || ($unhome eq 'no_host')) {
8310: return 'error: unable to find a home server for '.$uname.
8311: ' in domain '.$udom;
8312: }
8313: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8314: &escape($upass),$unhome);
8315: unless ($reply eq 'ok') {
8316: return 'error: '.$reply;
8317: }
8318: $uhome=&homeserver($uname,$udom,'true');
8319: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
8320: return 'error: unable verify users home machine.';
8321: }
8322: } # End of creation of new user
8323: # ---------------------------------------------------------------------- Add ID
8324: if ($uid) {
8325: $uid=~tr/A-Z/a-z/;
8326: my %uidhash=&idrget($udom,$uname);
8327: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8328: && (!$forceid)) {
8329: unless ($uid eq $uidhash{$uname}) {
8330: return 'error: user id "'.$uid.'" does not match '.
8331: 'current user id "'.$uidhash{$uname}.'".';
8332: }
8333: } else {
8334: &idput($udom,($uname => $uid));
8335: }
8336: }
8337: # -------------------------------------------------------------- Add names, etc
8338: my @tmp=&get('environment',
8339: ['firstname','middlename','lastname','generation','id',
8340: 'permanentemail','inststatus'],
8341: $udom,$uname);
8342: my (%names,%oldnames);
8343: if ($tmp[0] =~ m/^error:.*/) {
8344: %names=();
8345: } else {
8346: %names = @tmp;
8347: %oldnames = %names;
8348: }
8349: #
8350: # If name, email and/or uid are blank (e.g., because an uploaded file
8351: # of users did not contain them), do not overwrite existing values
8352: # unless field is in $candelete array ref.
8353: #
8354:
8355: my @fields = ('firstname','middlename','lastname','generation',
8356: 'permanentemail','id');
8357: my %newvalues;
8358: if (ref($candelete) eq 'ARRAY') {
8359: foreach my $field (@fields) {
8360: if (grep(/^\Q$field\E$/,@{$candelete})) {
8361: if ($field eq 'firstname') {
8362: $names{$field} = $first;
8363: } elsif ($field eq 'middlename') {
8364: $names{$field} = $middle;
8365: } elsif ($field eq 'lastname') {
8366: $names{$field} = $last;
8367: } elsif ($field eq 'generation') {
8368: $names{$field} = $gene;
8369: } elsif ($field eq 'permanentemail') {
8370: $names{$field} = $email;
8371: } elsif ($field eq 'id') {
8372: $names{$field} = $uid;
8373: }
8374: }
8375: }
8376: }
8377: if ($first) { $names{'firstname'} = $first; }
8378: if (defined($middle)) { $names{'middlename'} = $middle; }
8379: if ($last) { $names{'lastname'} = $last; }
8380: if (defined($gene)) { $names{'generation'} = $gene; }
8381: if ($email) {
8382: $email=~s/[^\w\@\.\-\,]//gs;
8383: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
8384: }
8385: if ($uid) { $names{'id'} = $uid; }
8386: if (defined($inststatus)) {
8387: $names{'inststatus'} = '';
8388: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8389: if (ref($usertypes) eq 'HASH') {
8390: my @okstatuses;
8391: foreach my $item (split(/:/,$inststatus)) {
8392: if (defined($usertypes->{$item})) {
8393: push(@okstatuses,$item);
8394: }
8395: }
8396: if (@okstatuses) {
8397: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8398: }
8399: }
8400: }
8401: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
8402: $umode.', '.$first.', '.$middle.', '.
8403: $last.', '.$gene.', '.$email.', '.$inststatus;
8404: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8405: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8406: } else {
8407: $logmsg .= ' during self creation';
8408: }
8409: my $changed;
8410: if ($newuser) {
8411: $changed = 1;
8412: } else {
8413: foreach my $field (@fields) {
8414: if ($names{$field} ne $oldnames{$field}) {
8415: $changed = 1;
8416: last;
8417: }
8418: }
8419: }
8420: unless ($changed) {
8421: $logmsg = 'No changes in user information needed for: '.$logmsg;
8422: &logthis($logmsg);
8423: return 'ok';
8424: }
8425: my $reply = &put('environment', \%names, $udom,$uname);
8426: if ($reply ne 'ok') {
8427: return 'error: '.$reply;
8428: }
8429: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8430: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8431: }
8432: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8433: &devalidate_cache_new('namescache',$uname.':'.$udom);
8434: $logmsg = 'Success modifying user '.$logmsg;
8435: &logthis($logmsg);
8436: return 'ok';
8437: }
8438:
8439: # -------------------------------------------------------------- Modify student
8440:
8441: sub modifystudent {
8442: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
8443: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
8444: $selfenroll,$context,$inststatus,$credits)=@_;
8445: if (!$cid) {
8446: unless ($cid=$env{'request.course.id'}) {
8447: return 'not_in_class';
8448: }
8449: }
8450: # --------------------------------------------------------------- Make the user
8451: my $reply=&modifyuser
8452: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
8453: $desiredhome,$email,$inststatus);
8454: unless ($reply eq 'ok') { return $reply; }
8455: # This will cause &modify_student_enrollment to get the uid from the
8456: # students environment
8457: $uid = undef if (!$forceid);
8458: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
8459: $gene,$usec,$end,$start,$type,$locktype,
8460: $cid,$selfenroll,$context,$credits);
8461: return $reply;
8462: }
8463:
8464: sub modify_student_enrollment {
8465: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8466: $locktype,$cid,$selfenroll,$context,$credits) = @_;
8467: my ($cdom,$cnum,$chome);
8468: if (!$cid) {
8469: unless ($cid=$env{'request.course.id'}) {
8470: return 'not_in_class';
8471: }
8472: $cdom=$env{'course.'.$cid.'.domain'};
8473: $cnum=$env{'course.'.$cid.'.num'};
8474: } else {
8475: ($cdom,$cnum)=split(/_/,$cid);
8476: }
8477: $chome=$env{'course.'.$cid.'.home'};
8478: if (!$chome) {
8479: $chome=&homeserver($cnum,$cdom);
8480: }
8481: if (!$chome) { return 'unknown_course'; }
8482: # Make sure the user exists
8483: my $uhome=&homeserver($uname,$udom);
8484: if (($uhome eq '') || ($uhome eq 'no_host')) {
8485: return 'error: no such user';
8486: }
8487: # Get student data if we were not given enough information
8488: if (!defined($first) || $first eq '' ||
8489: !defined($last) || $last eq '' ||
8490: !defined($uid) || $uid eq '' ||
8491: !defined($middle) || $middle eq '' ||
8492: !defined($gene) || $gene eq '') {
8493: # They did not supply us with enough data to enroll the student, so
8494: # we need to pick up more information.
8495: my %tmp = &get('environment',
8496: ['firstname','middlename','lastname', 'generation','id']
8497: ,$udom,$uname);
8498:
8499: #foreach my $key (keys(%tmp)) {
8500: # &logthis("key $key = ".$tmp{$key});
8501: #}
8502: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8503: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8504: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
8505: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
8506: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8507: }
8508: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
8509: my $user = "$uname:$udom";
8510: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
8511: my $reply=cput('classlist',
8512: {$user =>
8513: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
8514: $cdom,$cnum);
8515: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8516: &devalidate_getsection_cache($udom,$uname,$cid);
8517: } else {
8518: return 'error: '.$reply;
8519: }
8520: # Add student role to user
8521: my $uurl='/'.$cid;
8522: $uurl=~s/\_/\//g;
8523: if ($usec) {
8524: $uurl.='/'.$usec;
8525: }
8526: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8527: $selfenroll,$context);
8528: if ($result ne 'ok') {
8529: if ($old_entry{$user} ne '') {
8530: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8531: } else {
8532: $reply = &del('classlist',[$user],$cdom,$cnum);
8533: }
8534: }
8535: return $result;
8536: }
8537:
8538: sub format_name {
8539: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8540: my $name;
8541: if ($first ne 'lastname') {
8542: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8543: } else {
8544: if ($lastname=~/\S/) {
8545: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8546: $name=~s/\s+,/,/;
8547: } else {
8548: $name.= $firstname.' '.$middlename.' '.$generation;
8549: }
8550: }
8551: $name=~s/^\s+//;
8552: $name=~s/\s+$//;
8553: $name=~s/\s+/ /g;
8554: return $name;
8555: }
8556:
8557: # ------------------------------------------------- Write to course preferences
8558:
8559: sub writecoursepref {
8560: my ($courseid,%prefs)=@_;
8561: $courseid=~s/^\///;
8562: $courseid=~s/\_/\//g;
8563: my ($cdomain,$cnum)=split(/\//,$courseid);
8564: my $chome=homeserver($cnum,$cdomain);
8565: if (($chome eq '') || ($chome eq 'no_host')) {
8566: return 'error: no such course';
8567: }
8568: my $cstring='';
8569: foreach my $pref (keys(%prefs)) {
8570: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
8571: }
8572: $cstring=~s/\&$//;
8573: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8574: }
8575:
8576: # ---------------------------------------------------------- Make/modify course
8577:
8578: sub createcourse {
8579: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
8580: $course_owner,$crstype,$cnum,$context,$category)=@_;
8581: $url=&declutter($url);
8582: my $cid='';
8583: if ($context eq 'requestcourses') {
8584: my $can_create = 0;
8585: my ($ownername,$ownerdom) = split(':',$course_owner);
8586: if ($udom eq $ownerdom) {
8587: if (&usertools_access($ownername,$ownerdom,$category,undef,
8588: $context)) {
8589: $can_create = 1;
8590: }
8591: } else {
8592: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8593: $category);
8594: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8595: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8596: if (@curr > 0) {
8597: my @options = qw(approval validate autolimit);
8598: my $optregex = join('|',@options);
8599: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8600: $can_create = 1;
8601: }
8602: }
8603: }
8604: }
8605: if ($can_create) {
8606: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8607: unless (&allowed('ccc',$udom)) {
8608: return 'refused';
8609: }
8610: }
8611: } else {
8612: return 'refused';
8613: }
8614: } elsif (!&allowed('ccc',$udom)) {
8615: return 'refused';
8616: }
8617: # --------------------------------------------------------------- Get Unique ID
8618: my $uname;
8619: if ($cnum =~ /^$match_courseid$/) {
8620: my $chome=&homeserver($cnum,$udom,'true');
8621: if (($chome eq '') || ($chome eq 'no_host')) {
8622: $uname = $cnum;
8623: } else {
8624: $uname = &generate_coursenum($udom,$crstype);
8625: }
8626: } else {
8627: $uname = &generate_coursenum($udom,$crstype);
8628: }
8629: return $uname if ($uname =~ /^error/);
8630: # -------------------------------------------------- Check supplied server name
8631: if (!defined($course_server)) {
8632: if (defined(&domain($udom,'primary'))) {
8633: $course_server = &domain($udom,'primary');
8634: } else {
8635: $course_server = $env{'user.home'};
8636: }
8637: }
8638: my %host_servers =
8639: &Apache::lonnet::get_servers($udom,'library');
8640: unless ($host_servers{$course_server}) {
8641: return 'error: invalid home server for course: '.$course_server;
8642: }
8643: # ------------------------------------------------------------- Make the course
8644: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
8645: $course_server);
8646: unless ($reply eq 'ok') { return 'error: '.$reply; }
8647: my $uhome=&homeserver($uname,$udom,'true');
8648: if (($uhome eq '') || ($uhome eq 'no_host')) {
8649: return 'error: no such course';
8650: }
8651: # ----------------------------------------------------------------- Course made
8652: # log existence
8653: my $now = time;
8654: my $newcourse = {
8655: $udom.'_'.$uname => {
8656: description => $description,
8657: inst_code => $inst_code,
8658: owner => $course_owner,
8659: type => $crstype,
8660: creator => $env{'user.name'}.':'.
8661: $env{'user.domain'},
8662: created => $now,
8663: context => $context,
8664: },
8665: };
8666: &courseidput($udom,$newcourse,$uhome,'notime');
8667: # set toplevel url
8668: my $topurl=$url;
8669: unless ($nonstandard) {
8670: # ------------------------------------------ For standard courses, make top url
8671: my $mapurl=&clutter($url);
8672: if ($mapurl eq '/res/') { $mapurl=''; }
8673: $env{'form.initmap'}=(<<ENDINITMAP);
8674: <map>
8675: <resource id="1" type="start"></resource>
8676: <resource id="2" src="$mapurl"></resource>
8677: <resource id="3" type="finish"></resource>
8678: <link index="1" from="1" to="2"></link>
8679: <link index="2" from="2" to="3"></link>
8680: </map>
8681: ENDINITMAP
8682: $topurl=&declutter(
8683: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
8684: );
8685: }
8686: # ----------------------------------------------------------- Write preferences
8687: &writecoursepref($udom.'_'.$uname,
8688: ('description' => $description,
8689: 'url' => $topurl,
8690: 'internal.creator' => $env{'user.name'}.':'.
8691: $env{'user.domain'},
8692: 'internal.created' => $now,
8693: 'internal.creationcontext' => $context)
8694: );
8695: return '/'.$udom.'/'.$uname;
8696: }
8697:
8698: # ------------------------------------------------------------------- Create ID
8699: sub generate_coursenum {
8700: my ($udom,$crstype) = @_;
8701: my $domdesc = &domain($udom);
8702: return 'error: invalid domain' if ($domdesc eq '');
8703: my $first;
8704: if ($crstype eq 'Community') {
8705: $first = '0';
8706: } else {
8707: $first = int(1+rand(9));
8708: }
8709: my $uname=$first.
8710: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8711: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8712: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8713: # ----------------------------------------------- Make sure that does not exist
8714: my $uhome=&homeserver($uname,$udom,'true');
8715: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8716: if ($crstype eq 'Community') {
8717: $first = '0';
8718: } else {
8719: $first = int(1+rand(9));
8720: }
8721: $uname=$first.
8722: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8723: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8724: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8725: $uhome=&homeserver($uname,$udom,'true');
8726: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8727: return 'error: unable to generate unique course-ID';
8728: }
8729: }
8730: return $uname;
8731: }
8732:
8733: sub is_course {
8734: my ($cdom, $cnum) = scalar(@_) == 1 ?
8735: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8736:
8737: return unless $cdom and $cnum;
8738:
8739: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8740: '.');
8741:
8742: return unless(exists($courses{$cdom.'_'.$cnum}));
8743: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
8744: }
8745:
8746: sub store_userdata {
8747: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
8748: my $result;
8749: if ($datakey ne '') {
8750: if (ref($storehash) eq 'HASH') {
8751: if ($udom eq '' || $uname eq '') {
8752: $udom = $env{'user.domain'};
8753: $uname = $env{'user.name'};
8754: }
8755: my $uhome=&homeserver($uname,$udom);
8756: if (($uhome eq '') || ($uhome eq 'no_host')) {
8757: $result = 'error: no_host';
8758: } else {
8759: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8760: $storehash->{'host'} = $perlvar{'lonHostID'};
8761:
8762: my $namevalue='';
8763: foreach my $key (keys(%{$storehash})) {
8764: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8765: }
8766: $namevalue=~s/\&$//;
8767: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8768: $namevalue,$uhome);
8769: }
8770: } else {
8771: $result = 'error: data to store was not a hash reference';
8772: }
8773: } else {
8774: $result= 'error: invalid requestkey';
8775: }
8776: return $result;
8777: }
8778:
8779: # ---------------------------------------------------------- Assign Custom Role
8780:
8781: sub assigncustomrole {
8782: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
8783: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
8784: $end,$start,$deleteflag,$selfenroll,$context);
8785: }
8786:
8787: # ----------------------------------------------------------------- Revoke Role
8788:
8789: sub revokerole {
8790: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
8791: my $now=time;
8792: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
8793: }
8794:
8795: # ---------------------------------------------------------- Revoke Custom Role
8796:
8797: sub revokecustomrole {
8798: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
8799: my $now=time;
8800: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
8801: $deleteflag,$selfenroll,$context);
8802: }
8803:
8804: # ------------------------------------------------------------ Disk usage
8805: sub diskusage {
8806: my ($udom,$uname,$directorypath,$getpropath)=@_;
8807: $directorypath =~ s/\/$//;
8808: my $listing=&reply('du2:'.&escape($directorypath).':'
8809: .&escape($getpropath).':'.&escape($uname).':'
8810: .&escape($udom),homeserver($uname,$udom));
8811: if ($listing eq 'unknown_cmd') {
8812: if ($getpropath) {
8813: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8814: }
8815: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8816: }
8817: return $listing;
8818: }
8819:
8820: sub is_locked {
8821: my ($file_name, $domain, $user, $which) = @_;
8822: my @check;
8823: my $is_locked;
8824: push (@check,$file_name);
8825: my %locked = &get('file_permissions',\@check,
8826: $env{'user.domain'},$env{'user.name'});
8827: my ($tmp)=keys(%locked);
8828: if ($tmp=~/^error:/) { undef(%locked); }
8829:
8830: if (ref($locked{$file_name}) eq 'ARRAY') {
8831: $is_locked = 'false';
8832: foreach my $entry (@{$locked{$file_name}}) {
8833: if (ref($entry) eq 'ARRAY') {
8834: $is_locked = 'true';
8835: if (ref($which) eq 'ARRAY') {
8836: push(@{$which},$entry);
8837: } else {
8838: last;
8839: }
8840: }
8841: }
8842: } else {
8843: $is_locked = 'false';
8844: }
8845: return $is_locked;
8846: }
8847:
8848: sub declutter_portfile {
8849: my ($file) = @_;
8850: $file =~ s{^(/portfolio/|portfolio/)}{/};
8851: return $file;
8852: }
8853:
8854: # ------------------------------------------------------------- Mark as Read Only
8855:
8856: sub mark_as_readonly {
8857: my ($domain,$user,$files,$what) = @_;
8858: my %current_permissions = &dump('file_permissions',$domain,$user);
8859: my ($tmp)=keys(%current_permissions);
8860: if ($tmp=~/^error:/) { undef(%current_permissions); }
8861: foreach my $file (@{$files}) {
8862: $file = &declutter_portfile($file);
8863: push(@{$current_permissions{$file}},$what);
8864: }
8865: &put('file_permissions',\%current_permissions,$domain,$user);
8866: return;
8867: }
8868:
8869: # ------------------------------------------------------------Save Selected Files
8870:
8871: sub save_selected_files {
8872: my ($user, $path, @files) = @_;
8873: my $filename = $user."savedfiles";
8874: my @other_files = &files_not_in_path($user, $path);
8875: open (OUT, '>'.$tmpdir.$filename);
8876: foreach my $file (@files) {
8877: print (OUT $env{'form.currentpath'}.$file."\n");
8878: }
8879: foreach my $file (@other_files) {
8880: print (OUT $file."\n");
8881: }
8882: close (OUT);
8883: return 'ok';
8884: }
8885:
8886: sub clear_selected_files {
8887: my ($user) = @_;
8888: my $filename = $user."savedfiles";
8889: open (OUT, '>'.LONCAPA::tempdir().$filename);
8890: print (OUT undef);
8891: close (OUT);
8892: return ("ok");
8893: }
8894:
8895: sub files_in_path {
8896: my ($user, $path) = @_;
8897: my $filename = $user."savedfiles";
8898: my %return_files;
8899: open (IN, '<'.LONCAPA::tempdir().$filename);
8900: while (my $line_in = <IN>) {
8901: chomp ($line_in);
8902: my @paths_and_file = split (m!/!, $line_in);
8903: my $file_part = pop (@paths_and_file);
8904: my $path_part = join ('/', @paths_and_file);
8905: $path_part.='/';
8906: my $path_and_file = $path_part.$file_part;
8907: if ($path_part eq $path) {
8908: $return_files{$file_part}= 'selected';
8909: }
8910: }
8911: close (IN);
8912: return (\%return_files);
8913: }
8914:
8915: # called in portfolio select mode, to show files selected NOT in current directory
8916: sub files_not_in_path {
8917: my ($user, $path) = @_;
8918: my $filename = $user."savedfiles";
8919: my @return_files;
8920: my $path_part;
8921: open(IN, '<'.LONCAPA::.$filename);
8922: while (my $line = <IN>) {
8923: #ok, I know it's clunky, but I want it to work
8924: my @paths_and_file = split(m|/|, $line);
8925: my $file_part = pop(@paths_and_file);
8926: chomp($file_part);
8927: my $path_part = join('/', @paths_and_file);
8928: $path_part .= '/';
8929: my $path_and_file = $path_part.$file_part;
8930: if ($path_part ne $path) {
8931: push(@return_files, ($path_and_file));
8932: }
8933: }
8934: close(OUT);
8935: return (@return_files);
8936: }
8937:
8938: #----------------------------------------------Get portfolio file permissions
8939:
8940: sub get_portfile_permissions {
8941: my ($domain,$user) = @_;
8942: my %current_permissions = &dump('file_permissions',$domain,$user);
8943: my ($tmp)=keys(%current_permissions);
8944: if ($tmp=~/^error:/) { undef(%current_permissions); }
8945: return \%current_permissions;
8946: }
8947:
8948: #---------------------------------------------Get portfolio file access controls
8949:
8950: sub get_access_controls {
8951: my ($current_permissions,$group,$file) = @_;
8952: my %access;
8953: my $real_file = $file;
8954: $file =~ s/\.meta$//;
8955: if (defined($file)) {
8956: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
8957: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
8958: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
8959: }
8960: }
8961: } else {
8962: foreach my $key (keys(%{$current_permissions})) {
8963: if ($key =~ /\0accesscontrol$/) {
8964: if (defined($group)) {
8965: if ($key !~ m-^\Q$group\E/-) {
8966: next;
8967: }
8968: }
8969: my ($fullpath) = split(/\0/,$key);
8970: if (ref($$current_permissions{$key}) eq 'HASH') {
8971: foreach my $control (keys(%{$$current_permissions{$key}})) {
8972: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
8973: }
8974: }
8975: }
8976: }
8977: }
8978: return %access;
8979: }
8980:
8981: sub modify_access_controls {
8982: my ($file_name,$changes,$domain,$user)=@_;
8983: my ($outcome,$deloutcome);
8984: my %store_permissions;
8985: my %new_values;
8986: my %new_control;
8987: my %translation;
8988: my @deletions = ();
8989: my $now = time;
8990: if (exists($$changes{'activate'})) {
8991: if (ref($$changes{'activate'}) eq 'HASH') {
8992: my @newitems = sort(keys(%{$$changes{'activate'}}));
8993: my $numnew = scalar(@newitems);
8994: for (my $i=0; $i<$numnew; $i++) {
8995: my $newkey = $newitems[$i];
8996: my $newid = &Apache::loncommon::get_cgi_id();
8997: if ($newkey =~ /^\d+:/) {
8998: $newkey =~ s/^(\d+)/$newid/;
8999: $translation{$1} = $newid;
9000: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9001: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9002: $translation{$1} = $newid;
9003: }
9004: $new_values{$file_name."\0".$newkey} =
9005: $$changes{'activate'}{$newitems[$i]};
9006: $new_control{$newkey} = $now;
9007: }
9008: }
9009: }
9010: my %todelete;
9011: my %changed_items;
9012: foreach my $action ('delete','update') {
9013: if (exists($$changes{$action})) {
9014: if (ref($$changes{$action}) eq 'HASH') {
9015: foreach my $key (keys(%{$$changes{$action}})) {
9016: my ($itemnum) = ($key =~ /^([^:]+):/);
9017: if ($action eq 'delete') {
9018: $todelete{$itemnum} = 1;
9019: } else {
9020: $changed_items{$itemnum} = $key;
9021: }
9022: }
9023: }
9024: }
9025: }
9026: # get lock on access controls for file.
9027: my $lockhash = {
9028: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9029: ':'.$env{'user.domain'},
9030: };
9031: my $tries = 0;
9032: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9033:
9034: while (($gotlock ne 'ok') && $tries <3) {
9035: $tries ++;
9036: sleep 1;
9037: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9038: }
9039: if ($gotlock eq 'ok') {
9040: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9041: my ($tmp)=keys(%curr_permissions);
9042: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9043: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9044: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9045: if (ref($curr_controls) eq 'HASH') {
9046: foreach my $control_item (keys(%{$curr_controls})) {
9047: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9048: if (defined($todelete{$itemnum})) {
9049: push(@deletions,$file_name."\0".$control_item);
9050: } else {
9051: if (defined($changed_items{$itemnum})) {
9052: $new_control{$changed_items{$itemnum}} = $now;
9053: push(@deletions,$file_name."\0".$control_item);
9054: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9055: } else {
9056: $new_control{$control_item} = $$curr_controls{$control_item};
9057: }
9058: }
9059: }
9060: }
9061: }
9062: my ($group);
9063: if (&is_course($domain,$user)) {
9064: ($group,my $file) = split(/\//,$file_name,2);
9065: }
9066: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9067: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9068: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9069: # remove lock
9070: my @del_lock = ($file_name."\0".'locked_access_records');
9071: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
9072: my $sqlresult =
9073: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
9074: $group);
9075: } else {
9076: $outcome = "error: could not obtain lockfile\n";
9077: }
9078: return ($outcome,$deloutcome,\%new_values,\%translation);
9079: }
9080:
9081: sub make_public_indefinitely {
9082: my ($requrl) = @_;
9083: my $now = time;
9084: my $action = 'activate';
9085: my $aclnum = 0;
9086: if (&is_portfolio_url($requrl)) {
9087: my (undef,$udom,$unum,$file_name,$group) =
9088: &parse_portfolio_url($requrl);
9089: my $current_perms = &get_portfile_permissions($udom,$unum);
9090: my %access_controls = &get_access_controls($current_perms,
9091: $group,$file_name);
9092: foreach my $key (keys(%{$access_controls{$file_name}})) {
9093: my ($num,$scope,$end,$start) =
9094: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9095: if ($scope eq 'public') {
9096: if ($start <= $now && $end == 0) {
9097: $action = 'none';
9098: } else {
9099: $action = 'update';
9100: $aclnum = $num;
9101: }
9102: last;
9103: }
9104: }
9105: if ($action eq 'none') {
9106: return 'ok';
9107: } else {
9108: my %changes;
9109: my $newend = 0;
9110: my $newstart = $now;
9111: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9112: $changes{$action}{$newkey} = {
9113: type => 'public',
9114: time => {
9115: start => $newstart,
9116: end => $newend,
9117: },
9118: };
9119: my ($outcome,$deloutcome,$new_values,$translation) =
9120: &modify_access_controls($file_name,\%changes,$udom,$unum);
9121: return $outcome;
9122: }
9123: } else {
9124: return 'invalid';
9125: }
9126: }
9127:
9128: #------------------------------------------------------Get Marked as Read Only
9129:
9130: sub get_marked_as_readonly {
9131: my ($domain,$user,$what,$group) = @_;
9132: my $current_permissions = &get_portfile_permissions($domain,$user);
9133: my @readonly_files;
9134: my $cmp1=$what;
9135: if (ref($what)) { $cmp1=join('',@{$what}) };
9136: while (my ($file_name,$value) = each(%{$current_permissions})) {
9137: if (defined($group)) {
9138: if ($file_name !~ m-^\Q$group\E/-) {
9139: next;
9140: }
9141: }
9142: if (ref($value) eq "ARRAY"){
9143: foreach my $stored_what (@{$value}) {
9144: my $cmp2=$stored_what;
9145: if (ref($stored_what) eq 'ARRAY') {
9146: $cmp2=join('',@{$stored_what});
9147: }
9148: if ($cmp1 eq $cmp2) {
9149: push(@readonly_files, $file_name);
9150: last;
9151: } elsif (!defined($what)) {
9152: push(@readonly_files, $file_name);
9153: last;
9154: }
9155: }
9156: }
9157: }
9158: return @readonly_files;
9159: }
9160: #-----------------------------------------------------------Get Marked as Read Only Hash
9161:
9162: sub get_marked_as_readonly_hash {
9163: my ($current_permissions,$group,$what) = @_;
9164: my %readonly_files;
9165: while (my ($file_name,$value) = each(%{$current_permissions})) {
9166: if (defined($group)) {
9167: if ($file_name !~ m-^\Q$group\E/-) {
9168: next;
9169: }
9170: }
9171: if (ref($value) eq "ARRAY"){
9172: foreach my $stored_what (@{$value}) {
9173: if (ref($stored_what) eq 'ARRAY') {
9174: foreach my $lock_descriptor(@{$stored_what}) {
9175: if ($lock_descriptor eq 'graded') {
9176: $readonly_files{$file_name} = 'graded';
9177: } elsif ($lock_descriptor eq 'handback') {
9178: $readonly_files{$file_name} = 'handback';
9179: } else {
9180: if (!exists($readonly_files{$file_name})) {
9181: $readonly_files{$file_name} = 'locked';
9182: }
9183: }
9184: }
9185: }
9186: }
9187: }
9188: }
9189: return %readonly_files;
9190: }
9191: # ------------------------------------------------------------ Unmark as Read Only
9192:
9193: sub unmark_as_readonly {
9194: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9195: # for portfolio submissions, $what contains [$symb,$crsid]
9196: my ($domain,$user,$what,$file_name,$group) = @_;
9197: $file_name = &declutter_portfile($file_name);
9198: my $symb_crs = $what;
9199: if (ref($what)) { $symb_crs=join('',@$what); }
9200: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
9201: my ($tmp)=keys(%current_permissions);
9202: if ($tmp=~/^error:/) { undef(%current_permissions); }
9203: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
9204: foreach my $file (@readonly_files) {
9205: my $clean_file = &declutter_portfile($file);
9206: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
9207: my $current_locks = $current_permissions{$file};
9208: my @new_locks;
9209: my @del_keys;
9210: if (ref($current_locks) eq "ARRAY"){
9211: foreach my $locker (@{$current_locks}) {
9212: my $compare=$locker;
9213: if (ref($locker) eq 'ARRAY') {
9214: $compare=join('',@{$locker});
9215: if ($compare ne $symb_crs) {
9216: push(@new_locks, $locker);
9217: }
9218: }
9219: }
9220: if (scalar(@new_locks) > 0) {
9221: $current_permissions{$file} = \@new_locks;
9222: } else {
9223: push(@del_keys, $file);
9224: &del('file_permissions',\@del_keys, $domain, $user);
9225: delete($current_permissions{$file});
9226: }
9227: }
9228: }
9229: &put('file_permissions',\%current_permissions,$domain,$user);
9230: return;
9231: }
9232:
9233: # ------------------------------------------------------------ Directory lister
9234:
9235: sub dirlist {
9236: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
9237: $uri=~s/^\///;
9238: $uri=~s/\/$//;
9239: my ($udom, $uname);
9240: if ($getuserdir) {
9241: $udom = $userdomain;
9242: $uname = $username;
9243: } else {
9244: (undef,$udom,$uname)=split(/\//,$uri);
9245: if(defined($userdomain)) {
9246: $udom = $userdomain;
9247: }
9248: if(defined($username)) {
9249: $uname = $username;
9250: }
9251: }
9252: my ($dirRoot,$listing,@listing_results);
9253:
9254: $dirRoot = $perlvar{'lonDocRoot'};
9255: if (defined($getpropath)) {
9256: $dirRoot = &propath($udom,$uname);
9257: $dirRoot =~ s/\/$//;
9258: } elsif (defined($getuserdir)) {
9259: my $subdir=$uname.'__';
9260: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9261: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9262: ."/$udom/$subdir/$uname";
9263: } elsif (defined($alternateRoot)) {
9264: $dirRoot = $alternateRoot;
9265: }
9266:
9267: if($udom) {
9268: if($uname) {
9269: my $uhome = &homeserver($uname,$udom);
9270: if ($uhome eq 'no_host') {
9271: return ([],'no_host');
9272: }
9273: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
9274: .$getuserdir.':'.&escape($dirRoot)
9275: .':'.&escape($uname).':'.&escape($udom),$uhome);
9276: if ($listing eq 'unknown_cmd') {
9277: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
9278: } else {
9279: @listing_results = map { &unescape($_); } split(/:/,$listing);
9280: }
9281: if ($listing eq 'unknown_cmd') {
9282: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
9283: @listing_results = split(/:/,$listing);
9284: } else {
9285: @listing_results = map { &unescape($_); } split(/:/,$listing);
9286: }
9287: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9288: ($listing eq 'rejected') || ($listing eq 'refused') ||
9289: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9290: return ([],$listing);
9291: } else {
9292: return (\@listing_results);
9293: }
9294: } elsif(!$alternateRoot) {
9295: my (%allusers,%listerror);
9296: my %servers = &get_servers($udom,'library');
9297: foreach my $tryserver (keys(%servers)) {
9298: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9299: &escape($udom),$tryserver);
9300: if ($listing eq 'unknown_cmd') {
9301: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9302: $udom, $tryserver);
9303: } else {
9304: @listing_results = map { &unescape($_); } split(/:/,$listing);
9305: }
9306: if ($listing eq 'unknown_cmd') {
9307: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9308: $udom, $tryserver);
9309: @listing_results = split(/:/,$listing);
9310: } else {
9311: @listing_results =
9312: map { &unescape($_); } split(/:/,$listing);
9313: }
9314: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9315: ($listing eq 'rejected') || ($listing eq 'refused') ||
9316: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9317: $listerror{$tryserver} = $listing;
9318: } else {
9319: foreach my $line (@listing_results) {
9320: my ($entry) = split(/&/,$line,2);
9321: $allusers{$entry} = 1;
9322: }
9323: }
9324: }
9325: my @alluserslist=();
9326: foreach my $user (sort(keys(%allusers))) {
9327: push(@alluserslist,$user.'&user');
9328: }
9329: return (\@alluserslist);
9330: } else {
9331: return ([],'missing username');
9332: }
9333: } elsif(!defined($getpropath)) {
9334: my $path = $perlvar{'lonDocRoot'}.'/res/';
9335: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9336: return (\@all_domains);
9337: } else {
9338: return ([],'missing domain');
9339: }
9340: }
9341:
9342: # --------------------------------------------- GetFileTimestamp
9343: # This function utilizes dirlist and returns the date stamp for
9344: # when it was last modified. It will also return an error of -1
9345: # if an error occurs
9346:
9347: sub GetFileTimestamp {
9348: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
9349: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9350: $studentName = &LONCAPA::clean_username($studentName);
9351: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9352: undef,$getuserdir);
9353: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9354: return -1;
9355: }
9356: if (ref($fileref) eq 'ARRAY') {
9357: my @stats = split('&',$fileref->[0]);
9358: # @stats contains first the filename, then the stat output
9359: return $stats[10]; # so this is 10 instead of 9.
9360: } else {
9361: return -1;
9362: }
9363: }
9364:
9365: sub stat_file {
9366: my ($uri) = @_;
9367: $uri = &clutter_with_no_wrapper($uri);
9368:
9369: my ($udom,$uname,$file);
9370: if ($uri =~ m-^/(uploaded|editupload)/-) {
9371: ($udom,$uname,$file) =
9372: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
9373: $file = 'userfiles/'.$file;
9374: }
9375: if ($uri =~ m-^/res/-) {
9376: ($udom,$uname) =
9377: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
9378: $file = $uri;
9379: }
9380:
9381: if (!$udom || !$uname || !$file) {
9382: # unable to handle the uri
9383: return ();
9384: }
9385: my $getpropath;
9386: if ($file =~ /^userfiles\//) {
9387: $getpropath = 1;
9388: }
9389: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9390: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9391: return ();
9392: } else {
9393: if (ref($listref) eq 'ARRAY') {
9394: my @stats = split('&',$listref->[0]);
9395: shift(@stats); #filename is first
9396: return @stats;
9397: }
9398: }
9399: return ();
9400: }
9401:
9402: # -------------------------------------------------------- Value of a Condition
9403:
9404: # gets the value of a specific preevaluated condition
9405: # stored in the string $env{user.state.<cid>}
9406: # or looks up a condition reference in the bighash and if if hasn't
9407: # already been evaluated recurses into docondval to get the value of
9408: # the condition, then memoizing it to
9409: # $env{user.state.<cid>.<condition>}
9410: sub directcondval {
9411: my $number=shift;
9412: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
9413: &Apache::lonuserstate::evalstate();
9414: }
9415: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9416: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9417: } elsif ($number =~ /^_/) {
9418: my $sub_condition;
9419: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9420: &GDBM_READER(),0640)) {
9421: $sub_condition=$bighash{'conditions'.$number};
9422: untie(%bighash);
9423: }
9424: my $value = &docondval($sub_condition);
9425: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
9426: return $value;
9427: }
9428: if ($env{'user.state.'.$env{'request.course.id'}}) {
9429: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
9430: } else {
9431: return 2;
9432: }
9433: }
9434:
9435: # get the collection of conditions for this resource
9436: sub condval {
9437: my $condidx=shift;
9438: my $allpathcond='';
9439: foreach my $cond (split(/\|/,$condidx)) {
9440: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9441: $allpathcond.=
9442: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9443: }
9444: }
9445: $allpathcond=~s/\|$//;
9446: return &docondval($allpathcond);
9447: }
9448:
9449: #evaluates an expression of conditions
9450: sub docondval {
9451: my ($allpathcond) = @_;
9452: my $result=0;
9453: if ($env{'request.course.id'}
9454: && defined($allpathcond)) {
9455: my $operand='|';
9456: my @stack;
9457: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9458: if ($chunk eq '(') {
9459: push @stack,($operand,$result);
9460: } elsif ($chunk eq ')') {
9461: my $before=pop @stack;
9462: if (pop @stack eq '&') {
9463: $result=$result>$before?$before:$result;
9464: } else {
9465: $result=$result>$before?$result:$before;
9466: }
9467: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9468: $operand=$chunk;
9469: } else {
9470: my $new=directcondval($chunk);
9471: if ($operand eq '&') {
9472: $result=$result>$new?$new:$result;
9473: } else {
9474: $result=$result>$new?$result:$new;
9475: }
9476: }
9477: }
9478: }
9479: return $result;
9480: }
9481:
9482: # ---------------------------------------------------- Devalidate courseresdata
9483:
9484: sub devalidatecourseresdata {
9485: my ($coursenum,$coursedomain)=@_;
9486: my $hashid=$coursenum.':'.$coursedomain;
9487: &devalidate_cache_new('courseres',$hashid);
9488: }
9489:
9490:
9491: # --------------------------------------------------- Course Resourcedata Query
9492: #
9493: # Parameters:
9494: # $coursenum - Number of the course.
9495: # $coursedomain - Domain at which the course was created.
9496: # Returns:
9497: # A hash of the course parameters along (I think) with timestamps
9498: # and version info.
9499:
9500: sub get_courseresdata {
9501: my ($coursenum,$coursedomain)=@_;
9502: my $coursehom=&homeserver($coursenum,$coursedomain);
9503: my $hashid=$coursenum.':'.$coursedomain;
9504: my ($result,$cached)=&is_cached_new('courseres',$hashid);
9505: my %dumpreply;
9506: unless (defined($cached)) {
9507: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
9508: $result=\%dumpreply;
9509: my ($tmp) = keys(%dumpreply);
9510: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9511: &do_cache_new('courseres',$hashid,$result,600);
9512: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9513: return $tmp;
9514: } elsif ($tmp =~ /^(error)/) {
9515: $result=undef;
9516: &do_cache_new('courseres',$hashid,$result,600);
9517: }
9518: }
9519: return $result;
9520: }
9521:
9522: sub devalidateuserresdata {
9523: my ($uname,$udom)=@_;
9524: my $hashid="$udom:$uname";
9525: &devalidate_cache_new('userres',$hashid);
9526: }
9527:
9528: sub get_userresdata {
9529: my ($uname,$udom)=@_;
9530: #most student don\'t have any data set, check if there is some data
9531: if (&EXT_cache_status($udom,$uname)) { return undef; }
9532:
9533: my $hashid="$udom:$uname";
9534: my ($result,$cached)=&is_cached_new('userres',$hashid);
9535: if (!defined($cached)) {
9536: my %resourcedata=&dump('resourcedata',$udom,$uname);
9537: $result=\%resourcedata;
9538: &do_cache_new('userres',$hashid,$result,600);
9539: }
9540: my ($tmp)=keys(%$result);
9541: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9542: return $result;
9543: }
9544: #error 2 occurs when the .db doesn't exist
9545: if ($tmp!~/error: 2 /) {
9546: &logthis("<font color=\"blue\">WARNING:".
9547: " Trying to get resource data for ".
9548: $uname." at ".$udom.": ".
9549: $tmp."</font>");
9550: } elsif ($tmp=~/error: 2 /) {
9551: #&EXT_cache_set($udom,$uname);
9552: &do_cache_new('userres',$hashid,undef,600);
9553: undef($tmp); # not really an error so don't send it back
9554: }
9555: return $tmp;
9556: }
9557: #----------------------------------------------- resdata - return resource data
9558: # Purpose:
9559: # Return resource data for either users or for a course.
9560: # Parameters:
9561: # $name - Course/user name.
9562: # $domain - Name of the domain the user/course is registered on.
9563: # $type - Type of thing $name is (must be 'course' or 'user'
9564: # @which - Array of names of resources desired.
9565: # Returns:
9566: # The value of the first reasource in @which that is found in the
9567: # resource hash.
9568: # Exceptional Conditions:
9569: # If the $type passed in is not valid (not the string 'course' or
9570: # 'user', an undefined reference is returned.
9571: # If none of the resources are found, an undef is returned
9572: sub resdata {
9573: my ($name,$domain,$type,@which)=@_;
9574: my $result;
9575: if ($type eq 'course') {
9576: $result=&get_courseresdata($name,$domain);
9577: } elsif ($type eq 'user') {
9578: $result=&get_userresdata($name,$domain);
9579: }
9580: if (!ref($result)) { return $result; }
9581: foreach my $item (@which) {
9582: if (defined($result->{$item->[0]})) {
9583: return [$result->{$item->[0]},$item->[1]];
9584: }
9585: }
9586: return undef;
9587: }
9588:
9589: #
9590: # EXT resource caching routines
9591: #
9592:
9593: sub clear_EXT_cache_status {
9594: &delenv('cache.EXT.');
9595: }
9596:
9597: sub EXT_cache_status {
9598: my ($target_domain,$target_user) = @_;
9599: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
9600: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
9601: # We know already the user has no data
9602: return 1;
9603: } else {
9604: return 0;
9605: }
9606: }
9607:
9608: sub EXT_cache_set {
9609: my ($target_domain,$target_user) = @_;
9610: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
9611: #&appenv({$cachename => time});
9612: }
9613:
9614: # --------------------------------------------------------- Value of a Variable
9615: sub EXT {
9616:
9617: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
9618: unless ($varname) { return ''; }
9619: #get real user name/domain, courseid and symb
9620: my $courseid;
9621: my $publicuser;
9622: if ($symbparm) {
9623: $symbparm=&get_symb_from_alias($symbparm);
9624: }
9625: if (!($uname && $udom)) {
9626: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
9627: if (!$symbparm) { $symbparm=$cursymb; }
9628: } else {
9629: $courseid=$env{'request.course.id'};
9630: }
9631: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9632: my $rest;
9633: if (defined($therest[0])) {
9634: $rest=join('.',@therest);
9635: } else {
9636: $rest='';
9637: }
9638:
9639: my $qualifierrest=$qualifier;
9640: if ($rest) { $qualifierrest.='.'.$rest; }
9641: my $spacequalifierrest=$space;
9642: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
9643: if ($realm eq 'user') {
9644: # --------------------------------------------------------------- user.resource
9645: if ($space eq 'resource') {
9646: if ( (defined($Apache::lonhomework::parsing_a_problem)
9647: || defined($Apache::lonhomework::parsing_a_task))
9648: &&
9649: ($symbparm eq &symbread()) ) {
9650: # if we are in the middle of processing the resource the
9651: # get the value we are planning on committing
9652: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9653: return $Apache::lonhomework::results{$qualifierrest};
9654: } else {
9655: return $Apache::lonhomework::history{$qualifierrest};
9656: }
9657: } else {
9658: my %restored;
9659: if ($publicuser || $env{'request.state'} eq 'construct') {
9660: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9661: } else {
9662: %restored=&restore($symbparm,$courseid,$udom,$uname);
9663: }
9664: return $restored{$qualifierrest};
9665: }
9666: # ----------------------------------------------------------------- user.access
9667: } elsif ($space eq 'access') {
9668: # FIXME - not supporting calls for a specific user
9669: return &allowed($qualifier,$rest);
9670: # ------------------------------------------ user.preferences, user.environment
9671: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
9672: if (($uname eq $env{'user.name'}) &&
9673: ($udom eq $env{'user.domain'})) {
9674: return $env{join('.',('environment',$qualifierrest))};
9675: } else {
9676: my %returnhash;
9677: if (!$publicuser) {
9678: %returnhash=&userenvironment($udom,$uname,
9679: $qualifierrest);
9680: }
9681: return $returnhash{$qualifierrest};
9682: }
9683: # ----------------------------------------------------------------- user.course
9684: } elsif ($space eq 'course') {
9685: # FIXME - not supporting calls for a specific user
9686: return $env{join('.',('request.course',$qualifier))};
9687: # ------------------------------------------------------------------- user.role
9688: } elsif ($space eq 'role') {
9689: # FIXME - not supporting calls for a specific user
9690: my ($role,$where)=split(/\./,$env{'request.role'});
9691: if ($qualifier eq 'value') {
9692: return $role;
9693: } elsif ($qualifier eq 'extent') {
9694: return $where;
9695: }
9696: # ----------------------------------------------------------------- user.domain
9697: } elsif ($space eq 'domain') {
9698: return $udom;
9699: # ------------------------------------------------------------------- user.name
9700: } elsif ($space eq 'name') {
9701: return $uname;
9702: # ---------------------------------------------------- Any other user namespace
9703: } else {
9704: my %reply;
9705: if (!$publicuser) {
9706: %reply=&get($space,[$qualifierrest],$udom,$uname);
9707: }
9708: return $reply{$qualifierrest};
9709: }
9710: } elsif ($realm eq 'query') {
9711: # ---------------------------------------------- pull stuff out of query string
9712: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9713: [$spacequalifierrest]);
9714: return $env{'form.'.$spacequalifierrest};
9715: } elsif ($realm eq 'request') {
9716: # ------------------------------------------------------------- request.browser
9717: if ($space eq 'browser') {
9718: return $env{'browser.'.$qualifier};
9719: # ------------------------------------------------------------ request.filename
9720: } else {
9721: return $env{'request.'.$spacequalifierrest};
9722: }
9723: } elsif ($realm eq 'course') {
9724: # ---------------------------------------------------------- course.description
9725: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
9726: } elsif ($realm eq 'resource') {
9727:
9728: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
9729: if (!$symbparm) { $symbparm=&symbread(); }
9730: }
9731:
9732: if ($space eq 'title') {
9733: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9734: return &gettitle($symbparm);
9735: }
9736:
9737: if ($space eq 'map') {
9738: my ($map) = &decode_symb($symbparm);
9739: return &symbread($map);
9740: }
9741: if ($space eq 'filename') {
9742: if ($symbparm) {
9743: return &clutter((&decode_symb($symbparm))[2]);
9744: }
9745: return &hreflocation('',$env{'request.filename'});
9746: }
9747:
9748: my ($section, $group, @groups);
9749: my ($courselevelm,$courselevel);
9750: if ($symbparm && defined($courseid) &&
9751: $courseid eq $env{'request.course.id'}) {
9752:
9753: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
9754:
9755: # ----------------------------------------------------- Cascading lookup scheme
9756: my $symbp=$symbparm;
9757: my $mapp=&deversion((&decode_symb($symbp))[0]);
9758:
9759: my $symbparm=$symbp.'.'.$spacequalifierrest;
9760: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9761:
9762: if (($env{'user.name'} eq $uname) &&
9763: ($env{'user.domain'} eq $udom)) {
9764: $section=$env{'request.course.sec'};
9765: @groups = split(/:/,$env{'request.course.groups'});
9766: @groups=&sort_course_groups($courseid,@groups);
9767: } else {
9768: if (! defined($usection)) {
9769: $section=&getsection($udom,$uname,$courseid);
9770: } else {
9771: $section = $usection;
9772: }
9773: @groups = &get_users_groups($udom,$uname,$courseid);
9774: }
9775:
9776: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9777: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9778: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9779:
9780: $courselevel=$courseid.'.'.$spacequalifierrest;
9781: my $courselevelr=$courseid.'.'.$symbparm;
9782: $courselevelm=$courseid.'.'.$mapparm;
9783:
9784: # ----------------------------------------------------------- first, check user
9785:
9786: my $userreply=&resdata($uname,$udom,'user',
9787: ([$courselevelr,'resource'],
9788: [$courselevelm,'map' ],
9789: [$courselevel, 'course' ]));
9790: if (defined($userreply)) { return &get_reply($userreply); }
9791:
9792: # ------------------------------------------------ second, check some of course
9793: my $coursereply;
9794: if (@groups > 0) {
9795: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9796: $mapparm,$spacequalifierrest);
9797: if (defined($coursereply)) { return &get_reply($coursereply); }
9798: }
9799:
9800: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9801: $env{'course.'.$courseid.'.domain'},
9802: 'course',
9803: ([$seclevelr, 'resource'],
9804: [$seclevelm, 'map' ],
9805: [$seclevel, 'course' ],
9806: [$courselevelr,'resource']));
9807: if (defined($coursereply)) { return &get_reply($coursereply); }
9808:
9809: # ------------------------------------------------------ third, check map parms
9810: my %parmhash=();
9811: my $thisparm='';
9812: if (tie(%parmhash,'GDBM_File',
9813: $env{'request.course.fn'}.'_parms.db',
9814: &GDBM_READER(),0640)) {
9815: $thisparm=$parmhash{$symbparm};
9816: untie(%parmhash);
9817: }
9818: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
9819: }
9820: # ------------------------------------------ fourth, look in resource metadata
9821:
9822: $spacequalifierrest=~s/\./\_/;
9823: my $filename;
9824: if (!$symbparm) { $symbparm=&symbread(); }
9825: if ($symbparm) {
9826: $filename=(&decode_symb($symbparm))[2];
9827: } else {
9828: $filename=$env{'request.filename'};
9829: }
9830: my $metadata=&metadata($filename,$spacequalifierrest);
9831: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
9832: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
9833: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
9834:
9835: # ---------------------------------------------- fourth, look in rest of course
9836: if ($symbparm && defined($courseid) &&
9837: $courseid eq $env{'request.course.id'}) {
9838: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9839: $env{'course.'.$courseid.'.domain'},
9840: 'course',
9841: ([$courselevelm,'map' ],
9842: [$courselevel, 'course']));
9843: if (defined($coursereply)) { return &get_reply($coursereply); }
9844: }
9845: # ------------------------------------------------------------------ Cascade up
9846: unless ($space eq '0') {
9847: my @parts=split(/_/,$space);
9848: my $id=pop(@parts);
9849: my $part=join('_',@parts);
9850: if ($part eq '') { $part='0'; }
9851: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
9852: $symbparm,$udom,$uname,$section,1);
9853: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
9854: }
9855: if ($recurse) { return undef; }
9856: my $pack_def=&packages_tab_default($filename,$varname);
9857: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
9858: # ---------------------------------------------------- Any other user namespace
9859: } elsif ($realm eq 'environment') {
9860: # ----------------------------------------------------------------- environment
9861: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9862: return $env{'environment.'.$spacequalifierrest};
9863: } else {
9864: if ($uname eq 'anonymous' && $udom eq '') {
9865: return '';
9866: }
9867: my %returnhash=&userenvironment($udom,$uname,
9868: $spacequalifierrest);
9869: return $returnhash{$spacequalifierrest};
9870: }
9871: } elsif ($realm eq 'system') {
9872: # ----------------------------------------------------------------- system.time
9873: if ($space eq 'time') {
9874: return time;
9875: }
9876: } elsif ($realm eq 'server') {
9877: # ----------------------------------------------------------------- system.time
9878: if ($space eq 'name') {
9879: return $ENV{'SERVER_NAME'};
9880: }
9881: }
9882: return '';
9883: }
9884:
9885: sub get_reply {
9886: my ($reply_value) = @_;
9887: if (ref($reply_value) eq 'ARRAY') {
9888: if (wantarray) {
9889: return @$reply_value;
9890: }
9891: return $reply_value->[0];
9892: } else {
9893: return $reply_value;
9894: }
9895: }
9896:
9897: sub check_group_parms {
9898: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
9899: my @groupitems = ();
9900: my $resultitem;
9901: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
9902: foreach my $group (@{$groups}) {
9903: foreach my $level (@levels) {
9904: my $item = $courseid.'.['.$group.'].'.$level->[0];
9905: push(@groupitems,[$item,$level->[1]]);
9906: }
9907: }
9908: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
9909: $env{'course.'.$courseid.'.domain'},
9910: 'course',@groupitems);
9911: return $coursereply;
9912: }
9913:
9914: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
9915: my ($courseid,@groups) = @_;
9916: @groups = sort(@groups);
9917: return @groups;
9918: }
9919:
9920: sub packages_tab_default {
9921: my ($uri,$varname)=@_;
9922: my (undef,$part,$name)=split(/\./,$varname);
9923:
9924: my (@extension,@specifics,$do_default);
9925: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
9926: my ($pack_type,$pack_part)=split(/_/,$package,2);
9927: if ($pack_type eq 'default') {
9928: $do_default=1;
9929: } elsif ($pack_type eq 'extension') {
9930: push(@extension,[$package,$pack_type,$pack_part]);
9931: } elsif ($pack_part eq $part || $pack_type eq 'part') {
9932: # only look at packages defaults for packages that this id is
9933: push(@specifics,[$package,$pack_type,$pack_part]);
9934: }
9935: }
9936: # first look for a package that matches the requested part id
9937: foreach my $package (@specifics) {
9938: my (undef,$pack_type,$pack_part)=@{$package};
9939: next if ($pack_part ne $part);
9940: if (defined($packagetab{"$pack_type&$name&default"})) {
9941: return $packagetab{"$pack_type&$name&default"};
9942: }
9943: }
9944: # look for any possible matching non extension_ package
9945: foreach my $package (@specifics) {
9946: my (undef,$pack_type,$pack_part)=@{$package};
9947: if (defined($packagetab{"$pack_type&$name&default"})) {
9948: return $packagetab{"$pack_type&$name&default"};
9949: }
9950: if ($pack_type eq 'part') { $pack_part='0'; }
9951: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
9952: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
9953: }
9954: }
9955: # look for any posible extension_ match
9956: foreach my $package (@extension) {
9957: my ($package,$pack_type)=@{$package};
9958: if (defined($packagetab{"$pack_type&$name&default"})) {
9959: return $packagetab{"$pack_type&$name&default"};
9960: }
9961: if (defined($packagetab{$package."&$name&default"})) {
9962: return $packagetab{$package."&$name&default"};
9963: }
9964: }
9965: # look for a global default setting
9966: if ($do_default && defined($packagetab{"default&$name&default"})) {
9967: return $packagetab{"default&$name&default"};
9968: }
9969: return undef;
9970: }
9971:
9972: sub add_prefix_and_part {
9973: my ($prefix,$part)=@_;
9974: my $keyroot;
9975: if (defined($prefix) && $prefix !~ /^__/) {
9976: # prefix that has a part already
9977: $keyroot=$prefix;
9978: } elsif (defined($prefix)) {
9979: # prefix that is missing a part
9980: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
9981: } else {
9982: # no prefix at all
9983: if (defined($part)) { $keyroot='_'.$part; }
9984: }
9985: return $keyroot;
9986: }
9987:
9988: # ---------------------------------------------------------------- Get metadata
9989:
9990: my %metaentry;
9991: my %importedpartids;
9992: sub metadata {
9993: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
9994: $uri=&declutter($uri);
9995: # if it is a non metadata possible uri return quickly
9996: if (($uri eq '') ||
9997: (($uri =~ m|^/*adm/|) &&
9998: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
9999: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10000: return undef;
10001: }
10002: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
10003: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10004: return undef;
10005: }
10006: my $filename=$uri;
10007: $uri=~s/\.meta$//;
10008: #
10009: # Is the metadata already cached?
10010: # Look at timestamp of caching
10011: # Everything is cached by the main uri, libraries are never directly cached
10012: #
10013: if (!defined($liburi)) {
10014: my ($result,$cached)=&is_cached_new('meta',$uri);
10015: if (defined($cached)) { return $result->{':'.$what}; }
10016: }
10017: {
10018: # Imported parts would go here
10019: my %importedids=();
10020: my @origfileimportpartids=();
10021: my $importedparts=0;
10022: #
10023: # Is this a recursive call for a library?
10024: #
10025: # if (! exists($metacache{$uri})) {
10026: # $metacache{$uri}={};
10027: # }
10028: my $cachetime = 60*60;
10029: if ($liburi) {
10030: $liburi=&declutter($liburi);
10031: $filename=$liburi;
10032: } else {
10033: &devalidate_cache_new('meta',$uri);
10034: undef(%metaentry);
10035: }
10036: my %metathesekeys=();
10037: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10038: my $metastring;
10039: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10040: my $which = &hreflocation('','/'.($liburi || $uri));
10041: $metastring =
10042: &Apache::lonnet::ssi_body($which,
10043: ('grade_target' => 'meta'));
10044: $cachetime = 1; # only want this cached in the child not long term
10045: } elsif (($uri !~ m -^(editupload)/-) &&
10046: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10047: my $file=&filelocation('',&clutter($filename));
10048: #push(@{$metaentry{$uri.'.file'}},$file);
10049: $metastring=&getfile($file);
10050: }
10051: my $parser=HTML::LCParser->new(\$metastring);
10052: my $token;
10053: undef %metathesekeys;
10054: while ($token=$parser->get_token) {
10055: if ($token->[0] eq 'S') {
10056: if (defined($token->[2]->{'package'})) {
10057: #
10058: # This is a package - get package info
10059: #
10060: my $package=$token->[2]->{'package'};
10061: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10062: if (defined($token->[2]->{'id'})) {
10063: $keyroot.='_'.$token->[2]->{'id'};
10064: }
10065: if ($metaentry{':packages'}) {
10066: $metaentry{':packages'}.=','.$package.$keyroot;
10067: } else {
10068: $metaentry{':packages'}=$package.$keyroot;
10069: }
10070: foreach my $pack_entry (keys(%packagetab)) {
10071: my $part=$keyroot;
10072: $part=~s/^\_//;
10073: if ($pack_entry=~/^\Q$package\E\&/ ||
10074: $pack_entry=~/^\Q$package\E_0\&/) {
10075: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10076: # ignore package.tab specified default values
10077: # here &package_tab_default() will fetch those
10078: if ($subp eq 'default') { next; }
10079: my $value=$packagetab{$pack_entry};
10080: my $unikey;
10081: if ($pack =~ /_0$/) {
10082: $unikey='parameter_0_'.$name;
10083: $part=0;
10084: } else {
10085: $unikey='parameter'.$keyroot.'_'.$name;
10086: }
10087: if ($subp eq 'display') {
10088: $value.=' [Part: '.$part.']';
10089: }
10090: $metaentry{':'.$unikey.'.part'}=$part;
10091: $metathesekeys{$unikey}=1;
10092: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10093: $metaentry{':'.$unikey.'.'.$subp}=$value;
10094: }
10095: if (defined($metaentry{':'.$unikey.'.default'})) {
10096: $metaentry{':'.$unikey}=
10097: $metaentry{':'.$unikey.'.default'};
10098: }
10099: }
10100: }
10101: } else {
10102: #
10103: # This is not a package - some other kind of start tag
10104: #
10105: my $entry=$token->[1];
10106: my $unikey='';
10107:
10108: if ($entry eq 'import') {
10109: #
10110: # Importing a library here
10111: #
10112: my $location=$parser->get_text('/import');
10113: my $dir=$filename;
10114: $dir=~s|[^/]*$||;
10115: $location=&filelocation($dir,$location);
10116:
10117: my $importmode=$token->[2]->{'importmode'};
10118: if ($importmode eq 'problem') {
10119: # Import as problem/response
10120: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10121: } elsif ($importmode eq 'part') {
10122: # Import as part(s)
10123: $importedparts=1;
10124: # We need to get the original file and the imported file to get the part order correct
10125: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10126: # Load and inspect original file
10127: if ($#origfileimportpartids<0) {
10128: undef(%importedpartids);
10129: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10130: my $origfile=&getfile($origfilelocation);
10131: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10132: }
10133:
10134: # Load and inspect imported file
10135: my $impfile=&getfile($location);
10136: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10137: if ($#impfilepartids>=0) {
10138: # This problem had parts
10139: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10140: } else {
10141: # Importing by turning a single problem into a problem part
10142: # It gets the import-tags ID as part-ID
10143: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10144: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10145: }
10146: } else {
10147: # Normal import
10148: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10149: if (defined($token->[2]->{'id'})) {
10150: $unikey.='_'.$token->[2]->{'id'};
10151: }
10152: }
10153:
10154: if ($depthcount<20) {
10155: my $metadata =
10156: &metadata($uri,'keys', $location,$unikey,
10157: $depthcount+1);
10158: foreach my $meta (split(',',$metadata)) {
10159: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10160: $metathesekeys{$meta}=1;
10161: }
10162:
10163: }
10164: } else {
10165: #
10166: # Not importing, some other kind of non-package, non-library start tag
10167: #
10168: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10169: if (defined($token->[2]->{'id'})) {
10170: $unikey.='_'.$token->[2]->{'id'};
10171: }
10172: if (defined($token->[2]->{'name'})) {
10173: $unikey.='_'.$token->[2]->{'name'};
10174: }
10175: $metathesekeys{$unikey}=1;
10176: foreach my $param (@{$token->[3]}) {
10177: $metaentry{':'.$unikey.'.'.$param} =
10178: $token->[2]->{$param};
10179: }
10180: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10181: my $default=$metaentry{':'.$unikey.'.default'};
10182: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10183: # only ws inside the tag, and not in default, so use default
10184: # as value
10185: $metaentry{':'.$unikey}=$default;
10186: } elsif ( $internaltext =~ /\S/ ) {
10187: # something interesting inside the tag
10188: $metaentry{':'.$unikey}=$internaltext;
10189: } else {
10190: # no interesting values, don't set a default
10191: }
10192: # end of not-a-package not-a-library import
10193: }
10194: # end of not-a-package start tag
10195: }
10196: # the next is the end of "start tag"
10197: }
10198: }
10199: my ($extension) = ($uri =~ /\.(\w+)$/);
10200: $extension = lc($extension);
10201: if ($extension eq 'htm') { $extension='html'; }
10202:
10203: foreach my $key (keys(%packagetab)) {
10204: #no specific packages #how's our extension
10205: if ($key!~/^extension_\Q$extension\E&/) { next; }
10206: &metadata_create_package_def($uri,$key,'extension_'.$extension,
10207: \%metathesekeys);
10208: }
10209:
10210: if (!exists($metaentry{':packages'})
10211: || $packagetab{"import_defaults&extension_$extension"}) {
10212: foreach my $key (keys(%packagetab)) {
10213: #no specific packages well let's get default then
10214: if ($key!~/^default&/) { next; }
10215: &metadata_create_package_def($uri,$key,'default',
10216: \%metathesekeys);
10217: }
10218: }
10219: # are there custom rights to evaluate
10220: if ($metaentry{':copyright'} eq 'custom') {
10221:
10222: #
10223: # Importing a rights file here
10224: #
10225: unless ($depthcount) {
10226: my $location=$metaentry{':customdistributionfile'};
10227: my $dir=$filename;
10228: $dir=~s|[^/]*$||;
10229: $location=&filelocation($dir,$location);
10230: my $rights_metadata =
10231: &metadata($uri,'keys',$location,'_rights',
10232: $depthcount+1);
10233: foreach my $rights (split(',',$rights_metadata)) {
10234: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10235: $metathesekeys{$rights}=1;
10236: }
10237: }
10238: }
10239: # uniqifiy package listing
10240: my %seen;
10241: my @uniq_packages =
10242: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10243: $metaentry{':packages'} = join(',',@uniq_packages);
10244:
10245: if ($importedparts) {
10246: # We had imported parts and need to rebuild partorder
10247: $metaentry{':partorder'}='';
10248: $metathesekeys{'partorder'}=1;
10249: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10250: if ($origfileimportpartids[$index] eq 'part') {
10251: # original part, part of the problem
10252: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10253: } else {
10254: # we have imported parts at this position
10255: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10256: }
10257: }
10258: $metaentry{':partorder'}=~s/^\,//;
10259: }
10260:
10261: $metaentry{':keys'} = join(',',keys(%metathesekeys));
10262: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10263: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10264: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
10265: # this is the end of "was not already recently cached
10266: }
10267: return $metaentry{':'.$what};
10268: }
10269:
10270: sub metadata_create_package_def {
10271: my ($uri,$key,$package,$metathesekeys)=@_;
10272: my ($pack,$name,$subp)=split(/\&/,$key);
10273: if ($subp eq 'default') { next; }
10274:
10275: if (defined($metaentry{':packages'})) {
10276: $metaentry{':packages'}.=','.$package;
10277: } else {
10278: $metaentry{':packages'}=$package;
10279: }
10280: my $value=$packagetab{$key};
10281: my $unikey;
10282: $unikey='parameter_0_'.$name;
10283: $metaentry{':'.$unikey.'.part'}=0;
10284: $$metathesekeys{$unikey}=1;
10285: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10286: $metaentry{':'.$unikey.'.'.$subp}=$value;
10287: }
10288: if (defined($metaentry{':'.$unikey.'.default'})) {
10289: $metaentry{':'.$unikey}=
10290: $metaentry{':'.$unikey.'.default'};
10291: }
10292: }
10293:
10294: sub metadata_generate_part0 {
10295: my ($metadata,$metacache,$uri) = @_;
10296: my %allnames;
10297: foreach my $metakey (keys(%$metadata)) {
10298: if ($metakey=~/^parameter\_(.*)/) {
10299: my $part=$$metacache{':'.$metakey.'.part'};
10300: my $name=$$metacache{':'.$metakey.'.name'};
10301: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10302: $allnames{$name}=$part;
10303: }
10304: }
10305: }
10306: foreach my $name (keys(%allnames)) {
10307: $$metadata{"parameter_0_$name"}=1;
10308: my $key=":parameter_0_$name";
10309: $$metacache{"$key.part"}='0';
10310: $$metacache{"$key.name"}=$name;
10311: $$metacache{"$key.type"}=$$metacache{':parameter_'.
10312: $allnames{$name}.'_'.$name.
10313: '.type'};
10314: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10315: '.display'};
10316: my $expr='[Part: '.$allnames{$name}.']';
10317: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10318: $$metacache{"$key.display"}=$olddis;
10319: }
10320: }
10321:
10322: # ------------------------------------------------------ Devalidate title cache
10323:
10324: sub devalidate_title_cache {
10325: my ($url)=@_;
10326: if (!$env{'request.course.id'}) { return; }
10327: my $symb=&symbread($url);
10328: if (!$symb) { return; }
10329: my $key=$env{'request.course.id'}."\0".$symb;
10330: &devalidate_cache_new('title',$key);
10331: }
10332:
10333: # ------------------------------------------------- Get the title of a course
10334:
10335: sub current_course_title {
10336: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10337: }
10338: # ------------------------------------------------- Get the title of a resource
10339:
10340: sub gettitle {
10341: my $urlsymb=shift;
10342: my $symb=&symbread($urlsymb);
10343: if ($symb) {
10344: my $key=$env{'request.course.id'}."\0".$symb;
10345: my ($result,$cached)=&is_cached_new('title',$key);
10346: if (defined($cached)) {
10347: return $result;
10348: }
10349: my ($map,$resid,$url)=&decode_symb($symb);
10350: my $title='';
10351: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10352: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10353: } else {
10354: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10355: &GDBM_READER(),0640)) {
10356: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10357: $title=$bighash{'title_'.$mapid.'.'.$resid};
10358: untie(%bighash);
10359: }
10360: }
10361: $title=~s/\&colon\;/\:/gs;
10362: if ($title) {
10363: # Remember both $symb and $title for dynamic metadata
10364: $accesshash{$symb.'___crstitle'}=$title;
10365: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10366: # Cache this title and then return it
10367: return &do_cache_new('title',$key,$title,600);
10368: }
10369: $urlsymb=$url;
10370: }
10371: my $title=&metadata($urlsymb,'title');
10372: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10373: return $title;
10374: }
10375:
10376: sub getdocspath {
10377: my ($symb) = @_;
10378: my $path;
10379: if ($symb) {
10380: my ($mapurl,$id,$resurl) = &decode_symb($symb);
10381: if ($resurl=~/\.(sequence|page)$/) {
10382: $mapurl=$resurl;
10383: } elsif ($resurl eq 'adm/navmaps') {
10384: $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
10385: }
10386: my $mapresobj;
10387: my $navmap = Apache::lonnavmaps::navmap->new();
10388: if (ref($navmap)) {
10389: $mapresobj = $navmap->getResourceByUrl($mapurl);
10390: }
10391: $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
10392: my $type=$2;
10393: if (ref($mapresobj)) {
10394: my $pcslist = $mapresobj->map_hierarchy();
10395: if ($pcslist ne '') {
10396: foreach my $pc (split(/,/,$pcslist)) {
10397: next if ($pc <= 1);
10398: my $res = $navmap->getByMapPc($pc);
10399: if (ref($res)) {
10400: my $thisurl = $res->src();
10401: $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
10402: my $thistitle = $res->title();
10403: $path .= '&'.
10404: &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
10405: &Apache::lonhtmlcommon::entity_encode($thistitle).
10406: ':'.$res->randompick().
10407: ':'.$res->randomout().
10408: ':'.$res->encrypted().
10409: ':'.$res->randomorder().
10410: ':'.$res->is_page();
10411: }
10412: }
10413: }
10414: $path =~ s/^\&//;
10415: my $maptitle = $mapresobj->title();
10416: if ($mapurl eq 'default') {
10417: $maptitle = 'Main Course Documents';
10418: }
10419: $path .= ($path ne '')? '&' : ''.
10420: &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
10421: &Apache::lonhtmlcommon::entity_encode($maptitle).
10422: ':'.$mapresobj->randompick().
10423: ':'.$mapresobj->randomout().
10424: ':'.$mapresobj->encrypted().
10425: ':'.$mapresobj->randomorder().
10426: ':'.$mapresobj->is_page();
10427: } else {
10428: my $maptitle = &gettitle($mapurl);
10429: my $ispage;
10430: if ($mapurl =~ /\.page$/) {
10431: $ispage = 1;
10432: }
10433: if ($mapurl eq 'default') {
10434: $maptitle = 'Main Course Documents';
10435: }
10436: $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
10437: &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
10438: }
10439: unless ($mapurl eq 'default') {
10440: $path = 'default&'.
10441: &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
10442: ':::::&'.$path;
10443: }
10444: }
10445: return $path;
10446: }
10447:
10448: sub get_slot {
10449: my ($which,$cnum,$cdom)=@_;
10450: if (!$cnum || !$cdom) {
10451: (undef,my $courseid)=&whichuser();
10452: $cdom=$env{'course.'.$courseid.'.domain'};
10453: $cnum=$env{'course.'.$courseid.'.num'};
10454: }
10455: my $key=join("\0",'slots',$cdom,$cnum,$which);
10456: my %slotinfo;
10457: if (exists($remembered{$key})) {
10458: $slotinfo{$which} = $remembered{$key};
10459: } else {
10460: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10461: &Apache::lonhomework::showhash(%slotinfo);
10462: my ($tmp)=keys(%slotinfo);
10463: if ($tmp=~/^error:/) { return (); }
10464: $remembered{$key} = $slotinfo{$which};
10465: }
10466: if (ref($slotinfo{$which}) eq 'HASH') {
10467: return %{$slotinfo{$which}};
10468: }
10469: return $slotinfo{$which};
10470: }
10471:
10472: sub get_reservable_slots {
10473: my ($cnum,$cdom,$uname,$udom) = @_;
10474: my $now = time;
10475: my $reservable_info;
10476: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10477: if (exists($remembered{$key})) {
10478: $reservable_info = $remembered{$key};
10479: } else {
10480: my %resv;
10481: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10482: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10483: $reservable_info = \%resv;
10484: $remembered{$key} = $reservable_info;
10485: }
10486: return $reservable_info;
10487: }
10488:
10489: sub get_course_slots {
10490: my ($cnum,$cdom) = @_;
10491: my $hashid=$cnum.':'.$cdom;
10492: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10493: if (defined($cached)) {
10494: if (ref($result) eq 'HASH') {
10495: return %{$result};
10496: }
10497: } else {
10498: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10499: my ($tmp) = keys(%slots);
10500: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10501: &do_cache_new('allslots',$hashid,\%slots,600);
10502: return %slots;
10503: }
10504: }
10505: return;
10506: }
10507:
10508: sub devalidate_slots_cache {
10509: my ($cnum,$cdom)=@_;
10510: my $hashid=$cnum.':'.$cdom;
10511: &devalidate_cache_new('allslots',$hashid);
10512: }
10513:
10514: sub get_coursechange {
10515: my ($cdom,$cnum) = @_;
10516: if ($cdom eq '' || $cnum eq '') {
10517: return unless ($env{'request.course.id'});
10518: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10519: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10520: }
10521: my $hashid=$cdom.'_'.$cnum;
10522: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10523: if ((defined($cached)) && ($change ne '')) {
10524: return $change;
10525: } else {
10526: my %crshash;
10527: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10528: if ($crshash{'internal.contentchange'} eq '') {
10529: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10530: if ($change eq '') {
10531: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10532: $change = $crshash{'internal.created'};
10533: }
10534: } else {
10535: $change = $crshash{'internal.contentchange'};
10536: }
10537: my $cachetime = 600;
10538: &do_cache_new('crschange',$hashid,$change,$cachetime);
10539: }
10540: return $change;
10541: }
10542:
10543: sub devalidate_coursechange_cache {
10544: my ($cnum,$cdom)=@_;
10545: my $hashid=$cnum.':'.$cdom;
10546: &devalidate_cache_new('crschange',$hashid);
10547: }
10548:
10549: # ------------------------------------------------- Update symbolic store links
10550:
10551: sub symblist {
10552: my ($mapname,%newhash)=@_;
10553: $mapname=&deversion(&declutter($mapname));
10554: my %hash;
10555: if (($env{'request.course.fn'}) && (%newhash)) {
10556: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10557: &GDBM_WRCREAT(),0640)) {
10558: foreach my $url (keys(%newhash)) {
10559: next if ($url eq 'last_known'
10560: && $env{'form.no_update_last_known'});
10561: $hash{declutter($url)}=&encode_symb($mapname,
10562: $newhash{$url}->[1],
10563: $newhash{$url}->[0]);
10564: }
10565: if (untie(%hash)) {
10566: return 'ok';
10567: }
10568: }
10569: }
10570: return 'error';
10571: }
10572:
10573: # --------------------------------------------------------------- Verify a symb
10574:
10575: sub symbverify {
10576: my ($symb,$thisurl,$encstate)=@_;
10577: my $thisfn=$thisurl;
10578: $thisfn=&declutter($thisfn);
10579: # direct jump to resource in page or to a sequence - will construct own symbs
10580: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10581: # check URL part
10582: my ($map,$resid,$url)=&decode_symb($symb);
10583:
10584: unless ($url eq $thisfn) { return 0; }
10585:
10586: $symb=&symbclean($symb);
10587: $thisurl=&deversion($thisurl);
10588: $thisfn=&deversion($thisfn);
10589:
10590: my %bighash;
10591: my $okay=0;
10592:
10593: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10594: &GDBM_READER(),0640)) {
10595: my $noclutter;
10596: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10597: $thisurl =~ s/\?.+$//;
10598: if ($map =~ m{^uploaded/.+\.page$}) {
10599: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10600: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10601: $noclutter = 1;
10602: }
10603: }
10604: my $ids;
10605: if ($noclutter) {
10606: $ids=$bighash{'ids_'.$thisurl};
10607: } else {
10608: $ids=$bighash{'ids_'.&clutter($thisurl)};
10609: }
10610: unless ($ids) {
10611: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10612: $ids=$bighash{$idkey};
10613: }
10614: if ($ids) {
10615: # ------------------------------------------------------------------- Has ID(s)
10616: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10617: $symb =~ s/\?.+$//;
10618: }
10619: foreach my $id (split(/\,/,$ids)) {
10620: my ($mapid,$resid)=split(/\./,$id);
10621: if (
10622: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10623: eq $symb) {
10624: if (ref($encstate)) {
10625: $$encstate = $bighash{'encrypted_'.$id};
10626: }
10627: if (($env{'request.role.adv'}) ||
10628: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10629: ($thisurl eq '/adm/navmaps')) {
10630: $okay=1;
10631: last;
10632: }
10633: }
10634: }
10635: }
10636: untie(%bighash);
10637: }
10638: return $okay;
10639: }
10640:
10641: # --------------------------------------------------------------- Clean-up symb
10642:
10643: sub symbclean {
10644: my $symb=shift;
10645: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10646: # remove version from map
10647: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10648:
10649: # remove version from URL
10650: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10651:
10652: # remove wrapper
10653:
10654: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10655: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10656: return $symb;
10657: }
10658:
10659: # ---------------------------------------------- Split symb to find map and url
10660:
10661: sub encode_symb {
10662: my ($map,$resid,$url)=@_;
10663: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10664: }
10665:
10666: sub decode_symb {
10667: my $symb=shift;
10668: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10669: my ($map,$resid,$url)=split(/___/,$symb);
10670: return (&fixversion($map),$resid,&fixversion($url));
10671: }
10672:
10673: sub fixversion {
10674: my $fn=shift;
10675: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10676: my %bighash;
10677: my $uri=&clutter($fn);
10678: my $key=$env{'request.course.id'}.'_'.$uri;
10679: # is this cached?
10680: my ($result,$cached)=&is_cached_new('courseresversion',$key);
10681: if (defined($cached)) { return $result; }
10682: # unfortunately not cached, or expired
10683: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10684: &GDBM_READER(),0640)) {
10685: if ($bighash{'version_'.$uri}) {
10686: my $version=$bighash{'version_'.$uri};
10687: unless (($version eq 'mostrecent') ||
10688: ($version==&getversion($uri))) {
10689: $uri=~s/\.(\w+)$/\.$version\.$1/;
10690: }
10691: }
10692: untie %bighash;
10693: }
10694: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10695: }
10696:
10697: sub deversion {
10698: my $url=shift;
10699: $url=~s/\.\d+\.(\w+)$/\.$1/;
10700: return $url;
10701: }
10702:
10703: # ------------------------------------------------------ Return symb list entry
10704:
10705: sub symbread {
10706: my ($thisfn,$donotrecurse)=@_;
10707: my $cache_str;
10708: if ($thisfn ne '') {
10709: $cache_str='request.symbread.cached.'.$thisfn;
10710: if ($env{$cache_str} ne '') {
10711: return $env{$cache_str};
10712: }
10713: } else {
10714: # no filename provided? try from environment
10715: if ($env{'request.symb'}) {
10716: return $env{$cache_str}=&symbclean($env{'request.symb'});
10717: }
10718: $thisfn=$env{'request.filename'};
10719: }
10720: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10721: # is that filename actually a symb? Verify, clean, and return
10722: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10723: if (&symbverify($thisfn,$1)) {
10724: return $env{$cache_str}=&symbclean($thisfn);
10725: }
10726: }
10727: $thisfn=declutter($thisfn);
10728: my %hash;
10729: my %bighash;
10730: my $syval='';
10731: if (($env{'request.course.fn'}) && ($thisfn)) {
10732: my $targetfn = $thisfn;
10733: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10734: $targetfn = 'adm/wrapper/'.$thisfn;
10735: }
10736: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10737: $targetfn=$1;
10738: }
10739: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10740: &GDBM_READER(),0640)) {
10741: $syval=$hash{$targetfn};
10742: untie(%hash);
10743: }
10744: # ---------------------------------------------------------- There was an entry
10745: if ($syval) {
10746: #unless ($syval=~/\_\d+$/) {
10747: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10748: #&appenv({'request.ambiguous' => $thisfn});
10749: #return $env{$cache_str}='';
10750: #}
10751: #$syval.=$1;
10752: #}
10753: } else {
10754: # ------------------------------------------------------- Was not in symb table
10755: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10756: &GDBM_READER(),0640)) {
10757: # ---------------------------------------------- Get ID(s) for current resource
10758: my $ids=$bighash{'ids_'.&clutter($thisfn)};
10759: unless ($ids) {
10760: $ids=$bighash{'ids_/'.$thisfn};
10761: }
10762: unless ($ids) {
10763: # alias?
10764: $ids=$bighash{'mapalias_'.$thisfn};
10765: }
10766: if ($ids) {
10767: # ------------------------------------------------------------------- Has ID(s)
10768: my @possibilities=split(/\,/,$ids);
10769: if ($#possibilities==0) {
10770: # ----------------------------------------------- There is only one possibility
10771: my ($mapid,$resid)=split(/\./,$ids);
10772: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10773: $resid,$thisfn);
10774: } elsif (!$donotrecurse) {
10775: # ------------------------------------------ There is more than one possibility
10776: my $realpossible=0;
10777: foreach my $id (@possibilities) {
10778: my $file=$bighash{'src_'.$id};
10779: if (&allowed('bre',$file)) {
10780: my ($mapid,$resid)=split(/\./,$id);
10781: if ($bighash{'map_type_'.$mapid} ne 'page') {
10782: $realpossible++;
10783: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10784: $resid,$thisfn);
10785: }
10786: }
10787: }
10788: if ($realpossible!=1) { $syval=''; }
10789: } else {
10790: $syval='';
10791: }
10792: }
10793: untie(%bighash)
10794: }
10795: }
10796: if ($syval) {
10797: return $env{$cache_str}=$syval;
10798: }
10799: }
10800: &appenv({'request.ambiguous' => $thisfn});
10801: return $env{$cache_str}='';
10802: }
10803:
10804: # ---------------------------------------------------------- Return random seed
10805:
10806: sub numval {
10807: my $txt=shift;
10808: $txt=~tr/A-J/0-9/;
10809: $txt=~tr/a-j/0-9/;
10810: $txt=~tr/K-T/0-9/;
10811: $txt=~tr/k-t/0-9/;
10812: $txt=~tr/U-Z/0-5/;
10813: $txt=~tr/u-z/0-5/;
10814: $txt=~s/\D//g;
10815: if ($_64bit) { if ($txt > 2**32) { return -1; } }
10816: return int($txt);
10817: }
10818:
10819: sub numval2 {
10820: my $txt=shift;
10821: $txt=~tr/A-J/0-9/;
10822: $txt=~tr/a-j/0-9/;
10823: $txt=~tr/K-T/0-9/;
10824: $txt=~tr/k-t/0-9/;
10825: $txt=~tr/U-Z/0-5/;
10826: $txt=~tr/u-z/0-5/;
10827: $txt=~s/\D//g;
10828: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10829: my $total;
10830: foreach my $val (@txts) { $total+=$val; }
10831: if ($_64bit) { if ($total > 2**32) { return -1; } }
10832: return int($total);
10833: }
10834:
10835: sub numval3 {
10836: use integer;
10837: my $txt=shift;
10838: $txt=~tr/A-J/0-9/;
10839: $txt=~tr/a-j/0-9/;
10840: $txt=~tr/K-T/0-9/;
10841: $txt=~tr/k-t/0-9/;
10842: $txt=~tr/U-Z/0-5/;
10843: $txt=~tr/u-z/0-5/;
10844: $txt=~s/\D//g;
10845: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10846: my $total;
10847: foreach my $val (@txts) { $total+=$val; }
10848: if ($_64bit) { $total=(($total<<32)>>32); }
10849: return $total;
10850: }
10851:
10852: sub digest {
10853: my ($data)=@_;
10854: my $digest=&Digest::MD5::md5($data);
10855: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10856: my ($e,$f);
10857: {
10858: use integer;
10859: $e=($a+$b);
10860: $f=($c+$d);
10861: if ($_64bit) {
10862: $e=(($e<<32)>>32);
10863: $f=(($f<<32)>>32);
10864: }
10865: }
10866: if (wantarray) {
10867: return ($e,$f);
10868: } else {
10869: my $g;
10870: {
10871: use integer;
10872: $g=($e+$f);
10873: if ($_64bit) {
10874: $g=(($g<<32)>>32);
10875: }
10876: }
10877: return $g;
10878: }
10879: }
10880:
10881: sub latest_rnd_algorithm_id {
10882: return '64bit5';
10883: }
10884:
10885: sub get_rand_alg {
10886: my ($courseid)=@_;
10887: if (!$courseid) { $courseid=(&whichuser())[1]; }
10888: if ($courseid) {
10889: return $env{"course.$courseid.rndseed"};
10890: }
10891: return &latest_rnd_algorithm_id();
10892: }
10893:
10894: sub validCODE {
10895: my ($CODE)=@_;
10896: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10897: return 0;
10898: }
10899:
10900: sub getCODE {
10901: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10902: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10903: defined($Apache::lonhomework::parsing_a_task) ) &&
10904: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10905: return $Apache::lonhomework::history{'resource.CODE'};
10906: }
10907: return undef;
10908: }
10909: #
10910: # Determines the random seed for a specific context:
10911: #
10912: # parameters:
10913: # symb - in course context the symb for the seed.
10914: # course_id - The course id of the form domain_coursenum.
10915: # domain - Domain for the user.
10916: # course - Course for the user.
10917: # cenv - environment of the course.
10918: #
10919: # NOTE:
10920: # All parameters are picked out of the environment if missing
10921: # or not defined.
10922: # If a symb cannot be determined the current time is used instead.
10923: #
10924: # For a given well defined symb, courside, domain, username,
10925: # and course environment, the seed is reproducible.
10926: #
10927: sub rndseed {
10928: my ($symb,$courseid,$domain,$username, $cenv)=@_;
10929: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10930: if (!defined($symb)) {
10931: unless ($symb=$wsymb) { return time; }
10932: }
10933: if (!defined $courseid) {
10934: $courseid=$wcourseid;
10935: }
10936: if (!defined $domain) { $domain=$wdomain; }
10937: if (!defined $username) { $username=$wusername }
10938:
10939: my $which;
10940: if (defined($cenv->{'rndseed'})) {
10941: $which = $cenv->{'rndseed'};
10942: } else {
10943: $which =&get_rand_alg($courseid);
10944: }
10945: if (defined(&getCODE())) {
10946:
10947: if ($which eq '64bit5') {
10948: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10949: } elsif ($which eq '64bit4') {
10950: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10951: } else {
10952: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10953: }
10954: } elsif ($which eq '64bit5') {
10955: return &rndseed_64bit5($symb,$courseid,$domain,$username);
10956: } elsif ($which eq '64bit4') {
10957: return &rndseed_64bit4($symb,$courseid,$domain,$username);
10958: } elsif ($which eq '64bit3') {
10959: return &rndseed_64bit3($symb,$courseid,$domain,$username);
10960: } elsif ($which eq '64bit2') {
10961: return &rndseed_64bit2($symb,$courseid,$domain,$username);
10962: } elsif ($which eq '64bit') {
10963: return &rndseed_64bit($symb,$courseid,$domain,$username);
10964: }
10965: return &rndseed_32bit($symb,$courseid,$domain,$username);
10966: }
10967:
10968: sub rndseed_32bit {
10969: my ($symb,$courseid,$domain,$username)=@_;
10970: {
10971: use integer;
10972: my $symbchck=unpack("%32C*",$symb) << 27;
10973: my $symbseed=numval($symb) << 22;
10974: my $namechck=unpack("%32C*",$username) << 17;
10975: my $nameseed=numval($username) << 12;
10976: my $domainseed=unpack("%32C*",$domain) << 7;
10977: my $courseseed=unpack("%32C*",$courseid);
10978: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10979: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10980: #&logthis("rndseed :$num:$symb");
10981: if ($_64bit) { $num=(($num<<32)>>32); }
10982: return $num;
10983: }
10984: }
10985:
10986: sub rndseed_64bit {
10987: my ($symb,$courseid,$domain,$username)=@_;
10988: {
10989: use integer;
10990: my $symbchck=unpack("%32S*",$symb) << 21;
10991: my $symbseed=numval($symb) << 10;
10992: my $namechck=unpack("%32S*",$username);
10993:
10994: my $nameseed=numval($username) << 21;
10995: my $domainseed=unpack("%32S*",$domain) << 10;
10996: my $courseseed=unpack("%32S*",$courseid);
10997:
10998: my $num1=$symbchck+$symbseed+$namechck;
10999: my $num2=$nameseed+$domainseed+$courseseed;
11000: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11001: #&logthis("rndseed :$num:$symb");
11002: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11003: return "$num1,$num2";
11004: }
11005: }
11006:
11007: sub rndseed_64bit2 {
11008: my ($symb,$courseid,$domain,$username)=@_;
11009: {
11010: use integer;
11011: # strings need to be an even # of cahracters long, it it is odd the
11012: # last characters gets thrown away
11013: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11014: my $symbseed=numval($symb) << 10;
11015: my $namechck=unpack("%32S*",$username.' ');
11016:
11017: my $nameseed=numval($username) << 21;
11018: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11019: my $courseseed=unpack("%32S*",$courseid.' ');
11020:
11021: my $num1=$symbchck+$symbseed+$namechck;
11022: my $num2=$nameseed+$domainseed+$courseseed;
11023: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11024: #&logthis("rndseed :$num:$symb");
11025: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11026: return "$num1,$num2";
11027: }
11028: }
11029:
11030: sub rndseed_64bit3 {
11031: my ($symb,$courseid,$domain,$username)=@_;
11032: {
11033: use integer;
11034: # strings need to be an even # of cahracters long, it it is odd the
11035: # last characters gets thrown away
11036: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11037: my $symbseed=numval2($symb) << 10;
11038: my $namechck=unpack("%32S*",$username.' ');
11039:
11040: my $nameseed=numval2($username) << 21;
11041: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11042: my $courseseed=unpack("%32S*",$courseid.' ');
11043:
11044: my $num1=$symbchck+$symbseed+$namechck;
11045: my $num2=$nameseed+$domainseed+$courseseed;
11046: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11047: #&logthis("rndseed :$num1:$num2:$_64bit");
11048: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11049:
11050: return "$num1:$num2";
11051: }
11052: }
11053:
11054: sub rndseed_64bit4 {
11055: my ($symb,$courseid,$domain,$username)=@_;
11056: {
11057: use integer;
11058: # strings need to be an even # of cahracters long, it it is odd the
11059: # last characters gets thrown away
11060: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11061: my $symbseed=numval3($symb) << 10;
11062: my $namechck=unpack("%32S*",$username.' ');
11063:
11064: my $nameseed=numval3($username) << 21;
11065: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11066: my $courseseed=unpack("%32S*",$courseid.' ');
11067:
11068: my $num1=$symbchck+$symbseed+$namechck;
11069: my $num2=$nameseed+$domainseed+$courseseed;
11070: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11071: #&logthis("rndseed :$num1:$num2:$_64bit");
11072: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11073:
11074: return "$num1:$num2";
11075: }
11076: }
11077:
11078: sub rndseed_64bit5 {
11079: my ($symb,$courseid,$domain,$username)=@_;
11080: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11081: return "$num1:$num2";
11082: }
11083:
11084: sub rndseed_CODE_64bit {
11085: my ($symb,$courseid,$domain,$username)=@_;
11086: {
11087: use integer;
11088: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11089: my $symbseed=numval2($symb);
11090: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11091: my $CODEseed=numval(&getCODE());
11092: my $courseseed=unpack("%32S*",$courseid.' ');
11093: my $num1=$symbseed+$CODEchck;
11094: my $num2=$CODEseed+$courseseed+$symbchck;
11095: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11096: #&logthis("rndseed :$num1:$num2:$symb");
11097: if ($_64bit) { $num1=(($num1<<32)>>32); }
11098: if ($_64bit) { $num2=(($num2<<32)>>32); }
11099: return "$num1:$num2";
11100: }
11101: }
11102:
11103: sub rndseed_CODE_64bit4 {
11104: my ($symb,$courseid,$domain,$username)=@_;
11105: {
11106: use integer;
11107: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11108: my $symbseed=numval3($symb);
11109: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11110: my $CODEseed=numval3(&getCODE());
11111: my $courseseed=unpack("%32S*",$courseid.' ');
11112: my $num1=$symbseed+$CODEchck;
11113: my $num2=$CODEseed+$courseseed+$symbchck;
11114: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11115: #&logthis("rndseed :$num1:$num2:$symb");
11116: if ($_64bit) { $num1=(($num1<<32)>>32); }
11117: if ($_64bit) { $num2=(($num2<<32)>>32); }
11118: return "$num1:$num2";
11119: }
11120: }
11121:
11122: sub rndseed_CODE_64bit5 {
11123: my ($symb,$courseid,$domain,$username)=@_;
11124: my $code = &getCODE();
11125: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11126: return "$num1:$num2";
11127: }
11128:
11129: sub setup_random_from_rndseed {
11130: my ($rndseed)=@_;
11131: if ($rndseed =~/([,:])/) {
11132: my ($num1,$num2)=split(/[,:]/,$rndseed);
11133: &Math::Random::random_set_seed(abs($num1),abs($num2));
11134: } else {
11135: &Math::Random::random_set_seed_from_phrase($rndseed);
11136: }
11137: }
11138:
11139: sub latest_receipt_algorithm_id {
11140: return 'receipt3';
11141: }
11142:
11143: sub recunique {
11144: my $fucourseid=shift;
11145: my $unique;
11146: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11147: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11148: $unique=$env{"course.$fucourseid.internal.encseed"};
11149: } else {
11150: $unique=$perlvar{'lonReceipt'};
11151: }
11152: return unpack("%32C*",$unique);
11153: }
11154:
11155: sub recprefix {
11156: my $fucourseid=shift;
11157: my $prefix;
11158: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11159: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11160: $prefix=$env{"course.$fucourseid.internal.encpref"};
11161: } else {
11162: $prefix=$perlvar{'lonHostID'};
11163: }
11164: return unpack("%32C*",$prefix);
11165: }
11166:
11167: sub ireceipt {
11168: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11169:
11170: my $return =&recprefix($fucourseid).'-';
11171:
11172: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11173: $env{'request.state'} eq 'construct') {
11174: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11175: return $return;
11176: }
11177:
11178: my $cuname=unpack("%32C*",$funame);
11179: my $cudom=unpack("%32C*",$fudom);
11180: my $cucourseid=unpack("%32C*",$fucourseid);
11181: my $cusymb=unpack("%32C*",$fusymb);
11182: my $cunique=&recunique($fucourseid);
11183: my $cpart=unpack("%32S*",$part);
11184: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11185:
11186: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
11187:
11188: $return.= ($cunique%$cuname+
11189: $cunique%$cudom+
11190: $cusymb%$cuname+
11191: $cusymb%$cudom+
11192: $cucourseid%$cuname+
11193: $cucourseid%$cudom+
11194: $cpart%$cuname+
11195: $cpart%$cudom);
11196: } else {
11197: $return.= ($cunique%$cuname+
11198: $cunique%$cudom+
11199: $cusymb%$cuname+
11200: $cusymb%$cudom+
11201: $cucourseid%$cuname+
11202: $cucourseid%$cudom);
11203: }
11204: return $return;
11205: }
11206:
11207: sub receipt {
11208: my ($part)=@_;
11209: my ($symb,$courseid,$domain,$name) = &whichuser();
11210: return &ireceipt($name,$domain,$courseid,$symb,$part);
11211: }
11212:
11213: sub whichuser {
11214: my ($passedsymb)=@_;
11215: my ($symb,$courseid,$domain,$name,$publicuser);
11216: if (defined($env{'form.grade_symb'})) {
11217: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11218: my $allowed=&allowed('vgr',$tmp_courseid);
11219: if (!$allowed &&
11220: exists($env{'request.course.sec'}) &&
11221: $env{'request.course.sec'} !~ /^\s*$/) {
11222: $allowed=&allowed('vgr',$tmp_courseid.
11223: '/'.$env{'request.course.sec'});
11224: }
11225: if ($allowed) {
11226: ($symb)=&get_env_multiple('form.grade_symb');
11227: $courseid=$tmp_courseid;
11228: ($domain)=&get_env_multiple('form.grade_domain');
11229: ($name)=&get_env_multiple('form.grade_username');
11230: return ($symb,$courseid,$domain,$name,$publicuser);
11231: }
11232: }
11233: if (!$passedsymb) {
11234: $symb=&symbread();
11235: } else {
11236: $symb=$passedsymb;
11237: }
11238: $courseid=$env{'request.course.id'};
11239: $domain=$env{'user.domain'};
11240: $name=$env{'user.name'};
11241: if ($name eq 'public' && $domain eq 'public') {
11242: if (!defined($env{'form.username'})) {
11243: $env{'form.username'}.=time.rand(10000000);
11244: }
11245: $name.=$env{'form.username'};
11246: }
11247: return ($symb,$courseid,$domain,$name,$publicuser);
11248:
11249: }
11250:
11251: # ------------------------------------------------------------ Serves up a file
11252: # returns either the contents of the file or
11253: # -1 if the file doesn't exist
11254: #
11255: # if the target is a file that was uploaded via DOCS,
11256: # a check will be made to see if a current copy exists on the local server,
11257: # if it does this will be served, otherwise a copy will be retrieved from
11258: # the home server for the course and stored in /home/httpd/html/userfiles on
11259: # the local server.
11260:
11261: sub getfile {
11262: my ($file) = @_;
11263: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11264: &repcopy($file);
11265: return &readfile($file);
11266: }
11267:
11268: sub repcopy_userfile {
11269: my ($file)=@_;
11270: my $londocroot = $perlvar{'lonDocRoot'};
11271: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11272: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11273: my ($cdom,$cnum,$filename) =
11274: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11275: my $uri="/uploaded/$cdom/$cnum/$filename";
11276: if (-e "$file") {
11277: # we already have a local copy, check it out
11278: my @fileinfo = stat($file);
11279: my $rtncode;
11280: my $info;
11281: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11282: if ($lwpresp ne 'ok') {
11283: # there is no such file anymore, even though we had a local copy
11284: if ($rtncode eq '404') {
11285: unlink($file);
11286: }
11287: return -1;
11288: }
11289: if ($info < $fileinfo[9]) {
11290: # nice, the file we have is up-to-date, just say okay
11291: return 'ok';
11292: } else {
11293: # the file is outdated, get rid of it
11294: unlink($file);
11295: }
11296: }
11297: # one way or the other, at this point, we don't have the file
11298: # construct the correct path for the file
11299: my @parts = ($cdom,$cnum);
11300: if ($filename =~ m|^(.+)/[^/]+$|) {
11301: push @parts, split(/\//,$1);
11302: }
11303: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11304: foreach my $part (@parts) {
11305: $path .= '/'.$part;
11306: if (!-e $path) {
11307: mkdir($path,0770);
11308: }
11309: }
11310: # now the path exists for sure
11311: # get a user agent
11312: my $ua=new LWP::UserAgent;
11313: my $transferfile=$file.'.in.transfer';
11314: # FIXME: this should flock
11315: if (-e $transferfile) { return 'ok'; }
11316: my $request;
11317: $uri=~s/^\///;
11318: my $homeserver = &homeserver($cnum,$cdom);
11319: my $protocol = $protocol{$homeserver};
11320: $protocol = 'http' if ($protocol ne 'https');
11321: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11322: my $response=$ua->request($request,$transferfile);
11323: # did it work?
11324: if ($response->is_error()) {
11325: unlink($transferfile);
11326: &logthis("Userfile repcopy failed for $uri");
11327: return -1;
11328: }
11329: # worked, rename the transfer file
11330: rename($transferfile,$file);
11331: return 'ok';
11332: }
11333:
11334: sub tokenwrapper {
11335: my $uri=shift;
11336: $uri=~s|^https?\://([^/]+)||;
11337: $uri=~s|^/||;
11338: $env{'user.environment'}=~/\/([^\/]+)\.id/;
11339: my $token=$1;
11340: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11341: if ($udom && $uname && $file) {
11342: $file=~s|(\?\.*)*$||;
11343: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11344: my $homeserver = &homeserver($uname,$udom);
11345: my $protocol = $protocol{$homeserver};
11346: $protocol = 'http' if ($protocol ne 'https');
11347: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11348: (($uri=~/\?/)?'&':'?').'token='.$token.
11349: '&tokenissued='.$perlvar{'lonHostID'};
11350: } else {
11351: return '/adm/notfound.html';
11352: }
11353: }
11354:
11355: # call with reqtype HEAD: get last modification time
11356: # call with reqtype GET: get the file contents
11357: # Do not call this with reqtype GET for large files! It loads everything into memory
11358: #
11359: sub getuploaded {
11360: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11361: $uri=~s/^\///;
11362: my $homeserver = &homeserver($cnum,$cdom);
11363: my $protocol = $protocol{$homeserver};
11364: $protocol = 'http' if ($protocol ne 'https');
11365: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11366: my $ua=new LWP::UserAgent;
11367: my $request=new HTTP::Request($reqtype,$uri);
11368: my $response=$ua->request($request);
11369: $$rtncode = $response->code;
11370: if (! $response->is_success()) {
11371: return 'failed';
11372: }
11373: if ($reqtype eq 'HEAD') {
11374: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11375: } elsif ($reqtype eq 'GET') {
11376: $$info = $response->content;
11377: }
11378: return 'ok';
11379: }
11380:
11381: sub readfile {
11382: my $file = shift;
11383: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11384: my $fh;
11385: open($fh,"<$file");
11386: my $a='';
11387: while (my $line = <$fh>) { $a .= $line; }
11388: return $a;
11389: }
11390:
11391: sub filelocation {
11392: my ($dir,$file) = @_;
11393: my $location;
11394: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11395:
11396: if ($file =~ m-^/adm/-) {
11397: $file=~s-^/adm/wrapper/-/-;
11398: $file=~s-^/adm/coursedocs/showdoc/-/-;
11399: }
11400:
11401: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11402: $location = $file;
11403: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11404: my ($udom,$uname,$filename)=
11405: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11406: my $home=&homeserver($uname,$udom);
11407: my $is_me=0;
11408: my @ids=¤t_machine_ids();
11409: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11410: if ($is_me) {
11411: $location=propath($udom,$uname).'/userfiles/'.$filename;
11412: } else {
11413: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11414: $udom.'/'.$uname.'/'.$filename;
11415: }
11416: } elsif ($file =~ m-^/adm/-) {
11417: $location = $perlvar{'lonDocRoot'}.'/'.$file;
11418: } else {
11419: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11420: $file=~s:^/(res|priv)/:/:;
11421: my $space=$1;
11422: if ( !( $file =~ m:^/:) ) {
11423: $location = $dir. '/'.$file;
11424: } else {
11425: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11426: }
11427: }
11428: $location=~s://+:/:g; # remove duplicate /
11429: while ($location=~m{/\.\./}) {
11430: if ($location =~ m{/[^/]+/\.\./}) {
11431: $location=~ s{/[^/]+/\.\./}{/}g;
11432: } else {
11433: $location=~ s{/\.\./}{/}g;
11434: }
11435: } #remove dir/..
11436: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11437: return $location;
11438: }
11439:
11440: sub hreflocation {
11441: my ($dir,$file)=@_;
11442: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11443: $file=filelocation($dir,$file);
11444: } elsif ($file=~m-^/adm/-) {
11445: $file=~s-^/adm/wrapper/-/-;
11446: $file=~s-^/adm/coursedocs/showdoc/-/-;
11447: }
11448: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11449: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11450: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11451: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11452: {/uploaded/$1/$2/}x;
11453: }
11454: if ($file=~ m{^/userfiles/}) {
11455: $file =~ s{^/userfiles/}{/uploaded/};
11456: }
11457: return $file;
11458: }
11459:
11460:
11461:
11462:
11463:
11464: sub current_machine_domains {
11465: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11466: }
11467:
11468: sub machine_domains {
11469: my ($hostname) = @_;
11470: my @domains;
11471: my %hostname = &all_hostnames();
11472: while( my($id, $name) = each(%hostname)) {
11473: # &logthis("-$id-$name-$hostname-");
11474: if ($hostname eq $name) {
11475: push(@domains,&host_domain($id));
11476: }
11477: }
11478: return @domains;
11479: }
11480:
11481: sub current_machine_ids {
11482: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11483: }
11484:
11485: sub machine_ids {
11486: my ($hostname) = @_;
11487: $hostname ||= &hostname($perlvar{'lonHostID'});
11488: my @ids;
11489: my %name_to_host = &all_names();
11490: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11491: return @{ $name_to_host{$hostname} };
11492: }
11493: return;
11494: }
11495:
11496: sub additional_machine_domains {
11497: my @domains;
11498: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11499: while( my $line = <$fh>) {
11500: $line =~ s/\s//g;
11501: push(@domains,$line);
11502: }
11503: return @domains;
11504: }
11505:
11506: sub default_login_domain {
11507: my $domain = $perlvar{'lonDefDomain'};
11508: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11509: foreach my $posdom (¤t_machine_domains(),
11510: &additional_machine_domains()) {
11511: if (lc($posdom) eq lc($testdomain)) {
11512: $domain=$posdom;
11513: last;
11514: }
11515: }
11516: return $domain;
11517: }
11518:
11519: # ------------------------------------------------------------- Declutters URLs
11520:
11521: sub declutter {
11522: my $thisfn=shift;
11523: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11524: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11525: $thisfn=~s/^\///;
11526: $thisfn=~s|^adm/wrapper/||;
11527: $thisfn=~s|^adm/coursedocs/showdoc/||;
11528: $thisfn=~s/^res\///;
11529: $thisfn=~s/^priv\///;
11530: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11531: $thisfn=~s/\?.+$//;
11532: }
11533: return $thisfn;
11534: }
11535:
11536: # ------------------------------------------------------------- Clutter up URLs
11537:
11538: sub clutter {
11539: my $thisfn='/'.&declutter(shift);
11540: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11541: || $thisfn =~ m{^/adm/(includes|pages)} ) {
11542: $thisfn='/res'.$thisfn;
11543: }
11544: if ($thisfn !~m|^/adm|) {
11545: if ($thisfn =~ m|^/ext/|) {
11546: $thisfn='/adm/wrapper'.$thisfn;
11547: } else {
11548: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11549: my $embstyle=&Apache::loncommon::fileembstyle($ext);
11550: if ($embstyle eq 'ssi'
11551: || ($embstyle eq 'hdn')
11552: || ($embstyle eq 'rat')
11553: || ($embstyle eq 'prv')
11554: || ($embstyle eq 'ign')) {
11555: #do nothing with these
11556: } elsif (($embstyle eq 'img')
11557: || ($embstyle eq 'emb')
11558: || ($embstyle eq 'wrp')) {
11559: $thisfn='/adm/wrapper'.$thisfn;
11560: } elsif ($embstyle eq 'unk'
11561: && $thisfn!~/\.(sequence|page)$/) {
11562: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
11563: } else {
11564: # &logthis("Got a blank emb style");
11565: }
11566: }
11567: }
11568: return $thisfn;
11569: }
11570:
11571: sub clutter_with_no_wrapper {
11572: my $uri = &clutter(shift);
11573: if ($uri =~ m-^/adm/-) {
11574: $uri =~ s-^/adm/wrapper/-/-;
11575: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11576: }
11577: return $uri;
11578: }
11579:
11580: sub freeze_escape {
11581: my ($value)=@_;
11582: if (ref($value)) {
11583: $value=&nfreeze($value);
11584: return '__FROZEN__'.&escape($value);
11585: }
11586: return &escape($value);
11587: }
11588:
11589:
11590: sub thaw_unescape {
11591: my ($value)=@_;
11592: if ($value =~ /^__FROZEN__/) {
11593: substr($value,0,10,undef);
11594: $value=&unescape($value);
11595: return &thaw($value);
11596: }
11597: return &unescape($value);
11598: }
11599:
11600: sub correct_line_ends {
11601: my ($result)=@_;
11602: $$result =~s/\r\n/\n/mg;
11603: $$result =~s/\r/\n/mg;
11604: }
11605: # ================================================================ Main Program
11606:
11607: sub goodbye {
11608: &logthis("Starting Shut down");
11609: #not converted to using infrastruture and probably shouldn't be
11610: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11611: #converted
11612: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11613: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11614: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11615: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11616: #1.1 only
11617: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11618: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11619: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11620: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11621: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11622: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11623: &logthis(sprintf("%-20s is %s",'hits',$hits));
11624: &flushcourselogs();
11625: &logthis("Shutting down");
11626: }
11627:
11628: sub get_dns {
11629: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11630: if (!$ignore_cache) {
11631: my ($content,$cached)=
11632: &Apache::lonnet::is_cached_new('dns',$url);
11633: if ($cached) {
11634: &$func($content,$hashref);
11635: return;
11636: }
11637: }
11638:
11639: my %alldns;
11640: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11641: foreach my $dns (<$config>) {
11642: next if ($dns !~ /^\^(\S*)/x);
11643: my $line = $1;
11644: my ($host,$protocol) = split(/:/,$line);
11645: if ($protocol ne 'https') {
11646: $protocol = 'http';
11647: }
11648: $alldns{$host} = $protocol;
11649: }
11650: while (%alldns) {
11651: my ($dns) = keys(%alldns);
11652: my $ua=new LWP::UserAgent;
11653: $ua->timeout(30);
11654: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11655: my $response=$ua->request($request);
11656: delete($alldns{$dns});
11657: next if ($response->is_error());
11658: my @content = split("\n",$response->content);
11659: unless ($nocache) {
11660: &do_cache_new('dns',$url,\@content,30*24*60*60);
11661: }
11662: &$func(\@content,$hashref);
11663: return;
11664: }
11665: close($config);
11666: my $which = (split('/',$url))[3];
11667: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11668: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11669: my @content = <$config>;
11670: &$func(\@content,$hashref);
11671: return;
11672: }
11673:
11674: # ------------------------------------------------------Get DNS checksums file
11675: sub parse_dns_checksums_tab {
11676: my ($lines,$hashref) = @_;
11677: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11678: my $loncaparev = &get_server_loncaparev($machine_dom);
11679: my ($release,$timestamp) = split(/\-/,$loncaparev);
11680: my (%chksum,%revnum);
11681: if (ref($lines) eq 'ARRAY') {
11682: chomp(@{$lines});
11683: my $versions = shift(@{$lines});
11684: my %supported;
11685: if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
11686: my $releaseslist = $1;
11687: if ($releaseslist =~ /,/) {
11688: map { $supported{$_} = 1; } split(/,/,$releaseslist);
11689: } elsif ($releaseslist) {
11690: $supported{$releaseslist} = 1;
11691: }
11692: }
11693: if ($supported{$release}) {
11694: my $matchthis = 0;
11695: foreach my $line (@{$lines}) {
11696: if ($line =~ /^(\d[\w\.]+)$/) {
11697: if ($matchthis) {
11698: last;
11699: } elsif ($1 eq $release) {
11700: $matchthis = 1;
11701: }
11702: } elsif ($matchthis) {
11703: my ($file,$version,$shasum) = split(/,/,$line);
11704: $chksum{$file} = $shasum;
11705: $revnum{$file} = $version;
11706: }
11707: }
11708: if (ref($hashref) eq 'HASH') {
11709: %{$hashref} = (
11710: sums => \%chksum,
11711: versions => \%revnum,
11712: );
11713: }
11714: }
11715: }
11716: return;
11717: }
11718:
11719: sub fetch_dns_checksums {
11720: my %checksums;
11721: &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
11722: \%checksums);
11723: return \%checksums;
11724: }
11725:
11726: # ------------------------------------------------------------ Read domain file
11727: {
11728: my $loaded;
11729: my %domain;
11730:
11731: sub parse_domain_tab {
11732: my ($lines) = @_;
11733: foreach my $line (@$lines) {
11734: next if ($line =~ /^(\#|\s*$ )/x);
11735:
11736: chomp($line);
11737: my ($name,@elements) = split(/:/,$line,9);
11738: my %this_domain;
11739: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11740: 'lang_def', 'city', 'longi', 'lati',
11741: 'primary') {
11742: $this_domain{$field} = shift(@elements);
11743: }
11744: $domain{$name} = \%this_domain;
11745: }
11746: }
11747:
11748: sub reset_domain_info {
11749: undef($loaded);
11750: undef(%domain);
11751: }
11752:
11753: sub load_domain_tab {
11754: my ($ignore_cache) = @_;
11755: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11756: my $fh;
11757: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11758: my @lines = <$fh>;
11759: &parse_domain_tab(\@lines);
11760: }
11761: close($fh);
11762: $loaded = 1;
11763: }
11764:
11765: sub domain {
11766: &load_domain_tab() if (!$loaded);
11767:
11768: my ($name,$what) = @_;
11769: return if ( !exists($domain{$name}) );
11770:
11771: if (!$what) {
11772: return $domain{$name}{'description'};
11773: }
11774: return $domain{$name}{$what};
11775: }
11776:
11777: sub domain_info {
11778: &load_domain_tab() if (!$loaded);
11779: return %domain;
11780: }
11781:
11782: }
11783:
11784:
11785: # ------------------------------------------------------------- Read hosts file
11786: {
11787: my %hostname;
11788: my %hostdom;
11789: my %libserv;
11790: my $loaded;
11791: my %name_to_host;
11792: my %internetdom;
11793: my %LC_dns_serv;
11794:
11795: sub parse_hosts_tab {
11796: my ($file) = @_;
11797: foreach my $configline (@$file) {
11798: next if ($configline =~ /^(\#|\s*$ )/x);
11799: chomp($configline);
11800: if ($configline =~ /^\^/) {
11801: if ($configline =~ /^\^([\w.\-]+)/) {
11802: $LC_dns_serv{$1} = 1;
11803: }
11804: next;
11805: }
11806: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11807: $name=~s/\s//g;
11808: if ($id && $domain && $role && $name) {
11809: $hostname{$id}=$name;
11810: push(@{$name_to_host{$name}}, $id);
11811: $hostdom{$id}=$domain;
11812: if ($role eq 'library') { $libserv{$id}=$name; }
11813: if (defined($protocol)) {
11814: if ($protocol eq 'https') {
11815: $protocol{$id} = $protocol;
11816: } else {
11817: $protocol{$id} = 'http';
11818: }
11819: } else {
11820: $protocol{$id} = 'http';
11821: }
11822: if (defined($intdom)) {
11823: $internetdom{$id} = $intdom;
11824: }
11825: }
11826: }
11827: }
11828:
11829: sub reset_hosts_info {
11830: &purge_remembered();
11831: &reset_domain_info();
11832: &reset_hosts_ip_info();
11833: undef(%name_to_host);
11834: undef(%hostname);
11835: undef(%hostdom);
11836: undef(%libserv);
11837: undef($loaded);
11838: }
11839:
11840: sub load_hosts_tab {
11841: my ($ignore_cache) = @_;
11842: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11843: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11844: my @config = <$config>;
11845: &parse_hosts_tab(\@config);
11846: close($config);
11847: $loaded=1;
11848: }
11849:
11850: sub hostname {
11851: &load_hosts_tab() if (!$loaded);
11852:
11853: my ($lonid) = @_;
11854: return $hostname{$lonid};
11855: }
11856:
11857: sub all_hostnames {
11858: &load_hosts_tab() if (!$loaded);
11859:
11860: return %hostname;
11861: }
11862:
11863: sub all_names {
11864: &load_hosts_tab() if (!$loaded);
11865:
11866: return %name_to_host;
11867: }
11868:
11869: sub all_host_domain {
11870: &load_hosts_tab() if (!$loaded);
11871: return %hostdom;
11872: }
11873:
11874: sub is_library {
11875: &load_hosts_tab() if (!$loaded);
11876:
11877: return exists($libserv{$_[0]});
11878: }
11879:
11880: sub all_library {
11881: &load_hosts_tab() if (!$loaded);
11882:
11883: return %libserv;
11884: }
11885:
11886: sub unique_library {
11887: #2x reverse removes all hostnames that appear more than once
11888: my %unique = reverse &all_library();
11889: return reverse %unique;
11890: }
11891:
11892: sub get_servers {
11893: &load_hosts_tab() if (!$loaded);
11894:
11895: my ($domain,$type) = @_;
11896: my %possible_hosts = ($type eq 'library') ? %libserv
11897: : %hostname;
11898: my %result;
11899: if (ref($domain) eq 'ARRAY') {
11900: while ( my ($host,$hostname) = each(%possible_hosts)) {
11901: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11902: $result{$host} = $hostname;
11903: }
11904: }
11905: } else {
11906: while ( my ($host,$hostname) = each(%possible_hosts)) {
11907: if ($hostdom{$host} eq $domain) {
11908: $result{$host} = $hostname;
11909: }
11910: }
11911: }
11912: return %result;
11913: }
11914:
11915: sub get_unique_servers {
11916: my %unique = reverse &get_servers(@_);
11917: return reverse %unique;
11918: }
11919:
11920: sub host_domain {
11921: &load_hosts_tab() if (!$loaded);
11922:
11923: my ($lonid) = @_;
11924: return $hostdom{$lonid};
11925: }
11926:
11927: sub all_domains {
11928: &load_hosts_tab() if (!$loaded);
11929:
11930: my %seen;
11931: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11932: return @uniq;
11933: }
11934:
11935: sub internet_dom {
11936: &load_hosts_tab() if (!$loaded);
11937:
11938: my ($lonid) = @_;
11939: return $internetdom{$lonid};
11940: }
11941:
11942: sub is_LC_dns {
11943: &load_hosts_tab() if (!$loaded);
11944:
11945: my ($hostname) = @_;
11946: return exists($LC_dns_serv{$hostname});
11947: }
11948:
11949: }
11950:
11951: {
11952: my %iphost;
11953: my %name_to_ip;
11954: my %lonid_to_ip;
11955:
11956: sub get_hosts_from_ip {
11957: my ($ip) = @_;
11958: my %iphosts = &get_iphost();
11959: if (ref($iphosts{$ip})) {
11960: return @{$iphosts{$ip}};
11961: }
11962: return;
11963: }
11964:
11965: sub reset_hosts_ip_info {
11966: undef(%iphost);
11967: undef(%name_to_ip);
11968: undef(%lonid_to_ip);
11969: }
11970:
11971: sub get_host_ip {
11972: my ($lonid) = @_;
11973: if (exists($lonid_to_ip{$lonid})) {
11974: return $lonid_to_ip{$lonid};
11975: }
11976: my $name=&hostname($lonid);
11977: my $ip = gethostbyname($name);
11978: return if (!$ip || length($ip) ne 4);
11979: $ip=inet_ntoa($ip);
11980: $name_to_ip{$name} = $ip;
11981: $lonid_to_ip{$lonid} = $ip;
11982: return $ip;
11983: }
11984:
11985: sub get_iphost {
11986: my ($ignore_cache) = @_;
11987:
11988: if (!$ignore_cache) {
11989: if (%iphost) {
11990: return %iphost;
11991: }
11992: my ($ip_info,$cached)=
11993: &Apache::lonnet::is_cached_new('iphost','iphost');
11994: if ($cached) {
11995: %iphost = %{$ip_info->[0]};
11996: %name_to_ip = %{$ip_info->[1]};
11997: %lonid_to_ip = %{$ip_info->[2]};
11998: return %iphost;
11999: }
12000: }
12001:
12002: # get yesterday's info for fallback
12003: my %old_name_to_ip;
12004: my ($ip_info,$cached)=
12005: &Apache::lonnet::is_cached_new('iphost','iphost');
12006: if ($cached) {
12007: %old_name_to_ip = %{$ip_info->[1]};
12008: }
12009:
12010: my %name_to_host = &all_names();
12011: foreach my $name (keys(%name_to_host)) {
12012: my $ip;
12013: if (!exists($name_to_ip{$name})) {
12014: $ip = gethostbyname($name);
12015: if (!$ip || length($ip) ne 4) {
12016: if (defined($old_name_to_ip{$name})) {
12017: $ip = $old_name_to_ip{$name};
12018: &logthis("Can't find $name defaulting to old $ip");
12019: } else {
12020: &logthis("Name $name no IP found");
12021: next;
12022: }
12023: } else {
12024: $ip=inet_ntoa($ip);
12025: }
12026: $name_to_ip{$name} = $ip;
12027: } else {
12028: $ip = $name_to_ip{$name};
12029: }
12030: foreach my $id (@{ $name_to_host{$name} }) {
12031: $lonid_to_ip{$id} = $ip;
12032: }
12033: push(@{$iphost{$ip}},@{$name_to_host{$name}});
12034: }
12035: &do_cache_new('iphost','iphost',
12036: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12037: 48*60*60);
12038:
12039: return %iphost;
12040: }
12041:
12042: #
12043: # Given a DNS returns the loncapa host name for that DNS
12044: #
12045: sub host_from_dns {
12046: my ($dns) = @_;
12047: my @hosts;
12048: my $ip;
12049:
12050: if (exists($name_to_ip{$dns})) {
12051: $ip = $name_to_ip{$dns};
12052: }
12053: if (!$ip) {
12054: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12055: if (length($ip) == 4) {
12056: $ip = &IO::Socket::inet_ntoa($ip);
12057: }
12058: }
12059: if ($ip) {
12060: @hosts = get_hosts_from_ip($ip);
12061: return $hosts[0];
12062: }
12063: return undef;
12064: }
12065:
12066: sub get_internet_names {
12067: my ($lonid) = @_;
12068: return if ($lonid eq '');
12069: my ($idnref,$cached)=
12070: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12071: if ($cached) {
12072: return $idnref;
12073: }
12074: my $ip = &get_host_ip($lonid);
12075: my @hosts = &get_hosts_from_ip($ip);
12076: my %iphost = &get_iphost();
12077: my (@idns,%seen);
12078: foreach my $id (@hosts) {
12079: my $dom = &host_domain($id);
12080: my $prim_id = &domain($dom,'primary');
12081: my $prim_ip = &get_host_ip($prim_id);
12082: next if ($seen{$prim_ip});
12083: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12084: foreach my $id (@{$iphost{$prim_ip}}) {
12085: my $intdom = &internet_dom($id);
12086: unless (grep(/^\Q$intdom\E$/,@idns)) {
12087: push(@idns,$intdom);
12088: }
12089: }
12090: }
12091: $seen{$prim_ip} = 1;
12092: }
12093: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12094: }
12095:
12096: }
12097:
12098: sub all_loncaparevs {
12099: 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);
12100: }
12101:
12102: BEGIN {
12103:
12104: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12105: unless ($readit) {
12106: {
12107: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12108: %perlvar = (%perlvar,%{$configvars});
12109: }
12110:
12111:
12112: # ------------------------------------------------------ Read spare server file
12113: {
12114: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12115:
12116: while (my $configline=<$config>) {
12117: chomp($configline);
12118: if ($configline) {
12119: my ($host,$type) = split(':',$configline,2);
12120: if (!defined($type) || $type eq '') { $type = 'default' };
12121: push(@{ $spareid{$type} }, $host);
12122: }
12123: }
12124: close($config);
12125: }
12126: # ------------------------------------------------------------ Read permissions
12127: {
12128: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12129:
12130: while (my $configline=<$config>) {
12131: chomp($configline);
12132: if ($configline) {
12133: my ($role,$perm)=split(/ /,$configline);
12134: if ($perm ne '') { $pr{$role}=$perm; }
12135: }
12136: }
12137: close($config);
12138: }
12139:
12140: # -------------------------------------------- Read plain texts for permissions
12141: {
12142: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12143:
12144: while (my $configline=<$config>) {
12145: chomp($configline);
12146: if ($configline) {
12147: my ($short,@plain)=split(/:/,$configline);
12148: %{$prp{$short}} = ();
12149: if (@plain > 0) {
12150: $prp{$short}{'std'} = $plain[0];
12151: for (my $i=1; $i<@plain; $i++) {
12152: $prp{$short}{'alt'.$i} = $plain[$i];
12153: }
12154: }
12155: }
12156: }
12157: close($config);
12158: }
12159:
12160: # ---------------------------------------------------------- Read package table
12161: {
12162: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12163:
12164: while (my $configline=<$config>) {
12165: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12166: chomp($configline);
12167: my ($short,$plain)=split(/:/,$configline);
12168: my ($pack,$name)=split(/\&/,$short);
12169: if ($plain ne '') {
12170: $packagetab{$pack.'&'.$name.'&name'}=$name;
12171: $packagetab{$short}=$plain;
12172: }
12173: }
12174: close($config);
12175: }
12176:
12177: # ---------------------------------------------------------- Read loncaparev table
12178: {
12179: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12180: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12181: while (my $configline=<$config>) {
12182: chomp($configline);
12183: my ($hostid,$loncaparev)=split(/:/,$configline);
12184: $loncaparevs{$hostid}=$loncaparev;
12185: }
12186: close($config);
12187: }
12188: }
12189: }
12190:
12191: # ---------------------------------------------------------- Read serverhostID table
12192: {
12193: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12194: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12195: while (my $configline=<$config>) {
12196: chomp($configline);
12197: my ($name,$id)=split(/:/,$configline);
12198: $serverhomeIDs{$name}=$id;
12199: }
12200: close($config);
12201: }
12202: }
12203: }
12204:
12205: {
12206: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12207: if (-e $file) {
12208: my $parser = HTML::LCParser->new($file);
12209: while (my $token = $parser->get_token()) {
12210: if ($token->[0] eq 'S') {
12211: my $item = $token->[1];
12212: my $name = $token->[2]{'name'};
12213: my $value = $token->[2]{'value'};
12214: if ($item ne '' && $name ne '' && $value ne '') {
12215: my $release = $parser->get_text();
12216: $release =~ s/(^\s*|\s*$ )//gx;
12217: $needsrelease{$item.':'.$name.':'.$value} = $release;
12218: }
12219: }
12220: }
12221: }
12222: }
12223:
12224: # ---------------------------------------------------------- Read managers table
12225: {
12226: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12227: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12228: while (my $configline=<$config>) {
12229: chomp($configline);
12230: next if ($configline =~ /^\#/);
12231: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12232: $managerstab{$configline} = 1;
12233: }
12234: }
12235: close($config);
12236: }
12237: }
12238: }
12239:
12240: # ------------- set up temporary directory
12241: {
12242: $tmpdir = LONCAPA::tempdir();
12243:
12244: }
12245:
12246: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12247: 'compress_threshold'=> 20_000,
12248: });
12249:
12250: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12251: $dumpcount=0;
12252: $locknum=0;
12253:
12254: &logtouch();
12255: &logthis('<font color="yellow">INFO: Read configuration</font>');
12256: $readit=1;
12257: {
12258: use integer;
12259: my $test=(2**32)+1;
12260: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12261: &logthis(" Detected 64bit platform ($_64bit)");
12262: }
12263:
12264: {
12265: eval {
12266: ($apache) =
12267: (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
12268: };
12269: if ($@) {
12270: $apache = 1.3;
12271: }
12272: }
12273:
12274: }
12275: }
12276:
12277: 1;
12278: __END__
12279:
12280: =pod
12281:
12282: =head1 NAME
12283:
12284: Apache::lonnet - Subroutines to ask questions about things in the network.
12285:
12286: =head1 SYNOPSIS
12287:
12288: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12289:
12290: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12291:
12292: Common parameters:
12293:
12294: =over 4
12295:
12296: =item *
12297:
12298: $uname : an internal username (if $cname expecting a course Id specifically)
12299:
12300: =item *
12301:
12302: $udom : a domain (if $cdom expecting a course's domain specifically)
12303:
12304: =item *
12305:
12306: $symb : a resource instance identifier
12307:
12308: =item *
12309:
12310: $namespace : the name of a .db file that contains the data needed or
12311: being set.
12312:
12313: =back
12314:
12315: =head1 OVERVIEW
12316:
12317: lonnet provides subroutines which interact with the
12318: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12319: about classes, users, and resources.
12320:
12321: For many of these objects you can also use this to store data about
12322: them or modify them in various ways.
12323:
12324: =head2 Symbs
12325:
12326: To identify a specific instance of a resource, LON-CAPA uses symbols
12327: or "symbs"X<symb>. These identifiers are built from the URL of the
12328: map, the resource number of the resource in the map, and the URL of
12329: the resource itself. The latter is somewhat redundant, but might help
12330: if maps change.
12331:
12332: An example is
12333:
12334: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12335:
12336: The respective map entry is
12337:
12338: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12339: title="Problem 2">
12340: </resource>
12341:
12342: Symbs are used by the random number generator, as well as to store and
12343: restore data specific to a certain instance of for example a problem.
12344:
12345: =head2 Storing And Retrieving Data
12346:
12347: X<store()>X<cstore()>X<restore()>Three of the most important functions
12348: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12349: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12350: is is the non-critical message twin of cstore. These functions are for
12351: handlers to store a perl hash to a user's permanent data space in an
12352: easy manner, and to retrieve it again on another call. It is expected
12353: that a handler would use this once at the beginning to retrieve data,
12354: and then again once at the end to send only the new data back.
12355:
12356: The data is stored in the user's data directory on the user's
12357: homeserver under the ID of the course.
12358:
12359: The hash that is returned by restore will have all of the previous
12360: value for all of the elements of the hash.
12361:
12362: Example:
12363:
12364: #creating a hash
12365: my %hash;
12366: $hash{'foo'}='bar';
12367:
12368: #storing it
12369: &Apache::lonnet::cstore(\%hash);
12370:
12371: #changing a value
12372: $hash{'foo'}='notbar';
12373:
12374: #adding a new value
12375: $hash{'bar'}='foo';
12376: &Apache::lonnet::cstore(\%hash);
12377:
12378: #retrieving the hash
12379: my %history=&Apache::lonnet::restore();
12380:
12381: #print the hash
12382: foreach my $key (sort(keys(%history))) {
12383: print("\%history{$key} = $history{$key}");
12384: }
12385:
12386: Will print out:
12387:
12388: %history{1:foo} = bar
12389: %history{1:keys} = foo:timestamp
12390: %history{1:timestamp} = 990455579
12391: %history{2:bar} = foo
12392: %history{2:foo} = notbar
12393: %history{2:keys} = foo:bar:timestamp
12394: %history{2:timestamp} = 990455580
12395: %history{bar} = foo
12396: %history{foo} = notbar
12397: %history{timestamp} = 990455580
12398: %history{version} = 2
12399:
12400: Note that the special hash entries C<keys>, C<version> and
12401: C<timestamp> were added to the hash. C<version> will be equal to the
12402: total number of versions of the data that have been stored. The
12403: C<timestamp> attribute will be the UNIX time the hash was
12404: stored. C<keys> is available in every historical section to list which
12405: keys were added or changed at a specific historical revision of a
12406: hash.
12407:
12408: B<Warning>: do not store the hash that restore returns directly. This
12409: will cause a mess since it will restore the historical keys as if the
12410: were new keys. I.E. 1:foo will become 1:1:foo etc.
12411:
12412: Calling convention:
12413:
12414: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
12415: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
12416:
12417: For more detailed information, see lonnet specific documentation.
12418:
12419: =head1 RETURN MESSAGES
12420:
12421: =over 4
12422:
12423: =item * B<con_lost>: unable to contact remote host
12424:
12425: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12426: when the connection is brought back up
12427:
12428: =item * B<con_failed>: unable to contact remote host and unable to save message
12429: for later delivery
12430:
12431: =item * B<error:>: an error a occurred, a description of the error follows the :
12432:
12433: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12434: that was requested
12435:
12436: =back
12437:
12438: =head1 PUBLIC SUBROUTINES
12439:
12440: =head2 Session Environment Functions
12441:
12442: =over 4
12443:
12444: =item *
12445: X<appenv()>
12446: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12447: the user envirnoment file, and will be restored for each access this
12448: user makes during this session, also modifies the %env for the current
12449: process. Optional rolesarrayref - if defined contains a reference to an array
12450: of roles which are exempt from the restriction on modifying user.role entries
12451: in the user's environment.db and in %env.
12452:
12453: =item *
12454: X<delenv()>
12455: B<delenv($delthis,$regexp)>: removes all items from the session
12456: environment file that begin with $delthis. If the
12457: optional second arg - $regexp - is true, $delthis is treated as a
12458: regular expression, otherwise \Q$delthis\E is used.
12459: The values are also deleted from the current processes %env.
12460:
12461: =item * get_env_multiple($name)
12462:
12463: gets $name from the %env hash, it seemlessly handles the cases where multiple
12464: values may be defined and end up as an array ref.
12465:
12466: returns an array of values
12467:
12468: =back
12469:
12470: =head2 User Information
12471:
12472: =over 4
12473:
12474: =item *
12475: X<queryauthenticate()>
12476: B<queryauthenticate($uname,$udom)>: try to determine user's current
12477: authentication scheme
12478:
12479: =item *
12480: X<authenticate()>
12481: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12482: authenticate user from domain's lib servers (first use the current
12483: one). C<$upass> should be the users password.
12484: $checkdefauth is optional (value is 1 if a check should be made to
12485: authenticate user using default authentication method, and allow
12486: account creation if username does not have account in the domain).
12487: $clientcancheckhost is optional (value is 1 if checking whether the
12488: server can host will occur on the client side in lonauth.pm).
12489:
12490: =item *
12491: X<homeserver()>
12492: B<homeserver($uname,$udom)>: find the server which has
12493: the user's directory and files (there must be only one), this caches
12494: the answer, and also caches if there is a borken connection.
12495:
12496: =item *
12497: X<idget()>
12498: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12499: (IDs are a unique resource in a domain, there must be only 1 ID per
12500: username, and only 1 username per ID in a specific domain) (returns
12501: hash: id=>name,id=>name)
12502:
12503: =item *
12504: X<idrget()>
12505: B<idrget($udom,@unames)>: find the IDs behind a list of
12506: usernames (returns hash: name=>id,name=>id)
12507:
12508: =item *
12509: X<idput()>
12510: B<idput($udom,%ids)>: store away a list of names and associated IDs
12511:
12512: =item *
12513: X<rolesinit()>
12514: B<rolesinit($udom,$username)>: get user privileges.
12515: returns user role, first access and timer interval hashes
12516:
12517: =item *
12518: X<privileged()>
12519: B<privileged($username,$domain)>: returns a true if user has a
12520: privileged and active role (i.e. su or dc), false otherwise.
12521:
12522: =item *
12523: X<getsection()>
12524: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12525: course $cname, return section name/number or '' for "not in course"
12526: and '-1' for "no section"
12527:
12528: =item *
12529: X<userenvironment()>
12530: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12531: passed in @what from the requested user's environment, returns a hash
12532:
12533: =item *
12534: X<userlog_query()>
12535: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12536: activity.log file. %filters defines filters applied when parsing the
12537: log file. These can be start or end timestamps, or the type of action
12538: - log to look for Login or Logout events, check for Checkin or
12539: Checkout, role for role selection. The response is in the form
12540: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12541: escaped strings of the action recorded in the activity.log file.
12542:
12543: =back
12544:
12545: =head2 User Roles
12546:
12547: =over 4
12548:
12549: =item *
12550:
12551: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12552: F: full access
12553: U,I,K: authentication modes (cxx only)
12554: '': forbidden
12555: 1: user needs to choose course
12556: 2: browse allowed
12557: A: passphrase authentication needed
12558:
12559: =item *
12560:
12561: constructaccess($url,$setpriv) : check for access to construction space URL
12562:
12563: See if the owner domain and name in the URL match those in the
12564: expected environment. If so, return three element list
12565: ($ownername,$ownerdomain,$ownerhome).
12566:
12567: Otherwise return the null string.
12568:
12569: If second argument 'setpriv' is true, it assigns the privileges,
12570: and returns the same three element list, unless the owner has
12571: blocked "ad hoc" Domain Coordinator access to the Author Space,
12572: in which case the null string is returned.
12573:
12574: =item *
12575:
12576: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12577: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12578: and course level
12579:
12580: =item *
12581:
12582: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12583: (rolesplain.tab); plain text explanation of a user role term.
12584: $type is Course (default) or Community.
12585: If $forcedefault evaluates to true, text returned will be default
12586: text for $type. Otherwise, if this is a course, the text returned
12587: will be a custom name for the role (if defined in the course's
12588: environment). If no custom name is defined the default is returned.
12589:
12590: =item *
12591:
12592: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12593: All arguments are optional. Returns a hash of a roles, either for
12594: co-author/assistant author roles for a user's Construction Space
12595: (default), or if $context is 'userroles', roles for the user himself,
12596: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12597: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12598: For each key, value is set to colon-separated start and end times for
12599: the role. If no username and domain are specified, will default to
12600: current user/domain. Types, roles, and roledoms are references to arrays
12601: of role statuses (active, future or previous), roles
12602: (e.g., cc,in, st etc.) and domains of the roles which can be used
12603: to restrict the list of roles reported. If no array ref is
12604: provided for types, will default to return only active roles.
12605:
12606: =item *
12607:
12608: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12609: user: $uname:$udom has a role in the course: $cdom_$cnum.
12610:
12611: Additional optional arguments are: $type (if role checking is to be restricted
12612: to certain user status types -- previous (expired roles), active (currently
12613: available roles) or future (roles available in the future), and
12614: $hideprivileged -- if true will not report course roles for users who
12615: have active Domain Coordinator role in course's domain or in additional
12616: domains (specified in 'Domains to check for privileged users' in course
12617: environment -- set via: Course Settings -> Classlists and staff listing).
12618:
12619: =item *
12620:
12621: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12622: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12623: $possdomains and $possroles are optional array refs -- to domains to check and
12624: roles to check. If $possdomains is not specified, a dump will be done of the
12625: users' roles.db to check for a dc or su role in any domain. This can be
12626: time consuming if &privileged is called repeatedly (e.g., when displaying a
12627: classlist), so in such cases, supplying a $possdomains array is preferred, as
12628: this then allows &privileged_by_domain() to be used, which caches the identity
12629: of privileged users, eliminating the need for repeated calls to &dump().
12630:
12631: =item *
12632:
12633: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12634: where the outer hash keys are domains specified in the $possdomains array ref,
12635: next inner hash keys are privileged roles specified in the $roles array ref,
12636: and the innermost hash contains key = value pairs for username:domain = end:start
12637: for active or future "privileged" users with that role in that domain. To avoid
12638: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12639: innerhash are cached using priv_$role and $dom as the identifiers.
12640:
12641: =back
12642:
12643: =head2 User Modification
12644:
12645: =over 4
12646:
12647: =item *
12648:
12649: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12650: user for the level given by URL. Optional start and end dates (leave empty
12651: string or zero for "no date")
12652:
12653: =item *
12654:
12655: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12656: change a users, password, possible return values are: ok,
12657: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12658: refused
12659:
12660: =item *
12661:
12662: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12663:
12664: =item *
12665:
12666: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12667: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12668:
12669: will update user information (firstname,middlename,lastname,generation,
12670: permanentemail), and if forceid is true, student/employee ID also.
12671: A user's institutional affiliation(s) can also be updated.
12672: User information fields will not be overwritten with empty entries
12673: unless the field is included in the $candelete array reference.
12674: This array is included when a single user is modified via "Manage Users",
12675: or when Autoupdate.pl is run by cron in a domain.
12676:
12677: =item *
12678:
12679: modifystudent
12680:
12681: modify a student's enrollment and identification information.
12682: The course id is resolved based on the current users environment.
12683: This means the envoking user must be a course coordinator or otherwise
12684: associated with a course.
12685:
12686: This call is essentially a wrapper for lonnet::modifyuser and
12687: lonnet::modify_student_enrollment
12688:
12689: Inputs:
12690:
12691: =over 4
12692:
12693: =item B<$udom> Student's loncapa domain
12694:
12695: =item B<$uname> Student's loncapa login name
12696:
12697: =item B<$uid> Student/Employee ID
12698:
12699: =item B<$umode> Student's authentication mode
12700:
12701: =item B<$upass> Student's password
12702:
12703: =item B<$first> Student's first name
12704:
12705: =item B<$middle> Student's middle name
12706:
12707: =item B<$last> Student's last name
12708:
12709: =item B<$gene> Student's generation
12710:
12711: =item B<$usec> Student's section in course
12712:
12713: =item B<$end> Unix time of the roles expiration
12714:
12715: =item B<$start> Unix time of the roles start date
12716:
12717: =item B<$forceid> If defined, allow $uid to be changed
12718:
12719: =item B<$desiredhome> server to use as home server for student
12720:
12721: =item B<$email> Student's permanent e-mail address
12722:
12723: =item B<$type> Type of enrollment (auto or manual)
12724:
12725: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12726:
12727: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12728:
12729: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12730:
12731: =item B<$context> role change context (shown in User Management Logs display in a course)
12732:
12733: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12734:
12735: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
12736:
12737: =back
12738:
12739: =item *
12740:
12741: modify_student_enrollment
12742:
12743: Change a students enrollment status in a class. The environment variable
12744: 'role.request.course' must be defined for this function to proceed.
12745:
12746: Inputs:
12747:
12748: =over 4
12749:
12750: =item $udom, students domain
12751:
12752: =item $uname, students name
12753:
12754: =item $uid, students user id
12755:
12756: =item $first, students first name
12757:
12758: =item $middle
12759:
12760: =item $last
12761:
12762: =item $gene
12763:
12764: =item $usec
12765:
12766: =item $end
12767:
12768: =item $start
12769:
12770: =item $type
12771:
12772: =item $locktype
12773:
12774: =item $cid
12775:
12776: =item $selfenroll
12777:
12778: =item $context
12779:
12780: =item $credits, number of credits student will earn from this class
12781:
12782: =back
12783:
12784:
12785: =item *
12786:
12787: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12788: custom role; give a custom role to a user for the level given by URL. Specify
12789: name and domain of role author, and role name
12790:
12791: =item *
12792:
12793: revokerole($udom,$uname,$url,$role) : revoke a role for url
12794:
12795: =item *
12796:
12797: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12798:
12799: =back
12800:
12801: =head2 Course Infomation
12802:
12803: =over 4
12804:
12805: =item *
12806:
12807: coursedescription($courseid,$options) : returns a hash of information about the
12808: specified course id, including all environment settings for the
12809: course, the description of the course will be in the hash under the
12810: key 'description'
12811:
12812: $options is an optional parameter that if supplied is a hash reference that controls
12813: what how this function works. It has the following key/values:
12814:
12815: =over 4
12816:
12817: =item freshen_cache
12818:
12819: If defined, and the environment cache for the course is valid, it is
12820: returned in the returned hash.
12821:
12822: =item one_time
12823:
12824: If defined, the last cache time is set to _now_
12825:
12826: =item user
12827:
12828: If defined, the supplied username is used instead of the current user.
12829:
12830:
12831: =back
12832:
12833: =item *
12834:
12835: resdata($name,$domain,$type,@which) : request for current parameter
12836: setting for a specific $type, where $type is either 'course' or 'user',
12837: @what should be a list of parameters to ask about. This routine caches
12838: answers for 5 minutes.
12839:
12840: =item *
12841:
12842: get_courseresdata($courseid, $domain) : dump the entire course resource
12843: data base, returning a hash that is keyed by the resource name and has
12844: values that are the resource value. I believe that the timestamps and
12845: versions are also returned.
12846:
12847: =back
12848:
12849: =head2 Course Modification
12850:
12851: =over 4
12852:
12853: =item *
12854:
12855: writecoursepref($courseid,%prefs) : write preferences (environment
12856: database) for a course
12857:
12858: =item *
12859:
12860: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12861:
12862: =item *
12863:
12864: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12865:
12866: =item *
12867:
12868: is_course($courseid), is_course($cdom, $cnum)
12869:
12870: Accepts either a combined $courseid (in the form of domain_courseid) or the
12871: two component version $cdom, $cnum. It checks if the specified course exists.
12872:
12873: Returns:
12874: undef if the course doesn't exist, otherwise
12875: in scalar context the combined courseid.
12876: in list context the two components of the course identifier, domain and
12877: courseid.
12878:
12879: =back
12880:
12881: =head2 Resource Subroutines
12882:
12883: =over 4
12884:
12885: =item *
12886:
12887: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12888:
12889: =item *
12890:
12891: repcopy($filename) : subscribes to the requested file, and attempts to
12892: replicate from the owning library server, Might return
12893: 'unavailable', 'not_found', 'forbidden', 'ok', or
12894: 'bad_request', also attempts to grab the metadata for the
12895: resource. Expects the local filesystem pathname
12896: (/home/httpd/html/res/....)
12897:
12898: =back
12899:
12900: =head2 Resource Information
12901:
12902: =over 4
12903:
12904: =item *
12905:
12906: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12907: a vairety of different possible values, $varname should be a request
12908: string, and the other parameters can be used to specify who and what
12909: one is asking about.
12910:
12911: Possible values for $varname are environment.lastname (or other item
12912: from the envirnment hash), user.name (or someother aspect about the
12913: user), resource.0.maxtries (or some other part and parameter of a
12914: resource)
12915:
12916: =item *
12917:
12918: directcondval($number) : get current value of a condition; reads from a state
12919: string
12920:
12921: =item *
12922:
12923: condval($condidx) : value of condition index based on state
12924:
12925: =item *
12926:
12927: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12928: resource's metadata, $what should be either a specific key, or either
12929: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12930: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12931:
12932: this function automatically caches all requests
12933:
12934: =item *
12935:
12936: metadata_query($query,$custom,$customshow) : make a metadata query against the
12937: network of library servers; returns file handle of where SQL and regex results
12938: will be stored for query
12939:
12940: =item *
12941:
12942: symbread($filename) : return symbolic list entry (filename argument optional);
12943: returns the data handle
12944:
12945: =item *
12946:
12947: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12948: and is a possible symb for the URL in $thisfn, and if is an encrypted
12949: resource that the user accessed using /enc/ returns a 1 on success, 0
12950: on failure, user must be in a course, as it assumes the existence of
12951: the course initial hash, and uses $env('request.course.id'}. The third
12952: arg is an optional reference to a scalar. If this arg is passed in the
12953: call to symbverify, it will be set to 1 if the symb has been set to be
12954: encrypted; otherwise it will be null.
12955:
12956: =item *
12957:
12958: symbclean($symb) : removes versions numbers from a symb, returns the
12959: cleaned symb
12960:
12961: =item *
12962:
12963: is_on_map($uri) : checks if the $uri is somewhere on the current
12964: course map, user must be in a course for it to work.
12965:
12966: =item *
12967:
12968: numval($salt) : return random seed value (addend for rndseed)
12969:
12970: =item *
12971:
12972: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12973: a random seed, all arguments are optional, if they aren't sent it uses the
12974: environment to derive them. Note: if symb isn't sent and it can't get one
12975: from &symbread it will use the current time as its return value
12976:
12977: =item *
12978:
12979: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12980: unfakeable, receipt
12981:
12982: =item *
12983:
12984: receipt() : API to ireceipt working off of env values; given out to users
12985:
12986: =item *
12987:
12988: countacc($url) : count the number of accesses to a given URL
12989:
12990: =item *
12991:
12992: 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
12993:
12994: =item *
12995:
12996: 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)
12997:
12998: =item *
12999:
13000: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13001:
13002: =item *
13003:
13004: devalidate($symb) : devalidate temporary spreadsheet calculations,
13005: forcing spreadsheet to reevaluate the resource scores next time.
13006:
13007: =item *
13008:
13009: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13010: when viewing in course context.
13011:
13012: input: six args -- filename (decluttered), course number, course domain,
13013: url, symb (if registered) and group (if this is a
13014: group item -- e.g., bulletin board, group page etc.).
13015:
13016: output: array of five scalars --
13017: $cfile -- url for file editing if editable on current server
13018: $home -- homeserver of resource (i.e., for author if published,
13019: or course if uploaded.).
13020: $switchserver -- 1 if server switch will be needed.
13021: $forceedit -- 1 if icon/link should be to go to edit mode
13022: $forceview -- 1 if icon/link should be to go to view mode
13023:
13024: =item *
13025:
13026: is_course_upload($file,$cnum,$cdom)
13027:
13028: Used in course context to determine if current file was uploaded to
13029: the course (i.e., would be found in /userfiles/docs on the course's
13030: homeserver.
13031:
13032: input: 3 args -- filename (decluttered), course number and course domain.
13033: output: boolean -- 1 if file was uploaded.
13034:
13035: =back
13036:
13037: =head2 Storing/Retreiving Data
13038:
13039: =over 4
13040:
13041: =item *
13042:
13043: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13044: for this url; hashref needs to be given and should be a \%hashname; the
13045: remaining args aren't required and if they aren't passed or are '' they will
13046: be derived from the env
13047:
13048: =item *
13049:
13050: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13051: uses critical subroutine
13052:
13053: =item *
13054:
13055: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13056: all args are optional
13057:
13058: =item *
13059:
13060: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13061: dumps the complete (or key matching regexp) namespace into a hash
13062: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13063: normally &store()ed into
13064:
13065: $range should be either an integer '100' (give me the first 100
13066: matching records)
13067: or be two integers sperated by a - with no spaces
13068: '30-50' (give me the 30th through the 50th matching
13069: records)
13070:
13071:
13072: =item *
13073:
13074: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13075: replaces a &store() version of data with a replacement set of data
13076: for a particular resource in a namespace passed in the $storehash hash
13077: reference
13078:
13079: =item *
13080:
13081: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13082: works very similar to store/cstore, but all data is stored in a
13083: temporary location and can be reset using tmpreset, $storehash should
13084: be a hash reference, returns nothing on success
13085:
13086: =item *
13087:
13088: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13089: similar to restore, but all data is stored in a temporary location and
13090: can be reset using tmpreset. Returns a hash of values on success,
13091: error string otherwise.
13092:
13093: =item *
13094:
13095: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13096: deltes all keys for $symb form the temporary storage hash.
13097:
13098: =item *
13099:
13100: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13101: reference filled in from namesp ($udom and $uname are optional)
13102:
13103: =item *
13104:
13105: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13106: namesp ($udom and $uname are optional)
13107:
13108: =item *
13109:
13110: dump($namespace,$udom,$uname,$regexp,$range) :
13111: dumps the complete (or key matching regexp) namespace into a hash
13112: ($udom, $uname, $regexp, $range are optional)
13113:
13114: $range should be either an integer '100' (give me the first 100
13115: matching records)
13116: or be two integers sperated by a - with no spaces
13117: '30-50' (give me the 30th through the 50th matching
13118: records)
13119: =item *
13120:
13121: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13122: $store can be a scalar, an array reference, or if the amount to be
13123: incremented is > 1, a hash reference.
13124:
13125: ($udom and $uname are optional)
13126:
13127: =item *
13128:
13129: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13130: ($udom and $uname are optional)
13131:
13132: =item *
13133:
13134: cput($namespace,$storehash,$udom,$uname) : critical put
13135: ($udom and $uname are optional)
13136:
13137: =item *
13138:
13139: newput($namespace,$storehash,$udom,$uname) :
13140:
13141: Attempts to store the items in the $storehash, but only if they don't
13142: currently exist, if this succeeds you can be certain that you have
13143: successfully created a new key value pair in the $namespace db.
13144:
13145:
13146: Args:
13147: $namespace: name of database to store values to
13148: $storehash: hashref to store to the db
13149: $udom: (optional) domain of user containing the db
13150: $uname: (optional) name of user caontaining the db
13151:
13152: Returns:
13153: 'ok' -> succeeded in storing all keys of $storehash
13154: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13155: least <key> already existed in the db (other
13156: requested keys may also already exist)
13157: 'error: <msg>' -> unable to tie the DB or other error occurred
13158: 'con_lost' -> unable to contact request server
13159: 'refused' -> action was not allowed by remote machine
13160:
13161:
13162: =item *
13163:
13164: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13165: reference filled in from namesp (encrypts the return communication)
13166: ($udom and $uname are optional)
13167:
13168: =item *
13169:
13170: log($udom,$name,$home,$message) : write to permanent log for user; use
13171: critical subroutine
13172:
13173: =item *
13174:
13175: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13176: array reference filled in from namespace found in domain level on either
13177: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13178:
13179: =item *
13180:
13181: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13182: domain level either on specified domain server ($uhome) or primary domain
13183: server ($udom and $uhome are optional)
13184:
13185: =item *
13186:
13187: get_domain_defaults($target_domain) : returns hash with defaults for
13188: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
13189: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
13190: or localauth), initial password or a kerberos realm, language (e.g., en-us).
13191: Values are retrieved from cache (if current), or from domain's configuration.db
13192: (if available), or lastly from values in lonTabs/dns_domain,tab,
13193: or lonTabs/domain.tab.
13194:
13195: %domdefaults = &get_auth_defaults($target_domain);
13196:
13197: =back
13198:
13199: =head2 Network Status Functions
13200:
13201: =over 4
13202:
13203: =item *
13204:
13205: dirlist() : return directory list based on URI (first arg).
13206:
13207: Inputs: 1 required, 5 optional.
13208:
13209: =over
13210:
13211: =item
13212: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13213:
13214: =item
13215: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13216:
13217: =item
13218: $username - username of user/course to be listed. Extracted from $uri if absent.
13219:
13220: =item
13221: $getpropath - boolean: 1 if prepend path using &propath().
13222:
13223: =item
13224: $getuserdir - boolean: 1 if prepend path for "userfiles".
13225:
13226: =item
13227: $alternateRoot - path to prepend in place of path from $uri.
13228:
13229: =back
13230:
13231: Returns: Array of up to two items.
13232:
13233: =over
13234:
13235: a reference to an array of files/subdirectories
13236:
13237: =over
13238:
13239: Each element in the array of files/subdirectories is a & separated list of
13240: item name and the result of running stat on the item. If dirlist was requested
13241: for a file instead of a directory, the item name will be ''. For a directory
13242: listing, if the item is a metadata file, the element will end &N&M
13243: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13244: default copyright set (1).
13245:
13246: =back
13247:
13248: a scalar containing error condition (if encountered).
13249:
13250: =over
13251:
13252: =item
13253: no_host (no homeserver identified for $username:$domain).
13254:
13255: =item
13256: no_such_host (server contacted for listing not identified as valid host).
13257:
13258: =item
13259: con_lost (connection to remote server failed).
13260:
13261: =item
13262: refused (invalid $username:$domain received on lond side).
13263:
13264: =item
13265: no_such_dir (directory at specified path on lond side does not exist).
13266:
13267: =item
13268: empty (directory at specified path on lond side is empty).
13269:
13270: =over
13271:
13272: This is currently not encountered because the &ls3, &ls2,
13273: &ls (_handler) routines on the lond side do not filter out
13274: . and .. from a directory listing.
13275:
13276: =back
13277:
13278: =back
13279:
13280: =back
13281:
13282: =item *
13283:
13284: spareserver() : find server with least workload from spare.tab
13285:
13286:
13287: =item *
13288:
13289: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13290: if there is no corresponding loncapa host.
13291:
13292: =back
13293:
13294:
13295: =head2 Apache Request
13296:
13297: =over 4
13298:
13299: =item *
13300:
13301: ssi($url,%hash) : server side include, does a complete request cycle on url to
13302: localhost, posts hash
13303:
13304: =back
13305:
13306: =head2 Data to String to Data
13307:
13308: =over 4
13309:
13310: =item *
13311:
13312: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13313: and '&' separators, supports elements that are arrayrefs and hashrefs
13314:
13315: =item *
13316:
13317: hashref2str($hashref) : convert a hashref into a string complete with
13318: escaping and '=' and '&' separators, supports elements that are
13319: arrayrefs and hashrefs
13320:
13321: =item *
13322:
13323: arrayref2str($arrayref) : convert an arrayref into a string complete
13324: with escaping and '&' separators, supports elements that are arrayrefs
13325: and hashrefs
13326:
13327: =item *
13328:
13329: str2hash($string) : convert string to hash using unescaping and
13330: splitting on '=' and '&', supports elements that are arrayrefs and
13331: hashrefs
13332:
13333: =item *
13334:
13335: str2array($string) : convert string to hash using unescaping and
13336: splitting on '&', supports elements that are arrayrefs and hashrefs
13337:
13338: =back
13339:
13340: =head2 Logging Routines
13341:
13342:
13343: These routines allow one to make log messages in the lonnet.log and
13344: lonnet.perm logfiles.
13345:
13346: =over 4
13347:
13348: =item *
13349:
13350: logtouch() : make sure the logfile, lonnet.log, exists
13351:
13352: =item *
13353:
13354: logthis() : append message to the normal lonnet.log file, it gets
13355: preiodically rolled over and deleted.
13356:
13357: =item *
13358:
13359: logperm() : append a permanent message to lonnet.perm.log, this log
13360: file never gets deleted by any automated portion of the system, only
13361: messages of critical importance should go in here.
13362:
13363:
13364: =back
13365:
13366: =head2 General File Helper Routines
13367:
13368: =over 4
13369:
13370: =item *
13371:
13372: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13373: (a) files in /uploaded
13374: (i) If a local copy of the file exists -
13375: compares modification date of local copy with last-modified date for
13376: definitive version stored on home server for course. If local copy is
13377: stale, requests a new version from the home server and stores it.
13378: If the original has been removed from the home server, then local copy
13379: is unlinked.
13380: (ii) If local copy does not exist -
13381: requests the file from the home server and stores it.
13382:
13383: If $caller is 'uploadrep':
13384: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13385: for request for files originally uploaded via DOCS.
13386: - returns 'ok' if fresh local copy now available, -1 otherwise.
13387:
13388: Otherwise:
13389: This indicates a call from the content generation phase of the request.
13390: - returns the entire contents of the file or -1.
13391:
13392: (b) files in /res
13393: - returns the entire contents of a file or -1;
13394: it properly subscribes to and replicates the file if neccessary.
13395:
13396:
13397: =item *
13398:
13399: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13400: reference
13401:
13402: returns either a stat() list of data about the file or an empty list
13403: if the file doesn't exist or couldn't find out about it (connection
13404: problems or user unknown)
13405:
13406: =item *
13407:
13408: filelocation($dir,$file) : returns file system location of a file
13409: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13410: directory that relative $file lookups are to looked in ($dir of /a/dir
13411: and a file of ../bob will become /a/bob)
13412:
13413: =item *
13414:
13415: hreflocation($dir,$file) : returns file system location or a URL; same as
13416: filelocation except for hrefs
13417:
13418: =item *
13419:
13420: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13421:
13422: =back
13423:
13424: =head2 Usererfile file routines (/uploaded*)
13425:
13426: =over 4
13427:
13428: =item *
13429:
13430: userfileupload(): main rotine for putting a file in a user or course's
13431: filespace, arguments are,
13432:
13433: formname - required - this is the name of the element in $env where the
13434: filename, and the contents of the file to create/modifed exist
13435: the filename is in $env{'form.'.$formname.'.filename'} and the
13436: contents of the file is located in $env{'form.'.$formname}
13437: context - if coursedoc, store the file in the course of the active role
13438: of the current user;
13439: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13440: if 'canceloverwrite': delete file in tmp/overwrites directory
13441: subdir - required - subdirectory to put the file in under ../userfiles/
13442: if undefined, it will be placed in "unknown"
13443:
13444: (This routine calls clean_filename() to remove any dangerous
13445: characters from the filename, and then calls finuserfileupload() to
13446: complete the transaction)
13447:
13448: returns either the url of the uploaded file (/uploaded/....) if successful
13449: and /adm/notfound.html if unsuccessful
13450:
13451: =item *
13452:
13453: clean_filename(): routine for cleaing a filename up for storage in
13454: userfile space, argument is:
13455:
13456: filename - proposed filename
13457:
13458: returns: the new clean filename
13459:
13460: =item *
13461:
13462: finishuserfileupload(): routine that creates and sends the file to
13463: userspace, probably shouldn't be called directly
13464:
13465: docuname: username or courseid of destination for the file
13466: docudom: domain of user/course of destination for the file
13467: formname: same as for userfileupload()
13468: fname: filename (including subdirectories) for the file
13469: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13470: allfiles: reference to hash used to store objects found by parser
13471: codebase: reference to hash used for codebases of java objects found by parser
13472: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13473: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13474: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13475: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13476: context: if 'overwrite', will move the uploaded file from its temporary location to
13477: userfiles to facilitate overwriting a previously uploaded file with same name.
13478: mimetype: reference to scalar to accommodate mime type determined
13479: from File::MMagic if $parser = parse.
13480:
13481: returns either the url of the uploaded file (/uploaded/....) if successful
13482: and /adm/notfound.html if unsuccessful (or an error message if context
13483: was 'overwrite').
13484:
13485:
13486: =item *
13487:
13488: renameuserfile(): renames an existing userfile to a new name
13489:
13490: Args:
13491: docuname: username or courseid of destination for the file
13492: docudom: domain of user/course of destination for the file
13493: old: current file name (including any subdirs under userfiles)
13494: new: desired file name (including any subdirs under userfiles)
13495:
13496: =item *
13497:
13498: mkdiruserfile(): creates a directory is a userfiles dir
13499:
13500: Args:
13501: docuname: username or courseid of destination for the file
13502: docudom: domain of user/course of destination for the file
13503: dir: dir to create (including any subdirs under userfiles)
13504:
13505: =item *
13506:
13507: removeuserfile(): removes a file that exists in userfiles
13508:
13509: Args:
13510: docuname: username or courseid of destination for the file
13511: docudom: domain of user/course of destination for the file
13512: fname: filname to delete (including any subdirs under userfiles)
13513:
13514: =item *
13515:
13516: removeuploadedurl(): convience function for removeuserfile()
13517:
13518: Args:
13519: url: a full /uploaded/... url to delete
13520:
13521: =item *
13522:
13523: get_portfile_permissions():
13524: Args:
13525: domain: domain of user or course contain the portfolio files
13526: user: name of user or num of course contain the portfolio files
13527: Returns:
13528: hashref of a dump of the proper file_permissions.db
13529:
13530:
13531: =item *
13532:
13533: get_access_controls():
13534:
13535: Args:
13536: current_permissions: the hash ref returned from get_portfile_permissions()
13537: group: (optional) the group you want the files associated with
13538: file: (optional) the file you want access info on
13539:
13540: Returns:
13541: a hash (keys are file names) of hashes containing
13542: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13543: values are XML containing access control settings (see below)
13544:
13545: Internal notes:
13546:
13547: access controls are stored in file_permissions.db as key=value pairs.
13548: key -> path to file/file_name\0uniqueID:scope_end_start
13549: where scope -> public,guest,course,group,domains or users.
13550: end -> UNIX time for end of access (0 -> no end date)
13551: start -> UNIX time for start of access
13552:
13553: value -> XML description of access control
13554: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13555: <start></start>
13556: <end></end>
13557:
13558: <password></password> for scope type = guest
13559:
13560: <domain></domain> for scope type = course or group
13561: <number></number>
13562: <roles id="">
13563: <role></role>
13564: <access></access>
13565: <section></section>
13566: <group></group>
13567: </roles>
13568:
13569: <dom></dom> for scope type = domains
13570:
13571: <users> for scope type = users
13572: <user>
13573: <uname></uname>
13574: <udom></udom>
13575: </user>
13576: </users>
13577: </scope>
13578:
13579: Access data is also aggregated for each file in an additional key=value pair:
13580: key -> path to file/file_name\0accesscontrol
13581: value -> reference to hash
13582: hash contains key = value pairs
13583: where key = uniqueID:scope_end_start
13584: value = UNIX time record was last updated
13585:
13586: Used to improve speed of look-ups of access controls for each file.
13587:
13588: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13589:
13590: =item *
13591:
13592: modify_access_controls():
13593:
13594: Modifies access controls for a portfolio file
13595: Args
13596: 1. file name
13597: 2. reference to hash of required changes,
13598: 3. domain
13599: 4. username
13600: where domain,username are the domain of the portfolio owner
13601: (either a user or a course)
13602:
13603: Returns:
13604: 1. result of additions or updates ('ok' or 'error', with error message).
13605: 2. result of deletions ('ok' or 'error', with error message).
13606: 3. reference to hash of any new or updated access controls.
13607: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13608: key = integer (inbound ID)
13609: value = uniqueID
13610:
13611: =item *
13612:
13613: get_timebased_id():
13614:
13615: Attempts to get a unique timestamp-based suffix for use with items added to a
13616: course via the Course Editor (e.g., folders, composite pages,
13617: group bulletin boards).
13618:
13619: Args: (first three required; six others optional)
13620:
13621: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13622: docssequence, or name of group
13623:
13624: 2. keyid (alphanumeric): name of temporary locking key in hash,
13625: e.g., num, boardids
13626:
13627: 3. namespace: name of gdbm file used to store suffixes already assigned;
13628: file will be named nohist_namespace.db
13629:
13630: 4. cdom: domain of course; default is current course domain from %env
13631:
13632: 5. cnum: course number; default is current course number from %env
13633:
13634: 6. idtype: set to concat if an additional digit is to be appended to the
13635: unix timestamp to form the suffix, if the plain timestamp is already
13636: in use. Default is to not do this, but simply increment the unix
13637: timestamp by 1 until a unique key is obtained.
13638:
13639: 7. who: holder of locking key; defaults to user:domain for user.
13640:
13641: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13642: retrying); default is 3.
13643:
13644: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13645:
13646: Returns:
13647:
13648: 1. suffix obtained (numeric)
13649:
13650: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13651:
13652: 3. error: contains (localized) error message if an error occurred.
13653:
13654:
13655: =back
13656:
13657: =head2 HTTP Helper Routines
13658:
13659: =over 4
13660:
13661: =item *
13662:
13663: escape() : unpack non-word characters into CGI-compatible hex codes
13664:
13665: =item *
13666:
13667: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13668:
13669: =back
13670:
13671: =head1 PRIVATE SUBROUTINES
13672:
13673: =head2 Underlying communication routines (Shouldn't call)
13674:
13675: =over 4
13676:
13677: =item *
13678:
13679: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13680:
13681: =item *
13682:
13683: reply() : uses subreply to send a message to remote machine, logs all failures
13684:
13685: =item *
13686:
13687: critical() : passes a critical message to another server; if cannot
13688: get through then place message in connection buffer directory and
13689: returns con_delayed, if incapable of saving message, returns
13690: con_failed
13691:
13692: =item *
13693:
13694: reconlonc() : tries to reconnect lonc client processes.
13695:
13696: =back
13697:
13698: =head2 Resource Access Logging
13699:
13700: =over 4
13701:
13702: =item *
13703:
13704: flushcourselogs() : flush (save) buffer logs and access logs
13705:
13706: =item *
13707:
13708: courselog($what) : save message for course in hash
13709:
13710: =item *
13711:
13712: courseacclog($what) : save message for course using &courselog(). Perform
13713: special processing for specific resource types (problems, exams, quizzes, etc).
13714:
13715: =item *
13716:
13717: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13718: as a PerlChildExitHandler
13719:
13720: =back
13721:
13722: =head2 Other
13723:
13724: =over 4
13725:
13726: =item *
13727:
13728: symblist($mapname,%newhash) : update symbolic storage links
13729:
13730: =back
13731:
13732: =cut
13733:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>